@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.
@@ -0,0 +1,161 @@
1
+ // src/platforms/google-chat.js
2
+
3
+ export default {
4
+ rules: [
5
+ {
6
+ name: 'googleChatThreadSeparator',
7
+ filter: function (node) {
8
+ return node.nodeName === 'P' && node.hasAttribute('data-gchat-thread');
9
+ },
10
+ replacement: function (content, node) {
11
+ return '\n\n' + node.getAttribute('data-gchat-thread') + '\n\n';
12
+ }
13
+ },
14
+ {
15
+ name: 'googleChatAnnotation',
16
+ filter: function (node) {
17
+ return node.nodeName === 'P' && node.hasAttribute('data-gchat-annotation');
18
+ },
19
+ replacement: function (content, node) {
20
+ return '\n\n*' + node.getAttribute('data-gchat-annotation') + '*\n\n';
21
+ }
22
+ }
23
+ ],
24
+ sanitizer: function (doc) {
25
+ var body = doc.body || doc.documentElement;
26
+ if (!body) return;
27
+
28
+ // Guard: only run on Google Chat-like fragments
29
+ var hasChatMarkers = !!(
30
+ doc.querySelector('span[data-member-id]') ||
31
+ doc.querySelector('img[src*="chat.google.com/u/0/api/get_attachment_url"]') ||
32
+ doc.querySelector('[aria-label="External"]')
33
+ );
34
+ if (!hasChatMarkers) return;
35
+
36
+ var cleanText = function (text) {
37
+ return (text || '')
38
+ .replace(/\u200B/g, '')
39
+ .replace(/\s+/g, ' ')
40
+ .trim();
41
+ };
42
+
43
+ var hasDirectBr = function (node) {
44
+ for (var i = 0; i < node.childNodes.length; i++) {
45
+ if (node.childNodes[i].nodeName === 'BR') return true;
46
+ }
47
+ return false;
48
+ };
49
+
50
+ var parseHeaderMeta = function (headerEl) {
51
+ var author = '';
52
+ var authorCandidates = headerEl.querySelectorAll('span[role="presentation"] > span');
53
+ for (var i = 0; i < authorCandidates.length; i++) {
54
+ var candidate = cleanText(authorCandidates[i].textContent);
55
+ if (!candidate) continue;
56
+ if (candidate === ',') continue;
57
+ if (/^edited$/i.test(candidate)) continue;
58
+ if (/\d{1,2}:\d{2}/.test(candidate)) continue;
59
+ if (candidate.toLowerCase() === 'domain_disabled') continue;
60
+ author = candidate;
61
+ break;
62
+ }
63
+
64
+ if (!author) {
65
+ var fallback = headerEl.querySelector('span[role="presentation"]');
66
+ if (fallback) {
67
+ var fallbackText = cleanText(fallback.textContent);
68
+ if (fallbackText && !/\d{1,2}:\d{2}/.test(fallbackText)) {
69
+ author = fallbackText;
70
+ }
71
+ }
72
+ }
73
+
74
+ var timestamp = '';
75
+ headerEl.querySelectorAll('span[role="presentation"]').forEach(function (span) {
76
+ var text = cleanText(span.textContent);
77
+ if (/\d{1,2}:\d{2}/.test(text)) {
78
+ timestamp = text;
79
+ }
80
+ });
81
+
82
+ if (!author || !timestamp) return null;
83
+
84
+ return {
85
+ author: author,
86
+ timestamp: timestamp,
87
+ edited: /\bedited\b/i.test(cleanText(headerEl.textContent)),
88
+ external: !!headerEl.querySelector('[aria-label="External"]')
89
+ };
90
+ };
91
+
92
+ var headers = [];
93
+ doc.querySelectorAll('div').forEach(function (div) {
94
+ if (!hasDirectBr(div)) return;
95
+ var meta = parseHeaderMeta(div);
96
+ if (!meta) return;
97
+
98
+ var next = div.nextElementSibling;
99
+ if (!next || next.nodeName !== 'DIV') return;
100
+
101
+ headers.push({ element: div, meta: meta });
102
+ });
103
+
104
+ if (headers.length === 0) return;
105
+
106
+ var rootIndex = 0;
107
+ var replyIndex = 0;
108
+
109
+ headers.forEach(function (item, index) {
110
+ var headerEl = item.element;
111
+ var meta = item.meta;
112
+ var headerText = cleanText(headerEl.textContent);
113
+
114
+ var hasUnreadMarker = /(^|\s)\d+\s+unread\b/i.test(headerText);
115
+ var firstChild = headerEl.firstElementChild;
116
+ var hasLeadingDivider = !!(
117
+ firstChild &&
118
+ firstChild.nodeName === 'DIV' &&
119
+ cleanText(firstChild.textContent) === ''
120
+ );
121
+ var hasDatePrefix = /^[A-Za-z]{3}\s+\d{1,2},\s+\d{1,2}:\d{2}/.test(meta.timestamp);
122
+
123
+ var startsNewRoot = index === 0 || hasUnreadMarker || hasLeadingDivider;
124
+ if (!startsNewRoot && hasDatePrefix && replyIndex > 0) {
125
+ startsNewRoot = true;
126
+ }
127
+
128
+ if (startsNewRoot) {
129
+ rootIndex += 1;
130
+ replyIndex = 0;
131
+
132
+ var separatorEl = doc.createElement('p');
133
+ separatorEl.setAttribute('data-gchat-thread', '=== Root Chat ' + rootIndex + ' ===');
134
+ separatorEl.textContent = '\u200B';
135
+ headerEl.parentNode.insertBefore(separatorEl, headerEl);
136
+ } else {
137
+ replyIndex += 1;
138
+ }
139
+
140
+ var roleLabel = replyIndex === 0
141
+ ? '[root ' + rootIndex + ']'
142
+ : '[reply ' + replyIndex + ' to root ' + rootIndex + ']';
143
+
144
+ var parts = [roleLabel];
145
+ if (meta.author) parts.push(meta.author);
146
+ if (meta.external) parts.push('(external)');
147
+ if (meta.timestamp) {
148
+ parts.push('-');
149
+ parts.push(meta.timestamp);
150
+ }
151
+ if (meta.edited) parts.push('(edited)');
152
+
153
+ var annotationEl = doc.createElement('p');
154
+ annotationEl.setAttribute('data-gchat-annotation', parts.join(' '));
155
+ annotationEl.textContent = '\u200B';
156
+
157
+ headerEl.parentNode.insertBefore(annotationEl, headerEl);
158
+ headerEl.remove();
159
+ });
160
+ }
161
+ };
@@ -0,0 +1,304 @@
1
+ // src/platforms/google-docs.js
2
+ // Handles content copied from Google Docs
3
+
4
+ function isRobotoMono(node) {
5
+ if (node.nodeName !== 'SPAN') return false;
6
+ var ff = node.style && node.style.fontFamily;
7
+ return !!(ff && ff.toLowerCase().indexOf('roboto mono') !== -1);
8
+ }
9
+
10
+ // Returns true if every non-empty piece of content in <p> is a Roboto Mono span.
11
+ // Used to detect "this paragraph is a line of code".
12
+ function isCodeParagraph(p) {
13
+ if (p.nodeName !== 'P') return false;
14
+ var hasCode = false;
15
+ var nodes = p.childNodes;
16
+ for (var i = 0; i < nodes.length; i++) {
17
+ var node = nodes[i];
18
+ if (node.nodeType === 3) { // TEXT_NODE
19
+ if (node.textContent.replace(/[\u00a0\s]/g, '')) return false; // bare non-empty text
20
+ } else if (node.nodeType === 1) { // ELEMENT_NODE
21
+ if (node.nodeName === 'BR') continue;
22
+ if (isRobotoMono(node)) {
23
+ hasCode = true;
24
+ } else if (node.textContent.replace(/[\u00a0\s]/g, '')) {
25
+ return false; // non-empty non-code element
26
+ }
27
+ }
28
+ }
29
+ return hasCode;
30
+ }
31
+
32
+ export default {
33
+ rules: [],
34
+ sanitizer: function (doc) {
35
+ if (!doc.querySelector('[id*="docs-internal-guid"]')) return;
36
+
37
+ // -------------------------------------------------------
38
+ // 1. Merge consecutive Roboto Mono paragraphs → <pre><code>
39
+ //
40
+ // Google Docs represents pasted code as a series of <p> elements
41
+ // where every span uses font-family:'Roboto Mono'. Standalone <br>
42
+ // siblings between code paragraphs become blank lines in the block.
43
+ // -------------------------------------------------------
44
+ var visited = [];
45
+ doc.querySelectorAll('p').forEach(function (p) {
46
+ if (visited.indexOf(p) !== -1 || !isCodeParagraph(p)) return;
47
+
48
+ var groupNodes = [];
49
+ var curr = p;
50
+
51
+ while (curr) {
52
+ if (curr.nodeType === 1 && curr.nodeName === 'P' && isCodeParagraph(curr)) {
53
+ groupNodes.push({ blank: false, node: curr });
54
+ visited.push(curr);
55
+ curr = curr.nextSibling;
56
+ } else if (curr.nodeType === 1 && curr.nodeName === 'BR') {
57
+ // Include standalone <br> only if the next real sibling is still code
58
+ var peek = curr.nextSibling;
59
+ while (peek && peek.nodeType === 3 && !peek.textContent.trim()) peek = peek.nextSibling;
60
+ if (peek && peek.nodeType === 1 && peek.nodeName === 'P' && isCodeParagraph(peek)) {
61
+ groupNodes.push({ blank: true, node: curr });
62
+ curr = curr.nextSibling;
63
+ } else {
64
+ break;
65
+ }
66
+ } else if (curr.nodeType === 3 && !curr.textContent.trim()) {
67
+ curr = curr.nextSibling; // skip whitespace text nodes
68
+ } else {
69
+ break;
70
+ }
71
+ }
72
+
73
+ if (groupNodes.length === 0) return;
74
+
75
+ // A single monospace paragraph is usually inline code-like content
76
+ // (file paths, identifiers, table/list cell values), not a fenced block.
77
+ // Require 2+ monospace lines before promoting to <pre><code>.
78
+ var codeLineCount = groupNodes.reduce(function (count, item) {
79
+ return count + (item.blank ? 0 : 1);
80
+ }, 0);
81
+ if (codeLineCount < 2) return;
82
+
83
+ var lines = groupNodes.map(function (item) {
84
+ return item.blank ? '' : item.node.textContent.replace(/\u00a0/g, ' ');
85
+ });
86
+ // Trim trailing blank lines
87
+ while (lines.length > 0 && lines[lines.length - 1].trim() === '') lines.pop();
88
+
89
+ var pre = doc.createElement('pre');
90
+ var code = doc.createElement('code');
91
+ code.textContent = lines.join('\n');
92
+ pre.appendChild(code);
93
+
94
+ groupNodes[0].node.parentNode.insertBefore(pre, groupNodes[0].node);
95
+ groupNodes.forEach(function (item) {
96
+ if (item.node.parentNode) item.node.parentNode.removeChild(item.node);
97
+ });
98
+ });
99
+
100
+ // -------------------------------------------------------
101
+ // 2. Convert remaining Roboto Mono spans → <code> (inline code)
102
+ // -------------------------------------------------------
103
+ doc.querySelectorAll('span').forEach(function (span) {
104
+ if (!span.parentNode) return;
105
+ if (!isRobotoMono(span)) return;
106
+ var code = doc.createElement('code');
107
+ code.textContent = span.textContent;
108
+ span.parentNode.replaceChild(code, span);
109
+ });
110
+
111
+ // -------------------------------------------------------
112
+ // 3. Convert bold/italic spans → semantic <strong>/<em>
113
+ //
114
+ // Skip spans inside headings — headings are already bold by nature;
115
+ // wrapping in ** adds noise and breaks the `1\. ` period fix.
116
+ // -------------------------------------------------------
117
+ doc.querySelectorAll('span').forEach(function (span) {
118
+ if (!span.parentNode) return;
119
+
120
+ var ancestor = span.parentNode;
121
+ while (ancestor && ancestor.nodeName !== 'BODY') {
122
+ if (/^H[1-6]$/.test(ancestor.nodeName)) return; // inside heading, skip
123
+ ancestor = ancestor.parentNode;
124
+ }
125
+
126
+ var fw = span.style && span.style.fontWeight;
127
+ var fi = span.style && span.style.fontStyle;
128
+ var isBold = fw === '700' || fw === 'bold';
129
+ var isItalic = fi === 'italic';
130
+ if (!isBold && !isItalic) return;
131
+
132
+ var wrapper;
133
+ if (isBold && isItalic) {
134
+ var em = doc.createElement('em');
135
+ while (span.firstChild) em.appendChild(span.firstChild);
136
+ wrapper = doc.createElement('strong');
137
+ wrapper.appendChild(em);
138
+ } else if (isBold) {
139
+ wrapper = doc.createElement('strong');
140
+ while (span.firstChild) wrapper.appendChild(span.firstChild);
141
+ } else {
142
+ wrapper = doc.createElement('em');
143
+ while (span.firstChild) wrapper.appendChild(span.firstChild);
144
+ }
145
+ span.parentNode.replaceChild(wrapper, span);
146
+ });
147
+
148
+ // -------------------------------------------------------
149
+ // 4. Unwrap remaining plain spans (color/size/whitespace wrappers)
150
+ // -------------------------------------------------------
151
+ doc.querySelectorAll('span').forEach(function (span) {
152
+ if (!span.parentNode) return;
153
+ while (span.firstChild) span.parentNode.insertBefore(span.firstChild, span);
154
+ span.remove();
155
+ });
156
+
157
+ // -------------------------------------------------------
158
+ // 5. Unwrap <p> elements inside table cells — prevents spurious newlines
159
+ // -------------------------------------------------------
160
+ doc.querySelectorAll('td p, th p').forEach(function (p) {
161
+ while (p.firstChild) p.parentNode.insertBefore(p.firstChild, p);
162
+ p.remove();
163
+ });
164
+
165
+ // -------------------------------------------------------
166
+ // 6. Strip empty trailing rows (Google Docs blank placeholder rows)
167
+ // -------------------------------------------------------
168
+ doc.querySelectorAll('table tr').forEach(function (row) {
169
+ var cells = row.querySelectorAll('td, th');
170
+ var isEmpty = Array.prototype.every.call(cells, function (cell) {
171
+ return cell.textContent.trim() === '';
172
+ });
173
+ if (isEmpty && cells.length > 0) row.remove();
174
+ });
175
+
176
+ // -------------------------------------------------------
177
+ // 7. Promote first <tbody> row → <thead> with <th> elements
178
+ //
179
+ // Turndown's GFM plugin only converts <table> to markdown when
180
+ // <thead> exists. Google Docs emits <tbody>-only tables.
181
+ // -------------------------------------------------------
182
+ doc.querySelectorAll('table').forEach(function (table) {
183
+ if (table.querySelector('thead')) return;
184
+ var tbody = table.querySelector('tbody');
185
+ if (!tbody) return;
186
+ var firstRow = tbody.querySelector('tr');
187
+ if (!firstRow) return;
188
+
189
+ firstRow.querySelectorAll('td').forEach(function (td) {
190
+ var th = doc.createElement('th');
191
+ while (td.firstChild) th.appendChild(td.firstChild);
192
+ td.parentNode.replaceChild(th, td);
193
+ });
194
+
195
+ var thead = doc.createElement('thead');
196
+ table.insertBefore(thead, tbody);
197
+ thead.appendChild(firstRow);
198
+ });
199
+
200
+ // -------------------------------------------------------
201
+ // 8. Strip colgroup and noisy table attributes
202
+ // -------------------------------------------------------
203
+ doc.querySelectorAll('colgroup').forEach(function (cg) { cg.remove(); });
204
+ doc.querySelectorAll('table, tr, td, th').forEach(function (el) {
205
+ el.removeAttribute('style');
206
+ el.removeAttribute('dir');
207
+ el.removeAttribute('align');
208
+ });
209
+ doc.querySelectorAll('table').forEach(function (t) {
210
+ t.removeAttribute('cellspacing');
211
+ t.removeAttribute('cellpadding');
212
+ });
213
+
214
+ // -------------------------------------------------------
215
+ // 9. Strip id/dir/style from headings (docs-internal-guid noise)
216
+ // -------------------------------------------------------
217
+ doc.querySelectorAll('h1,h2,h3,h4,h5,h6').forEach(function (h) {
218
+ h.removeAttribute('id');
219
+ h.removeAttribute('dir');
220
+ h.removeAttribute('style');
221
+ });
222
+
223
+ // -------------------------------------------------------
224
+ // 10. Repair Google Docs nested list structure
225
+ //
226
+ // Docs often emits nested bullets as sibling lists instead of
227
+ // nesting them under the previous <li>:
228
+ // <ul><li>Parent</li></ul><ul><li aria-level="2">Child</li></ul>
229
+ // This flattens indentation in markdown output.
230
+ // -------------------------------------------------------
231
+ doc.querySelectorAll('ul, ol').forEach(function (list) {
232
+ if (!list.parentNode || list.parentNode.nodeName === 'LI') return;
233
+
234
+ var firstLi = null;
235
+ for (var i = 0; i < list.children.length; i++) {
236
+ if (list.children[i].nodeName === 'LI') {
237
+ firstLi = list.children[i];
238
+ break;
239
+ }
240
+ }
241
+ if (!firstLi) return;
242
+
243
+ var level = parseInt(firstLi.getAttribute('aria-level') || '1', 10);
244
+ if (!(level > 1)) return;
245
+
246
+ var prev = list.previousSibling;
247
+ while (prev) {
248
+ if (prev.nodeType === 3 && !prev.textContent.trim()) {
249
+ prev = prev.previousSibling;
250
+ continue;
251
+ }
252
+ if (prev.nodeType === 1 && prev.nodeName === 'BR') {
253
+ prev = prev.previousSibling;
254
+ continue;
255
+ }
256
+ break;
257
+ }
258
+
259
+ if (!prev || prev.nodeType !== 1) return;
260
+
261
+ var hostLi = null;
262
+ if (prev.nodeName === 'LI') {
263
+ hostLi = prev;
264
+ } else if (prev.nodeName === 'UL' || prev.nodeName === 'OL') {
265
+ for (var j = prev.children.length - 1; j >= 0; j--) {
266
+ if (prev.children[j].nodeName === 'LI') {
267
+ hostLi = prev.children[j];
268
+ break;
269
+ }
270
+ }
271
+ }
272
+
273
+ if (hostLi) hostLi.appendChild(list);
274
+ });
275
+
276
+ // -------------------------------------------------------
277
+ // 11. Unwrap list-item paragraphs to avoid loose list spacing
278
+ //
279
+ // Google Docs wraps list text in <li><p>...</p></li>, which makes
280
+ // Turndown emit extra blank lines between bullets. Flatten to
281
+ // <li>text ...</li> so nested lists keep proper hierarchy.
282
+ // -------------------------------------------------------
283
+ doc.querySelectorAll('li > p').forEach(function (p) {
284
+ if (!p.parentNode) return;
285
+ while (p.firstChild) p.parentNode.insertBefore(p.firstChild, p);
286
+ p.remove();
287
+ });
288
+
289
+ // -------------------------------------------------------
290
+ // 12. Strip dir/style/aria attrs from paragraphs and list elements
291
+ // -------------------------------------------------------
292
+ doc.querySelectorAll('p, li, ul, ol').forEach(function (el) {
293
+ el.removeAttribute('dir');
294
+ el.removeAttribute('style');
295
+ el.removeAttribute('aria-level');
296
+ el.removeAttribute('role');
297
+ });
298
+
299
+ // -------------------------------------------------------
300
+ // 13. Remove injected <style> tags
301
+ // -------------------------------------------------------
302
+ doc.querySelectorAll('style').forEach(function (s) { s.remove(); });
303
+ }
304
+ };