@luutuankiet/clipboard2markdown 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +91 -0
- package/bin/cli.js +161 -0
- package/package.json +59 -0
- package/src/converter.js +91 -0
- package/src/md-to-html.js +182 -0
- package/src/platforms/common.js +298 -0
- package/src/platforms/confluence.js +294 -0
- package/src/platforms/google-chat.js +161 -0
- package/src/platforms/google-docs.js +304 -0
- package/src/platforms/google-sheets.js +239 -0
- package/src/platforms/index.js +40 -0
- package/src/platforms/jira.js +301 -0
- package/src/platforms/slack.js +192 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2014 Euan Goddard
|
|
4
|
+
Copyright 2011-2015 Dom Christie
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
# Clipboard2Markdown
|
|
2
|
+
|
|
3
|
+
**Agent-Ready Markdown from Any Webpage.**
|
|
4
|
+
|
|
5
|
+
A client-side tool that converts complex HTML (tables, code blocks, nested lists) from authenticated platforms into clean Markdown. Perfect for pasting context into AI agents without granting them API access.
|
|
6
|
+
|
|
7
|
+
## Why This Exists
|
|
8
|
+
|
|
9
|
+
Workflow platforms don't let you copy as Markdown — you get rich text. But your AI agents need Markdown. And getting agents to authenticate to Jira/Confluence/Slack is painful or impossible.
|
|
10
|
+
|
|
11
|
+
**The solution:** Copy from any authenticated page → Paste here → Get clean Markdown → Paste to your agent.
|
|
12
|
+
|
|
13
|
+
## Supported Platforms
|
|
14
|
+
|
|
15
|
+
| Platform | Status | Notable Fixes |
|
|
16
|
+
|----------|--------|---------------|
|
|
17
|
+
| Jira | ✅ Full | Code blocks preserve newlines & indentation |
|
|
18
|
+
| Confluence | ✅ Full | Smart links, emoji, lists inside tables |
|
|
19
|
+
| Google Sheets | ✅ Full | Merged cells (rowspan/colspan), pipe escaping |
|
|
20
|
+
| Slack | ✅ Full | Code blocks, list formatting |
|
|
21
|
+
| Notion | 🔜 Planned | — |
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
- **🔄 Turndown.js Engine** — Robust GFM support (tables, task lists, strikethrough)
|
|
26
|
+
- **🧹 Platform Sanitizers** — Pre-process quirky HTML before conversion
|
|
27
|
+
- **🔒 100% Client-Side** — No data leaves your browser
|
|
28
|
+
- **🧪 Automated Testing** — Fixture-based regression suite prevents breakage
|
|
29
|
+
- **⚡ Vite Build System** — Hot reload dev server, optimized production builds
|
|
30
|
+
|
|
31
|
+
## Demo
|
|
32
|
+
|
|
33
|
+
**Live:** https://luutuankiet.github.io/clipboard2markdown/
|
|
34
|
+
|
|
35
|
+

