-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpr2markdown.user.js
More file actions
282 lines (243 loc) · 6.58 KB
/
pr2markdown.user.js
File metadata and controls
282 lines (243 loc) · 6.58 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
// ==UserScript==
// @name PR to Markdown
// @namespace http://tampermonkey.net/
// @version 1.0.0
// @description Add a copy button to GitHub and GitLab pull requests to copy PR content as markdown
// @author You
// @match https://github.com/*
// @include https://gitlab.*
// @grant GM_setClipboard
// @run-at document-end
// ==/UserScript==
(function () {
"use strict";
// Logging system
const LOG_LEVELS = {
ERROR: 0,
WARN: 1,
INFO: 2,
DEBUG: 3
};
const CURRENT_LOG_LEVEL = LOG_LEVELS.ERROR; // Default to only show errors
const logger = {
error: (message, ...args) => {
if (CURRENT_LOG_LEVEL >= LOG_LEVELS.ERROR) {
console.error(`PR2Markdown: ${message}`, ...args);
}
},
warn: (message, ...args) => {
if (CURRENT_LOG_LEVEL >= LOG_LEVELS.WARN) {
console.warn(`PR2Markdown: ${message}`, ...args);
}
},
info: (message, ...args) => {
if (CURRENT_LOG_LEVEL >= LOG_LEVELS.INFO) {
console.info(`PR2Markdown: ${message}`, ...args);
}
},
debug: (message, ...args) => {
if (CURRENT_LOG_LEVEL >= LOG_LEVELS.DEBUG) {
console.debug(`PR2Markdown: ${message}`, ...args);
}
}
};
/**
* @typedef {"github" | "gitlab"} Platform
*/
const TITLE_SELECTOR = {
github: "bdi",
gitlab: "h1",
};
/**
* @returns {Platform | null}
*/
function detectPlatform() {
const hostname = window.location.hostname;
const path = window.location.pathname;
if (hostname.includes("github")) {
return "github";
} else if (hostname.includes("gitlab") || path.includes("/-/merge_requests/")) {
return "gitlab";
}
return null;
}
/**
* @param {Platform} platform
* @returns {boolean}
*/
function isOnPRPage(platform) {
const path = window.location.pathname;
switch (platform) {
case "github":
const parts = path.split("/")
return parts[3] == "pull" && /^\d+$/.test(parts[4])
case "gitlab":
return /\/-\/merge_requests\/\d+/.test(path);
}
}
/**
* @param {Platform} platform
* @returns {Element}
* @throws {Error} If the title element cannot be found
*/
function getTitleElement(platform) {
const selector = TITLE_SELECTOR[platform];
const element = document.querySelector(selector);
if (!element) {
throw new Error(`Title element not found for platform: ${platform}`);
}
return element;
}
/**
* @param {Platform} platform
* @returns {Element}
* @throws {Error} If the action section cannot be found
*/
function getActionSection(platform) {
const titleElement = getTitleElement(platform);
let actionSection;
switch (platform) {
case "gitlab":
actionSection = titleElement.nextElementSibling;
break;
case "github":
actionSection = titleElement.parentElement?.nextElementSibling;
break;
}
if (!actionSection) {
throw new Error(`Action section not found for platform: ${platform}`);
}
return actionSection;
}
/**
* @param {Platform} platform
* @returns {string}
*/
function getPRTitle(platform) {
const titleElement = getTitleElement(platform);
return titleElement ? titleElement.textContent.trim() : "Pull Request";
}
/**
* @param {Platform} platform
* @returns {string}
*/
function getPRUrl(platform) {
const pathname = window.location.pathname;
let basePath = "";
if (platform === 'github') {
const parts = pathname.split("/");
basePath = `/${parts[1]}/${parts[2]}/pull/${parts[4]}`;
} else if (platform === 'gitlab') {
basePath = pathname.match(/^(.*\/-\/merge_requests\/\d+)/)[1];
}
return window.location.origin + basePath;
}
/**
* @param {string} title
* @param {string} url
* @returns {string}
*/
function generateMarkdown(title, url) {
return `[${title}](${url})`;
}
/**
* @param {string} text
* @returns {Promise<boolean>}
*/
async function copyToClipboard(text) {
try {
GM_setClipboard(text);
return true;
} catch (err) {
logger.error("Failed to copy to clipboard:", err);
return false;
}
}
/**
* @param {Platform} platform
*/
function getButtonClassNamesByPlatform(platform) {
switch (platform) {
case "github":
return "btn-sm btn";
case "gitlab":
return "gl-button btn btn-md btn-default gl-hidden @sm/panel:gl-inline-flex gl-self-start";
}
}
/**
* @param {Platform} platform
*/
function tryAddCopyButton(platform) {
if (!isOnPRPage(platform)) {
logger.debug("Not on a PR/MR page");
return;
}
logger.debug(`On MR page for platform: ${platform}`);
if (document.getElementById("pr2md-copy-btn")) {
logger.debug("Button already exists")
return;
}
logger.info("Attempting to add copy button");
try {
const titleElement = getTitleElement(platform);
const actionSection = getActionSection(platform);
logger.debug("Found title element:", titleElement);
logger.debug("Found action section:", actionSection);
const button = document.createElement("button");
button.id = "pr2md-copy-btn";
button.className = getButtonClassNamesByPlatform(platform);
button.textContent = "📋";
button.title = "Copy PR as Markdown";
button.addEventListener("click", async function () {
const title = getPRTitle(platform);
const url = getPRUrl(platform);
const markdown = generateMarkdown(title, url);
logger.debug("Generated markdown:", markdown);
const success = await copyToClipboard(markdown);
if (success) {
button.textContent = "✅";
setTimeout(() => {
button.textContent = "📋";
}, 2000);
} else {
button.textContent = "❌";
setTimeout(() => {
button.textContent = "📋";
}, 2000);
}
});
actionSection.insertBefore(button, actionSection.firstChild);
logger.info("Button added successfully");
} catch (error) {
logger.error("Error adding copy button:", error);
}
}
function init() {
logger.info("Userscript loaded on", window.location.href);
const platform = detectPlatform();
logger.debug("Detected platform:", platform);
if (!platform) {
logger.warn("Platform not detected or not supported");
return;
}
try {
// if (document.readyState === "loading") {
// document.addEventListener("DOMContentLoaded", () =>
// tryAddCopyButton(platform),
// );
// } else {
// tryAddCopyButton(platform);
// }
const observer = new MutationObserver(() => {
tryAddCopyButton(platform);
});
observer.observe(document.body, {
childList: true,
subtree: true,
});
} catch (error) {
logger.error("Error during initialization:", error);
}
}
init();
})();