-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
636 lines (558 loc) · 22.3 KB
/
script.js
File metadata and controls
636 lines (558 loc) · 22.3 KB
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
// 全局变量
let currentOutput = '';
let currentFormat = '';
// DOM元素
const markdownInput = document.getElementById('markdownInput');
const fileInput = document.getElementById('fileInput');
const pasteBtn = document.getElementById('pasteBtn');
const clearBtn = document.getElementById('clearBtn');
const exampleBtn = document.getElementById('exampleBtn');
const convertTxtBtn = document.getElementById('convertTxt');
const convertWordBtn = document.getElementById('convertWord');
const convertHtmlBtn = document.getElementById('convertHtml');
const outputPreview = document.getElementById('outputPreview');
const outputText = document.getElementById('outputText');
const downloadBtn = document.getElementById('downloadBtn');
const copyBtn = document.getElementById('copyBtn');
const actionButtonsGroup = document.getElementById('actionButtonsGroup');
// 粘贴功能
pasteBtn.addEventListener('click', async () => {
try {
const text = await navigator.clipboard.readText();
markdownInput.value = text;
markdownInput.focus();
showNotification('✅ 已粘贴剪贴板内容');
} catch (err) {
showNotification('❌ 无法读取剪贴板,请手动粘贴', 'error');
}
});
// 文件上传
fileInput.addEventListener('change', (e) => {
const file = e.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = (event) => {
markdownInput.value = event.target.result;
showNotification('✅ 文件已加载');
};
reader.readAsText(file);
}
});
// 示例内容功能
exampleBtn.addEventListener('click', () => {
const exampleMarkdown = `# AI生成内容示例
这是一个**Markdown格式**的示例内容,展示了AI工具生成的内容格式。
## 主要特点
- 支持多种格式转换
- 一键去除Markdown语法
- 保留格式转换为Word文档
### 使用场景
1. **内容分享**:将AI生成的内容分享到微信、QQ
2. **文档制作**:转换为Word文档,更专业
3. **格式整理**:去除语法,只保留纯文本
> 这是一个引用示例,展示引用格式的转换效果。
**粗体文本** 和 *斜体文本* 都会被正确处理。
\`代码片段\` 也会被正确转换。
---
现在试试转换这个示例内容,看看效果如何!`;
markdownInput.value = exampleMarkdown;
markdownInput.focus();
showNotification('✅ 已加载示例内容');
});
// 清空功能
clearBtn.addEventListener('click', () => {
markdownInput.value = '';
outputText.value = '';
outputPreview.innerHTML = '';
outputText.classList.remove('active');
outputPreview.classList.remove('active');
actionButtonsGroup.style.display = 'none';
currentOutput = '';
currentFormat = '';
showNotification('🗑️ 已清空');
});
// Markdown转TXT(去除所有语法,纯文本)
convertTxtBtn.addEventListener('click', () => {
const markdown = markdownInput.value.trim();
if (!markdown) {
showNotification('⚠️ 请输入Markdown内容', 'error');
return;
}
try {
// 去除Markdown语法的函数
let text = markdown;
// 移除代码块
text = text.replace(/```[\s\S]*?```/g, '');
text = text.replace(/`[^`]*`/g, (match) => {
return match.replace(/`/g, '');
});
// 移除链接 [text](url) -> text
text = text.replace(/\[([^\]]+)\]\([^\)]+\)/g, '$1');
// 移除图片
text = text.replace(/!\[([^\]]*)\]\([^\)]+\)/g, '');
// 移除粗体、斜体标记
text = text.replace(/\*\*([^*]+)\*\*/g, '$1');
text = text.replace(/\*([^*]+)\*/g, '$1');
text = text.replace(/__([^_]+)__/g, '$1');
text = text.replace(/_([^_]+)_/g, '$1');
// 移除删除线
text = text.replace(/~~([^~]+)~~/g, '$1');
// 移除标题标记
text = text.replace(/^#{1,6}\s+/gm, '');
// 移除列表标记
text = text.replace(/^[\s]*[-*+]\s+/gm, '');
text = text.replace(/^[\s]*\d+\.\s+/gm, '');
// 移除引用标记
text = text.replace(/^>\s+/gm, '');
// 移除水平线
text = text.replace(/^[-*_]{3,}$/gm, '');
// 移除表格标记
text = text.replace(/\|/g, ' ');
text = text.replace(/^[\s]*:?-+:?[\s]*$/gm, '');
// 清理多余空行(保留最多两个连续空行)
text = text.replace(/\n{3,}/g, '\n\n');
// 去除首尾空白
text = text.trim();
currentOutput = text;
currentFormat = 'txt';
outputText.value = text;
outputText.classList.add('active');
outputPreview.classList.remove('active');
actionButtonsGroup.style.display = 'flex';
showNotification('✅ 已转换为TXT格式');
} catch (error) {
showNotification('❌ 转换失败: ' + error.message, 'error');
}
});
// Markdown转Word
convertWordBtn.addEventListener('click', async () => {
const markdown = markdownInput.value.trim();
if (!markdown) {
showNotification('⚠️ 请输入Markdown内容', 'error');
return;
}
try {
// 使用marked解析Markdown为HTML
const html = marked.parse(markdown);
// 创建Word文档 - 使用docx库
const { Document, Packer, Paragraph, TextRun, HeadingLevel } = docx;
const doc = new Document({
sections: [{
properties: {},
children: []
}]
});
// 解析HTML并转换为Word格式
const parser = new DOMParser();
const htmlDoc = parser.parseFromString(html, 'text/html');
const body = htmlDoc.body;
const paragraphs = [];
// 递归处理节点
function processNode(node) {
if (node.nodeType === Node.TEXT_NODE) {
const text = node.textContent.trim();
if (text) {
return new TextRun(text);
}
return null;
}
if (node.nodeType === Node.ELEMENT_NODE) {
const tagName = node.tagName.toLowerCase();
const children = [];
// 收集所有子节点
Array.from(node.childNodes).forEach(child => {
const result = processNode(child);
if (result) {
if (Array.isArray(result)) {
children.push(...result);
} else {
children.push(result);
}
}
});
if (tagName === 'h1') {
return new Paragraph({
children: children.length > 0 ? children : [new TextRun(node.textContent)],
heading: HeadingLevel.HEADING_1,
spacing: { after: 200 }
});
} else if (tagName === 'h2') {
return new Paragraph({
children: children.length > 0 ? children : [new TextRun(node.textContent)],
heading: HeadingLevel.HEADING_2,
spacing: { after: 200 }
});
} else if (tagName === 'h3') {
return new Paragraph({
children: children.length > 0 ? children : [new TextRun(node.textContent)],
heading: HeadingLevel.HEADING_3,
spacing: { after: 200 }
});
} else if (tagName === 'p') {
if (children.length > 0) {
return new Paragraph({
children: children,
spacing: { after: 100 }
});
}
} else if (tagName === 'strong' || tagName === 'b') {
return new TextRun({
text: node.textContent,
bold: true
});
} else if (tagName === 'em' || tagName === 'i') {
return new TextRun({
text: node.textContent,
italics: true
});
} else if (tagName === 'ul') {
const items = Array.from(node.querySelectorAll('li'));
return items.map(item => {
return new Paragraph({
text: item.textContent.trim(),
bullet: { level: 0 },
spacing: { after: 50 }
});
});
} else if (tagName === 'ol') {
const items = Array.from(node.querySelectorAll('li'));
return items.map((item, index) => {
return new Paragraph({
text: item.textContent.trim(),
numbering: { reference: 'default-numbering', level: 0 },
spacing: { after: 50 }
});
});
} else if (tagName === 'li') {
return new Paragraph({
text: node.textContent.trim(),
bullet: { level: 0 },
spacing: { after: 50 }
});
} else if (tagName === 'br') {
return new Paragraph({ text: '' });
} else if (children.length > 0) {
return children;
}
}
return null;
}
// 处理body的所有直接子节点
Array.from(body.childNodes).forEach(node => {
const result = processNode(node);
if (result) {
if (Array.isArray(result)) {
paragraphs.push(...result);
} else {
paragraphs.push(result);
}
}
});
// 如果没有段落,至少添加一个
if (paragraphs.length === 0) {
paragraphs.push(new Paragraph({
children: [new TextRun(markdown)]
}));
}
doc.sections[0].children = paragraphs;
// 生成Word文档
const blob = await Packer.toBlob(doc);
currentOutput = blob;
currentFormat = 'docx';
// 显示预览(转换为纯文本预览)
const previewText = markdown.replace(/[#*`\[\]()]/g, '').trim();
outputText.value = previewText.substring(0, 500) + (previewText.length > 500 ? '...' : '');
outputText.classList.add('active');
outputPreview.classList.remove('active');
actionButtonsGroup.style.display = 'flex';
showNotification('✅ 已转换为Word格式');
} catch (error) {
console.error('Word转换错误:', error);
// 如果docx库失败,使用HTML转Word的备用方案
try {
const html = marked.parse(markdown);
// 创建HTML格式的Word文档(.doc格式,Word可以打开)
const wordHtml = `<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
body { font-family: "Microsoft YaHei", Arial, sans-serif; line-height: 1.6; }
h1, h2, h3 { color: #333; margin-top: 20px; }
</style>
</head>
<body>
${html}
</body>
</html>`;
const blob = new Blob(['\ufeff' + wordHtml], {
type: 'application/msword;charset=utf-8'
});
currentOutput = blob;
currentFormat = 'doc';
outputText.value = markdown.replace(/[#*`\[\]()]/g, '').trim().substring(0, 500);
outputText.classList.add('active');
outputPreview.classList.remove('active');
actionButtonsGroup.style.display = 'flex';
showNotification('✅ 已转换为Word格式(.doc)');
} catch (fallbackError) {
showNotification('❌ Word转换失败: ' + error.message, 'error');
}
}
});
// Markdown转HTML
convertHtmlBtn.addEventListener('click', () => {
const markdown = markdownInput.value.trim();
if (!markdown) {
showNotification('⚠️ 请输入Markdown内容', 'error');
return;
}
try {
const html = marked.parse(markdown);
currentOutput = html;
currentFormat = 'html';
outputPreview.innerHTML = html;
outputPreview.classList.add('active');
outputText.classList.remove('active');
actionButtonsGroup.style.display = 'flex';
showNotification('✅ 已转换为HTML格式');
} catch (error) {
showNotification('❌ HTML转换失败: ' + error.message, 'error');
}
});
// 兼容移动端的下载函数
function downloadFile(blob, fileName) {
// 检测是否为移动设备
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
// 创建 blob URL
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = fileName;
link.style.display = 'none';
// iOS Safari 特殊处理
if (isIOS) {
// iOS 不支持直接下载,在新窗口打开
// 对于文本文件,可以尝试复制到剪贴板
if (blob.type.includes('text/plain') || blob.type.includes('text/html')) {
// 尝试读取内容并复制到剪贴板
blob.text().then(text => {
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text).then(() => {
showNotification('✅ 内容已复制到剪贴板,可粘贴到其他应用', 'success');
URL.revokeObjectURL(url);
}).catch(() => {
// 如果复制失败,在新窗口打开
window.open(url, '_blank');
setTimeout(() => URL.revokeObjectURL(url), 1000);
});
} else {
// 不支持剪贴板,在新窗口打开
window.open(url, '_blank');
setTimeout(() => URL.revokeObjectURL(url), 1000);
}
}).catch(() => {
window.open(url, '_blank');
setTimeout(() => URL.revokeObjectURL(url), 1000);
});
return;
} else {
// 非文本文件,在新窗口打开
window.open(url, '_blank');
setTimeout(() => URL.revokeObjectURL(url), 1000);
return;
}
}
// 移动端(非iOS)和桌面端使用链接下载
if (isMobile) {
// Android 等移动浏览器
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
URL.revokeObjectURL(url);
}, 200);
} else {
// 桌面端优先使用 FileSaver.js
try {
if (typeof saveAs !== 'undefined') {
saveAs(blob, fileName);
// FileSaver 会自动处理,但我们还是清理 URL
setTimeout(() => URL.revokeObjectURL(url), 1000);
} else {
// FileSaver 未加载,使用链接方式
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
URL.revokeObjectURL(url);
}, 200);
}
} catch (error) {
// 如果 FileSaver 失败,回退到链接方式
document.body.appendChild(link);
link.click();
setTimeout(() => {
document.body.removeChild(link);
URL.revokeObjectURL(url);
}, 200);
}
}
}
// 复制功能
copyBtn.addEventListener('click', async () => {
if (!currentOutput) {
showNotification('⚠️ 没有可复制的内容', 'error');
return;
}
try {
let textToCopy = '';
if (currentFormat === 'txt') {
// TXT格式:直接复制文本
textToCopy = currentOutput;
} else if (currentFormat === 'html') {
// HTML格式:复制HTML代码
textToCopy = currentOutput;
} else if (currentFormat === 'docx' || currentFormat === 'doc') {
// Word格式:复制预览文本
textToCopy = outputText.value;
if (!textToCopy || textToCopy.includes('...')) {
// 如果没有预览文本,尝试从markdown生成
const markdown = markdownInput.value.trim();
textToCopy = markdown.replace(/[#*`\[\]()]/g, '').trim();
}
}
if (!textToCopy) {
showNotification('⚠️ 没有可复制的内容', 'error');
return;
}
// 使用现代Clipboard API
if (navigator.clipboard && navigator.clipboard.writeText) {
await navigator.clipboard.writeText(textToCopy);
showNotification('✅ 已复制到剪贴板');
} else {
// 降级方案:使用传统方法
const textarea = document.createElement('textarea');
textarea.value = textToCopy;
textarea.style.position = 'fixed';
textarea.style.opacity = '0';
document.body.appendChild(textarea);
textarea.select();
try {
document.execCommand('copy');
showNotification('✅ 已复制到剪贴板');
} catch (err) {
showNotification('❌ 复制失败,请手动选择复制', 'error');
}
document.body.removeChild(textarea);
}
} catch (error) {
console.error('复制错误:', error);
showNotification('❌ 复制失败: ' + error.message, 'error');
}
});
// 下载功能
downloadBtn.addEventListener('click', () => {
if (!currentOutput) {
showNotification('⚠️ 没有可下载的内容', 'error');
return;
}
try {
const markdown = markdownInput.value.trim();
// 生成更安全的文件名
let fileName = markdown.substring(0, 30).replace(/[^\w\s\u4e00-\u9fa5]/g, '').trim() || 'converted';
// 移除多余空格
fileName = fileName.replace(/\s+/g, '_');
let blob;
let fileExtension;
if (currentFormat === 'txt') {
blob = new Blob([currentOutput], { type: 'text/plain;charset=utf-8' });
fileExtension = 'txt';
} else if (currentFormat === 'docx') {
blob = currentOutput; // 已经是 Blob
fileExtension = 'docx';
} else if (currentFormat === 'doc') {
blob = currentOutput; // 已经是 Blob
fileExtension = 'doc';
} else if (currentFormat === 'html') {
blob = new Blob([currentOutput], { type: 'text/html;charset=utf-8' });
fileExtension = 'html';
} else {
throw new Error('未知的格式类型');
}
const fullFileName = `${fileName}.${fileExtension}`;
// iOS 设备会显示特殊提示,其他设备显示下载成功
const isIOS = /iPhone|iPad|iPod/i.test(navigator.userAgent);
if (!isIOS || (!blob.type.includes('text/plain') && !blob.type.includes('text/html'))) {
// 非iOS或非文本文件,显示下载提示
downloadFile(blob, fullFileName);
showNotification('✅ 文件已下载');
} else {
// iOS文本文件,会在downloadFile中显示复制提示
downloadFile(blob, fullFileName);
}
} catch (error) {
console.error('下载错误:', error);
showNotification('❌ 下载失败: ' + error.message, 'error');
}
});
// 通知函数
function showNotification(message, type = 'success') {
// 创建通知元素
const notification = document.createElement('div');
notification.textContent = message;
// 苹果风格颜色
const colors = {
success: {
bg: 'rgba(52, 199, 89, 0.95)',
text: '#FFFFFF'
},
error: {
bg: 'rgba(255, 59, 48, 0.95)',
text: '#FFFFFF'
}
};
const color = colors[type] || colors.success;
// 检测是否为移动设备
const isMobile = window.innerWidth <= 768;
notification.style.cssText = `
position: fixed;
top: ${isMobile ? '16px' : '32px'};
${isMobile ? 'left: 16px; right: 16px;' : 'right: 32px;'}
background: ${color.bg};
backdrop-filter: blur(40px) saturate(200%);
-webkit-backdrop-filter: blur(40px) saturate(200%);
color: ${color.text};
padding: ${isMobile ? '14px 20px' : '16px 24px'};
border-radius: ${isMobile ? '14px' : '16px'};
box-shadow:
0 12px 32px rgba(0, 0, 0, 0.2),
0 4px 12px rgba(0, 0, 0, 0.15),
0 1px 3px rgba(0, 0, 0, 0.1),
inset 0 1px 0 rgba(255, 255, 255, 0.2);
z-index: 10000;
animation: slideIn 0.5s cubic-bezier(0.33, 1, 0.68, 1);
font-weight: 500;
font-size: ${isMobile ? '15px' : '15px'};
font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', sans-serif;
letter-spacing: -0.2px;
border: 0.5px solid rgba(255, 255, 255, 0.25);
max-width: ${isMobile ? '100%' : '360px'};
word-wrap: break-word;
line-height: 1.5;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
touch-action: manipulation;
`;
document.body.appendChild(notification);
setTimeout(() => {
notification.style.animation = 'slideOut 0.4s cubic-bezier(0.33, 1, 0.68, 1)';
setTimeout(() => {
if (document.body.contains(notification)) {
document.body.removeChild(notification);
}
}, 400);
}, 3500);
}
// CSS动画已在style.css中定义