|
|
36
|
+
|
|
37
|
+
## Command Line
|
|
38
|
+
|
|
39
|
+
The same converters ship as the `c2m` CLI:
|
|
40
|
+
|
|
41
|
+
```bash
|
|
42
|
+
npm install -g @luutuankiet/clipboard2markdown
|
|
43
|
+
c2m --help
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
`c2m` reads the clipboard, converts it (HTML to Markdown, or Markdown to HTML), and writes the result back. Clipboard conversion needs macOS.
|
|
47
|
+
|
|
48
|
+
## Development
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
# Install dependencies
|
|
52
|
+
npm install
|
|
53
|
+
|
|
54
|
+
# Start dev server with hot reload
|
|
55
|
+
npm run dev
|
|
56
|
+
|
|
57
|
+
# Run regression tests
|
|
58
|
+
npm test
|
|
59
|
+
|
|
60
|
+
# Build for production
|
|
61
|
+
npm run build
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
### Adding Test Cases
|
|
65
|
+
|
|
66
|
+
No code required — just add files:
|
|
67
|
+
|
|
68
|
+
1. Save raw HTML to `tests/fixtures/{platform}/{case}.html`
|
|
69
|
+
2. Create expected output in `tests/fixtures/{platform}/{case}.md`
|
|
70
|
+
3. Run `npm test` — the runner auto-discovers new pairs
|
|
71
|
+
|
|
72
|
+
**Tip:** Use the "📋 Copy Raw HTML" button in the app to capture clipboard HTML for fixtures.
|
|
73
|
+
|
|
74
|
+
## Credits
|
|
75
|
+
|
|
76
|
+
Forked from [clipboard2markdown](https://github.com/euangoddard/clipboard2markdown) by Euan Goddard.
|
|
77
|
+
|
|
78
|
+
Modernized with:
|
|
79
|
+
- [Turndown.js](https://github.com/mixmark-io/turndown) (replacing to-markdown)
|
|
80
|
+
- [Vite](https://vitejs.dev/) build system
|
|
81
|
+
- Platform-specific sanitizers for Jira, Confluence, Google Sheets, Slack
|
|
82
|
+
|
|
83
|
+
## License
|
|
84
|
+
|
|
85
|
+
[![License][license-image]][license-url]
|
|
86
|
+
|
|
87
|
+
Released under the MIT License. See the [LICENSE](LICENSE) file
|
|
88
|
+
for details.
|
|
89
|
+
|
|
90
|
+
[license-image]: https://img.shields.io/npm/l/markdownlint.svg
|
|
91
|
+
[license-url]: http://opensource.org/licenses/MIT
|
package/bin/cli.js
ADDED
|
@@ -0,0 +1,161 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import { spawnSync } from 'child_process';
|
|
3
|
+
import { writeFileSync, unlinkSync, readFileSync, realpathSync } from 'fs';
|
|
4
|
+
import { tmpdir } from 'os';
|
|
5
|
+
import { join } from 'path';
|
|
6
|
+
import { fileURLToPath } from 'url';
|
|
7
|
+
|
|
8
|
+
const HELP = `c2m - convert the clipboard between rich HTML and Markdown
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
c2m HTML on the clipboard -> Markdown, plain text -> HTML
|
|
12
|
+
c2m --to-md force HTML -> Markdown
|
|
13
|
+
c2m --to-html force Markdown -> HTML
|
|
14
|
+
c2m --help show this help
|
|
15
|
+
c2m --version print the version
|
|
16
|
+
|
|
17
|
+
Clipboard conversion needs macOS (it uses osascript).
|
|
18
|
+
Exit codes: 0 converted, 1 empty clipboard, 2 conversion failed.
|
|
19
|
+
`;
|
|
20
|
+
|
|
21
|
+
// Converters need jsdom's DOM globals; loaded lazily so commands that
|
|
22
|
+
// don't touch the clipboard skip the jsdom startup cost
|
|
23
|
+
async function loadConverters() {
|
|
24
|
+
const { JSDOM } = await import('jsdom');
|
|
25
|
+
const { window: domWindow } = new JSDOM('<!DOCTYPE html>');
|
|
26
|
+
globalThis.DOMParser = domWindow.DOMParser;
|
|
27
|
+
globalThis.NodeFilter = domWindow.NodeFilter;
|
|
28
|
+
const { convert } = await import('../src/converter.js');
|
|
29
|
+
const { convertMdToHtml } = await import('../src/md-to-html.js');
|
|
30
|
+
return { convert, convertMdToHtml };
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function readVersion() {
|
|
34
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
35
|
+
return pkg.version;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
// --- clipboard I/O via JXA (macOS only) ---
|
|
39
|
+
|
|
40
|
+
function readClipboard() {
|
|
41
|
+
const script = `
|
|
42
|
+
ObjC.import("AppKit");
|
|
43
|
+
var pb = $.NSPasteboard.generalPasteboard;
|
|
44
|
+
var types = ObjC.deepUnwrap(pb.types);
|
|
45
|
+
if (types.indexOf("public.html") !== -1) {
|
|
46
|
+
var data = pb.dataForType("public.html");
|
|
47
|
+
var str = $.NSString.alloc.initWithDataEncoding(data, $.NSUTF8StringEncoding);
|
|
48
|
+
JSON.stringify({ type: "html", content: ObjC.unwrap(str) || "" });
|
|
49
|
+
} else {
|
|
50
|
+
var plain = ObjC.unwrap(pb.stringForType("public.utf8-plain-text"));
|
|
51
|
+
JSON.stringify({ type: "text", content: plain || "" });
|
|
52
|
+
}
|
|
53
|
+
`;
|
|
54
|
+
const result = spawnSync('osascript', ['-l', 'JavaScript', '-e', script], {
|
|
55
|
+
encoding: 'utf8',
|
|
56
|
+
maxBuffer: 10 * 1024 * 1024,
|
|
57
|
+
});
|
|
58
|
+
if (result.status !== 0) throw new Error(`Clipboard read failed: ${result.stderr}`);
|
|
59
|
+
return JSON.parse(result.stdout.trim());
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function writeTextToClipboard(text) {
|
|
63
|
+
const tmp = join(tmpdir(), `c2m_${Date.now()}.txt`);
|
|
64
|
+
writeFileSync(tmp, text, 'utf8');
|
|
65
|
+
const script = `
|
|
66
|
+
ObjC.import("AppKit");
|
|
67
|
+
var str = $.NSString.stringWithContentsOfFileEncodingError(${JSON.stringify(tmp)}, $.NSUTF8StringEncoding, null);
|
|
68
|
+
var pb = $.NSPasteboard.generalPasteboard;
|
|
69
|
+
pb.clearContents;
|
|
70
|
+
pb.setStringForType(str, "public.utf8-plain-text");
|
|
71
|
+
`;
|
|
72
|
+
try {
|
|
73
|
+
const result = spawnSync('osascript', ['-l', 'JavaScript', '-e', script], { encoding: 'utf8' });
|
|
74
|
+
if (result.status !== 0) throw new Error(`Clipboard write failed: ${result.stderr}`);
|
|
75
|
+
} finally {
|
|
76
|
+
try { unlinkSync(tmp); } catch {}
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function writeHtmlToClipboard(html) {
|
|
81
|
+
const tmp = join(tmpdir(), `c2m_${Date.now()}.html`);
|
|
82
|
+
writeFileSync(tmp, html, 'utf8');
|
|
83
|
+
const script = `
|
|
84
|
+
ObjC.import("AppKit");
|
|
85
|
+
var str = $.NSString.stringWithContentsOfFileEncodingError(${JSON.stringify(tmp)}, $.NSUTF8StringEncoding, null);
|
|
86
|
+
var htmlData = str.dataUsingEncoding($.NSUTF8StringEncoding);
|
|
87
|
+
var pb = $.NSPasteboard.generalPasteboard;
|
|
88
|
+
pb.clearContents;
|
|
89
|
+
pb.setDataForType(htmlData, "public.html");
|
|
90
|
+
`;
|
|
91
|
+
try {
|
|
92
|
+
const result = spawnSync('osascript', ['-l', 'JavaScript', '-e', script], { encoding: 'utf8' });
|
|
93
|
+
if (result.status !== 0) throw new Error(`Clipboard write failed: ${result.stderr}`);
|
|
94
|
+
} finally {
|
|
95
|
+
try { unlinkSync(tmp); } catch {}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
// --- core logic (exported for testing) ---
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* Determine conversion direction.
|
|
103
|
+
* @param {'html'|'text'} clipboardType - what the pasteboard held
|
|
104
|
+
* @param {boolean} forceToMd - --to-md flag was passed
|
|
105
|
+
* @param {boolean} forceToHtml - --to-html flag was passed
|
|
106
|
+
* @returns {'to-md'|'to-html'}
|
|
107
|
+
*/
|
|
108
|
+
export function detectDirection(clipboardType, forceToMd, forceToHtml) {
|
|
109
|
+
if (forceToMd) return 'to-md';
|
|
110
|
+
if (forceToHtml) return 'to-html';
|
|
111
|
+
return clipboardType === 'html' ? 'to-md' : 'to-html';
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// --- entry point (only runs when executed directly) ---
|
|
115
|
+
|
|
116
|
+
// npm installs bin as a symlink, so compare real paths
|
|
117
|
+
function isEntryPoint() {
|
|
118
|
+
if (!process.argv[1]) return false;
|
|
119
|
+
try {
|
|
120
|
+
return realpathSync(process.argv[1]) === fileURLToPath(import.meta.url);
|
|
121
|
+
} catch {
|
|
122
|
+
return false;
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (isEntryPoint()) {
|
|
127
|
+
const args = process.argv.slice(2);
|
|
128
|
+
|
|
129
|
+
if (args.includes('--help') || args.includes('-h')) {
|
|
130
|
+
process.stdout.write(HELP);
|
|
131
|
+
process.exit(0);
|
|
132
|
+
}
|
|
133
|
+
if (args.includes('--version') || args.includes('-v')) {
|
|
134
|
+
process.stdout.write(`${readVersion()}\n`);
|
|
135
|
+
process.exit(0);
|
|
136
|
+
}
|
|
137
|
+
if (process.platform !== 'darwin') {
|
|
138
|
+
process.stderr.write('c2m: clipboard conversion needs macOS. See c2m --help.\n');
|
|
139
|
+
process.exit(2);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const forceToMd = args.includes('--to-md');
|
|
143
|
+
const forceToHtml = args.includes('--to-html');
|
|
144
|
+
|
|
145
|
+
try {
|
|
146
|
+
const { convert, convertMdToHtml } = await loadConverters();
|
|
147
|
+
const clipboard = readClipboard();
|
|
148
|
+
if (!clipboard.content || !clipboard.content.trim()) {
|
|
149
|
+
process.exit(1); // no convertible content
|
|
150
|
+
}
|
|
151
|
+
const direction = detectDirection(clipboard.type, forceToMd, forceToHtml);
|
|
152
|
+
if (direction === 'to-md') {
|
|
153
|
+
writeTextToClipboard(convert(clipboard.content));
|
|
154
|
+
} else {
|
|
155
|
+
writeHtmlToClipboard(convertMdToHtml(clipboard.content));
|
|
156
|
+
}
|
|
157
|
+
process.exit(0);
|
|
158
|
+
} catch {
|
|
159
|
+
process.exit(2);
|
|
160
|
+
}
|
|
161
|
+
}
|
package/package.json
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@luutuankiet/clipboard2markdown",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Convert rich clipboard HTML from Jira, Confluence, Slack and Google apps into clean Markdown, and back.",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"bin": {
|
|
7
|
+
"c2m": "./bin/cli.js"
|
|
8
|
+
},
|
|
9
|
+
"files": [
|
|
10
|
+
"bin",
|
|
11
|
+
"src",
|
|
12
|
+
"README.md",
|
|
13
|
+
"LICENSE"
|
|
14
|
+
],
|
|
15
|
+
"scripts": {
|
|
16
|
+
"dev": "vite",
|
|
17
|
+
"build": "vite build",
|
|
18
|
+
"preview": "vite preview",
|
|
19
|
+
"test": "vitest run"
|
|
20
|
+
},
|
|
21
|
+
"repository": {
|
|
22
|
+
"type": "git",
|
|
23
|
+
"url": "git+https://github.com/luutuankiet/clipboard2markdown.git"
|
|
24
|
+
},
|
|
25
|
+
"keywords": [
|
|
26
|
+
"clipboard",
|
|
27
|
+
"markdown",
|
|
28
|
+
"html",
|
|
29
|
+
"cli",
|
|
30
|
+
"jira",
|
|
31
|
+
"confluence",
|
|
32
|
+
"slack",
|
|
33
|
+
"agents"
|
|
34
|
+
],
|
|
35
|
+
"author": "luutuankiet",
|
|
36
|
+
"license": "MIT",
|
|
37
|
+
"bugs": {
|
|
38
|
+
"url": "https://github.com/luutuankiet/clipboard2markdown/issues"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://github.com/luutuankiet/clipboard2markdown#readme",
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public"
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=20.0.0"
|
|
46
|
+
},
|
|
47
|
+
"devDependencies": {
|
|
48
|
+
"mermaid": "^11.0.0",
|
|
49
|
+
"vite": "^7.3.1",
|
|
50
|
+
"vitest": "^4.0.18"
|
|
51
|
+
},
|
|
52
|
+
"dependencies": {
|
|
53
|
+
"jsdom": "^28.0.0",
|
|
54
|
+
"marked": "^15.0.0",
|
|
55
|
+
"pako": "^2.1.0",
|
|
56
|
+
"turndown": "^7.2.2",
|
|
57
|
+
"turndown-plugin-gfm": "^1.0.2"
|
|
58
|
+
}
|
|
59
|
+
}
|
package/src/converter.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import TurndownService from 'turndown';
|
|
2
|
+
import { gfm } from 'turndown-plugin-gfm';
|
|
3
|
+
import { addAllRules, sanitize } from './platforms/index.js';
|
|
4
|
+
|
|
5
|
+
// Initialize Turndown with options
|
|
6
|
+
var turndownService = new TurndownService({
|
|
7
|
+
headingStyle: 'atx',
|
|
8
|
+
hr: '---',
|
|
9
|
+
bulletListMarker: '-',
|
|
10
|
+
codeBlockStyle: 'fenced',
|
|
11
|
+
fence: '```',
|
|
12
|
+
emDelimiter: '*',
|
|
13
|
+
strongDelimiter: '**',
|
|
14
|
+
linkStyle: 'inlined'
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
// Use GFM plugin (tables, strikethrough, task lists)
|
|
18
|
+
turndownService.use(gfm);
|
|
19
|
+
|
|
20
|
+
// Load all platform rules (Jira, Slack, Common, etc.)
|
|
21
|
+
addAllRules(turndownService);
|
|
22
|
+
|
|
23
|
+
// ===========================================
|
|
24
|
+
// ESCAPE OVERRIDE (disable underscore escaping)
|
|
25
|
+
// ===========================================
|
|
26
|
+
// Turndown escapes ALL underscores by default (e.g., join_payment_provider → join\_payment\_provider).
|
|
27
|
+
// This is overly aggressive — underscores mid-word don't trigger emphasis in CommonMark.
|
|
28
|
+
// We override the escape method to remove underscore escaping while keeping other escapes.
|
|
29
|
+
// See: https://github.com/mixmark-io/turndown/issues/233
|
|
30
|
+
|
|
31
|
+
var originalEscape = turndownService.escape.bind(turndownService);
|
|
32
|
+
turndownService.escape = function (string) {
|
|
33
|
+
// Apply default escaping, then unescape underscores and dashes
|
|
34
|
+
// Dashes: Turndown escapes `-` at line start (potential list marker), but inside
|
|
35
|
+
// table cells this is overly aggressive — tables can't contain block-level lists.
|
|
36
|
+
// This preserves user's bullet-point formatting like "- item" in cells.
|
|
37
|
+
return originalEscape(string)
|
|
38
|
+
.replace(/\\_/g, '_')
|
|
39
|
+
.replace(/\\-/g, '-');
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// ===========================================
|
|
43
|
+
// PRE-PROCESSING (HTML sanitization)
|
|
44
|
+
// ===========================================
|
|
45
|
+
|
|
46
|
+
var sanitizeHTML = function (html) {
|
|
47
|
+
var doc = new DOMParser().parseFromString(html, 'text/html');
|
|
48
|
+
|
|
49
|
+
// Run all platform sanitizers
|
|
50
|
+
sanitize(doc);
|
|
51
|
+
|
|
52
|
+
return doc.body.innerHTML;
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// ===========================================
|
|
56
|
+
// POST-PROCESSING (smart punctuation cleanup)
|
|
57
|
+
// ===========================================
|
|
58
|
+
|
|
59
|
+
var escape = function (str) {
|
|
60
|
+
return str.replace(/^(#{1,6} \d+)\\\./gm, '$1.') // unescape 1\. in headings — can't be a list there
|
|
61
|
+
.replace(/[\u2018\u2019\u00b4]/g, "'")
|
|
62
|
+
.replace(/[\u201c\u201d\u2033]/g, '"')
|
|
63
|
+
.replace(/[\u2212\u2022\u00b7\u25aa]/g, '-')
|
|
64
|
+
.replace(/[\u2013\u2015]/g, '--')
|
|
65
|
+
.replace(/\u2014/g, '---')
|
|
66
|
+
.replace(/\u2026/g, '...')
|
|
67
|
+
.replace(/\{\{TABLE_BR\}\}/g, '<br>') // Table cell line breaks
|
|
68
|
+
.replace(/\{\{PIPE\}\}/g, '\\|') // Escaped pipes in table cells
|
|
69
|
+
.replace(/\{\{GS_LBRACK\}\}/g, '[') // Google Sheets literals
|
|
70
|
+
.replace(/\{\{GS_RBRACK\}\}/g, ']')
|
|
71
|
+
.replace(/\{\{GS_BKTICK\}\}/g, '`')
|
|
72
|
+
.replace(/\{\{GS_SPACE\}\}/g, ' ') // Google Sheets preserved spaces (indentation)
|
|
73
|
+
.replace(/\{\{GS_TAB\}\}/g, '\t') // Google Sheets preserved tabs
|
|
74
|
+
.replace(/[ ]+\n/g, '\n')
|
|
75
|
+
.replace(/\s*\\\n/g, '\\\n')
|
|
76
|
+
.replace(/\s*\\\n\s*\\\n/g, '\n\n')
|
|
77
|
+
.replace(/\s*\\\n\n/g, '\n\n')
|
|
78
|
+
.replace(/\n-\n/g, '\n')
|
|
79
|
+
.replace(/\n\n\s*\\\n/g, '\n\n')
|
|
80
|
+
.replace(/\n\n\n*/g, '\n\n')
|
|
81
|
+
.replace(/[ ]+$/gm, '')
|
|
82
|
+
.replace(/^\s+|[\s\\]+$/g, '');
|
|
83
|
+
};
|
|
84
|
+
|
|
85
|
+
// ===========================================
|
|
86
|
+
// MAIN CONVERT FUNCTION
|
|
87
|
+
// ===========================================
|
|
88
|
+
|
|
89
|
+
export var convert = function (str) {
|
|
90
|
+
return escape(turndownService.turndown(sanitizeHTML(str)));
|
|
91
|
+
};
|
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Markdown to HTML converter with Google Docs-ready styling.
|
|
3
|
+
*
|
|
4
|
+
* Features:
|
|
5
|
+
* - Tables: Blue header (#c9daf8), 0.5pt borders, auto column widths
|
|
6
|
+
* - XML-like tags: Escaped to literal text (e.g., <current_mode> → <current_mode>)
|
|
7
|
+
* - Whitespace: Preserves spaces after <br> tags
|
|
8
|
+
* - Newlines: Converts \n to <br> in content (not in lists/tables/code)
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { marked } from 'marked';
|
|
12
|
+
|
|
13
|
+
// Configure marked for GFM (tables, strikethrough, etc.)
|
|
14
|
+
marked.setOptions({ gfm: true });
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Fix nested lists for Google Docs compatibility.
|
|
18
|
+
* Google Docs needs nested <ul>/<ol> to be properly separated from parent content.
|
|
19
|
+
*/
|
|
20
|
+
function fixNestedListsForGoogleDocs(html, domParser) {
|
|
21
|
+
var parser = domParser || new DOMParser();
|
|
22
|
+
var doc = parser.parseFromString(html, 'text/html');
|
|
23
|
+
|
|
24
|
+
// Find all nested lists (ul/ol inside li)
|
|
25
|
+
doc.querySelectorAll('li > ul, li > ol').forEach(function (nestedList) {
|
|
26
|
+
// Add display:block and margin to ensure proper rendering
|
|
27
|
+
nestedList.style.display = 'block';
|
|
28
|
+
nestedList.style.marginLeft = '24px';
|
|
29
|
+
nestedList.style.marginTop = '4px';
|
|
30
|
+
nestedList.style.marginBottom = '4px';
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// Ensure all list items have proper display
|
|
34
|
+
doc.querySelectorAll('li').forEach(function (li) {
|
|
35
|
+
li.style.display = 'list-item';
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
// Ensure all lists have proper display
|
|
39
|
+
doc.querySelectorAll('ul, ol').forEach(function (list) {
|
|
40
|
+
list.style.display = 'block';
|
|
41
|
+
if (!list.style.marginLeft && !list.parentElement.matches('li')) {
|
|
42
|
+
// Top-level lists
|
|
43
|
+
list.style.marginLeft = '24px';
|
|
44
|
+
}
|
|
45
|
+
});
|
|
46
|
+
|
|
47
|
+
return doc.body.innerHTML;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Apply Google Docs-compatible inline styles to tables.
|
|
52
|
+
*/
|
|
53
|
+
function applyGoogleDocsTableStyles(html, domParser) {
|
|
54
|
+
var parser = domParser || new DOMParser();
|
|
55
|
+
var doc = parser.parseFromString(html, 'text/html');
|
|
56
|
+
|
|
57
|
+
doc.querySelectorAll('table').forEach(function (table) {
|
|
58
|
+
table.style.borderCollapse = 'collapse';
|
|
59
|
+
table.style.width = '100%';
|
|
60
|
+
|
|
61
|
+
doc.querySelectorAll('th').forEach(function (th) {
|
|
62
|
+
th.style.backgroundColor = '#c9daf8';
|
|
63
|
+
th.style.border = 'solid #000000 0.5pt';
|
|
64
|
+
th.style.padding = '6px 8px';
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
doc.querySelectorAll('td').forEach(function (td) {
|
|
68
|
+
td.style.border = 'solid #000000 0.5pt';
|
|
69
|
+
td.style.padding = '6px 8px';
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
|
|
73
|
+
return doc.body.innerHTML;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Convert spaces after <br> to to preserve indentation.
|
|
78
|
+
*/
|
|
79
|
+
function preserveWhitespaceAfterBr(html) {
|
|
80
|
+
return html.replace(/<br\s*\/?>(\s+)/gi, function (match, spaces) {
|
|
81
|
+
return '<br>' + spaces.split('').map(function () { return ' '; }).join('');
|
|
82
|
+
});
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* Escape XML-like tags that aren't standard HTML.
|
|
87
|
+
* E.g., <current_mode> → <current_mode>
|
|
88
|
+
*/
|
|
89
|
+
function escapeXmlLikeTags(markdown) {
|
|
90
|
+
var standardTags = /^(a|abbr|address|area|article|aside|audio|b|base|bdi|bdo|blockquote|body|br|button|canvas|caption|cite|code|col|colgroup|data|datalist|dd|del|details|dfn|dialog|div|dl|dt|em|embed|fieldset|figcaption|figure|footer|form|h[1-6]|head|header|hgroup|hr|html|i|iframe|img|input|ins|kbd|label|legend|li|link|main|map|mark|menu|meta|meter|nav|noscript|object|ol|optgroup|option|output|p|param|picture|pre|progress|q|rp|rt|ruby|s|samp|script|section|select|slot|small|source|span|strong|style|sub|summary|sup|table|tbody|td|template|textarea|tfoot|th|thead|time|title|tr|track|u|ul|var|video|wbr)$/i;
|
|
91
|
+
|
|
92
|
+
return markdown.replace(/<(\/?)(\w[\w_-]*)([^>]*)>/g, function (match, slash, tagName, rest) {
|
|
93
|
+
if (standardTags.test(tagName)) {
|
|
94
|
+
return match;
|
|
95
|
+
}
|
|
96
|
+
return '<' + slash + tagName + rest + '>';
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Convert newlines to <br> in text content.
|
|
102
|
+
* Skips: <pre>, <code>, <table>, <ol>, <ul>, <li>
|
|
103
|
+
* Skips: whitespace-only text nodes
|
|
104
|
+
*/
|
|
105
|
+
function preserveNewlinesInHtml(html, domParser) {
|
|
106
|
+
var parser = domParser || new DOMParser();
|
|
107
|
+
var doc = parser.parseFromString(html, 'text/html');
|
|
108
|
+
|
|
109
|
+
var walker = doc.createTreeWalker(doc.body, NodeFilter.SHOW_TEXT, null, false);
|
|
110
|
+
var textNodes = [];
|
|
111
|
+
while (walker.nextNode()) {
|
|
112
|
+
textNodes.push(walker.currentNode);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
textNodes.forEach(function (node) {
|
|
116
|
+
var parent = node.parentNode;
|
|
117
|
+
while (parent && parent !== doc.body) {
|
|
118
|
+
var tag = parent.tagName;
|
|
119
|
+
if (tag === 'PRE' || tag === 'CODE' || tag === 'TABLE' ||
|
|
120
|
+
tag === 'OL' || tag === 'UL' || tag === 'LI') {
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
parent = parent.parentNode;
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
var text = node.textContent;
|
|
127
|
+
|
|
128
|
+
if (/^\s*$/.test(text)) {
|
|
129
|
+
return;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (text.indexOf('\n') !== -1) {
|
|
133
|
+
var fragment = doc.createDocumentFragment();
|
|
134
|
+
var parts = text.split('\n');
|
|
135
|
+
parts.forEach(function (part, i) {
|
|
136
|
+
if (i > 0) {
|
|
137
|
+
fragment.appendChild(doc.createElement('br'));
|
|
138
|
+
}
|
|
139
|
+
if (part) {
|
|
140
|
+
fragment.appendChild(doc.createTextNode(part));
|
|
141
|
+
}
|
|
142
|
+
});
|
|
143
|
+
node.parentNode.replaceChild(fragment, node);
|
|
144
|
+
}
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
return doc.body.innerHTML;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Convert Markdown to Google Docs-ready HTML.
|
|
152
|
+
*
|
|
153
|
+
* @param {string} markdown - Input markdown text
|
|
154
|
+
* @param {object} options - Optional: { domParser: DOMParser instance }
|
|
155
|
+
* @returns {string} HTML with inline styles for Google Docs
|
|
156
|
+
*/
|
|
157
|
+
export function convertMdToHtml(markdown, options) {
|
|
158
|
+
var opts = options || {};
|
|
159
|
+
var domParser = opts.domParser;
|
|
160
|
+
|
|
161
|
+
// 1. Escape XML-like tags before parsing
|
|
162
|
+
var escapedMd = escapeXmlLikeTags(markdown);
|
|
163
|
+
// 2. Parse markdown to HTML
|
|
164
|
+
var rawHtml = marked.parse(escapedMd);
|
|
165
|
+
// 3. Preserve newlines (convert \n to <br>)
|
|
166
|
+
var withNewlines = preserveNewlinesInHtml(rawHtml, domParser);
|
|
167
|
+
// 4. Preserve whitespace after <br> tags
|
|
168
|
+
var withPreservedSpaces = preserveWhitespaceAfterBr(withNewlines);
|
|
169
|
+
// 5. Fix nested lists for Google Docs
|
|
170
|
+
var withFixedLists = fixNestedListsForGoogleDocs(withPreservedSpaces, domParser);
|
|
171
|
+
// 6. Apply Google Docs table styling
|
|
172
|
+
return applyGoogleDocsTableStyles(withFixedLists, domParser);
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Also export individual functions for testing
|
|
176
|
+
export {
|
|
177
|
+
applyGoogleDocsTableStyles,
|
|
178
|
+
preserveWhitespaceAfterBr,
|
|
179
|
+
escapeXmlLikeTags,
|
|
180
|
+
preserveNewlinesInHtml,
|
|
181
|
+
fixNestedListsForGoogleDocs
|
|
182
|
+
};
|