forked from wso2/vscode-extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinject-theme.js
More file actions
executable file
·396 lines (352 loc) · 15.9 KB
/
inject-theme.js
File metadata and controls
executable file
·396 lines (352 loc) · 15.9 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
#!/usr/bin/env node
/**
* Injects custom CSS theme into the MCP Inspector client's index.html
* This modifies the npm package directly so the theme is applied when served
*/
const fs = require('fs');
const path = require('path');
// Target the actual npm package location that gets served
const INDEX_HTML_PATH = path.join(
__dirname,
'..',
'node_modules',
'@modelcontextprotocol',
'inspector',
'client',
'dist',
'index.html'
);
// Placeholder CSS - will be replaced by dynamic theme injection at runtime
const CUSTOM_CSS = ` <!-- Dynamic Theme Injection Placeholder -->
<script>
// === Clipboard paste bridge ===
// Cross-origin iframes inside VS Code webviews cannot use the Clipboard API
// (microsoft/vscode#129178, #182642). We intercept Cmd/Ctrl+V over paste-capable
// fields and ask the parent webview for the clipboard text, then insert it ourselves.
(function () {
var pasteRequestId = 0;
var pendingPasteRequests = new Map();
function isPasteableInput(el) {
if (!el) return false;
if (el.isContentEditable) return true;
if (el.tagName === 'TEXTAREA') return !el.disabled && !el.readOnly;
if (el.tagName === 'INPUT') {
var t = (el.type || 'text').toLowerCase();
var pasteableTypes = ['text', 'search', 'url', 'email', 'password', 'tel', 'number'];
return pasteableTypes.indexOf(t) !== -1 && !el.disabled && !el.readOnly;
}
return false;
}
function insertTextAt(el, text) {
if (!el || !text) return;
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
var start = el.selectionStart != null ? el.selectionStart : el.value.length;
var end = el.selectionEnd != null ? el.selectionEnd : el.value.length;
var nativeSetter = Object.getOwnPropertyDescriptor(
el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype,
'value'
).set;
// Use the native setter so React's onChange fires (React tracks the prior value)
nativeSetter.call(el, el.value.slice(0, start) + text + el.value.slice(end));
var caret = start + text.length;
el.setSelectionRange(caret, caret);
el.dispatchEvent(new Event('input', { bubbles: true }));
} else if (el.isContentEditable) {
document.execCommand('insertText', false, text);
}
}
function selectAll(el) {
if (!el) return;
if (el.tagName === 'INPUT' || el.tagName === 'TEXTAREA') {
try { el.select(); } catch (_) { /* ignore */ }
} else if (el.isContentEditable) {
var range = document.createRange();
range.selectNodeContents(el);
var sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
}
}
function getSelectionContext() {
var ae = document.activeElement;
if (ae && (ae.tagName === 'INPUT' || ae.tagName === 'TEXTAREA')) {
var s = ae.selectionStart;
var en = ae.selectionEnd;
if (s != null && en != null && s !== en) {
return { text: ae.value.slice(s, en), inInput: true, el: ae, start: s, end: en };
}
}
var sel = window.getSelection();
var selText = sel ? sel.toString() : '';
if (selText) return { text: selText, inInput: false };
return null;
}
function deleteSelection(ctx) {
if (!ctx) return;
if (ctx.inInput && ctx.el && !ctx.el.disabled && !ctx.el.readOnly) {
var nativeSetter = Object.getOwnPropertyDescriptor(
ctx.el.tagName === 'TEXTAREA' ? window.HTMLTextAreaElement.prototype : window.HTMLInputElement.prototype,
'value'
).set;
nativeSetter.call(ctx.el, ctx.el.value.slice(0, ctx.start) + ctx.el.value.slice(ctx.end));
ctx.el.setSelectionRange(ctx.start, ctx.start);
ctx.el.dispatchEvent(new Event('input', { bubbles: true }));
} else {
try { document.execCommand('delete'); } catch (_) { /* ignore */ }
}
}
document.addEventListener('keydown', function (e) {
if (!(e.metaKey || e.ctrlKey)) return;
if (e.shiftKey || e.altKey) return;
var k = e.key && e.key.toLowerCase();
// Copy / Cut: work on any selection in the document (form field or UI text).
if (k === 'c' || k === 'x') {
var ctx = getSelectionContext();
if (!ctx || !ctx.text) return;
e.preventDefault();
e.stopPropagation();
if (typeof window.__mcpInspectorWriteClipboard === 'function') {
window.__mcpInspectorWriteClipboard(ctx.text).catch(function () { /* swallow */ });
}
if (k === 'x') deleteSelection(ctx);
return;
}
// Paste / Select-all: only meaningful when a paste-capable field is focused.
var ae = document.activeElement;
if (!isPasteableInput(ae)) return;
if (k === 'v') {
// Prevent the (broken) native paste path; do our own via the parent webview.
e.preventDefault();
e.stopPropagation();
var id = ++pasteRequestId;
pendingPasteRequests.set(id, ae);
window.parent.postMessage({ type: 'mcp-inspector-request-paste', requestId: id }, '*');
} else if (k === 'a') {
// VS Code's webview swallows the native Select All; do it manually.
e.preventDefault();
e.stopPropagation();
selectAll(ae);
}
}, true);
// Bridge for writing to the system clipboard (copy direction).
// Cross-origin iframes can't use navigator.clipboard.writeText() either,
// so we ask the extension host to do it via vscode.env.clipboard.writeText().
var copyRequestId = 0;
var pendingCopyRequests = new Map();
window.__mcpInspectorWriteClipboard = function (text) {
return new Promise(function (resolve, reject) {
var id = ++copyRequestId;
pendingCopyRequests.set(id, { resolve: resolve, reject: reject });
window.parent.postMessage({
type: 'mcp-inspector-request-clipboard-write',
requestId: id,
text: text == null ? '' : String(text)
}, '*');
setTimeout(function () {
if (pendingCopyRequests.has(id)) {
pendingCopyRequests.delete(id);
reject(new Error('Clipboard write timed out'));
}
}, 5000);
});
};
window.addEventListener('message', function (e) {
var msg = e.data;
if (!msg) return;
if (msg.type === 'mcp-inspector-paste-response') {
var target = pendingPasteRequests.get(msg.requestId);
pendingPasteRequests.delete(msg.requestId);
if (target && msg.text) insertTextAt(target, msg.text);
} else if (msg.type === 'mcp-inspector-clipboard-write-result') {
var pending = pendingCopyRequests.get(msg.requestId);
if (!pending) return;
pendingCopyRequests.delete(msg.requestId);
if (msg.ok) pending.resolve();
else pending.reject(new Error(msg.error || 'Clipboard write failed'));
}
});
})();
// Function to convert color (hex or rgb/rgba) to HSL format
function colorToHsl(color) {
let r, g, b;
// Handle HEX format (#ffffff or #fff)
if (color.startsWith('#')) {
let hex = color.replace('#', '');
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
r = parseInt(hex.substr(0, 2), 16) / 255;
g = parseInt(hex.substr(2, 2), 16) / 255;
b = parseInt(hex.substr(4, 2), 16) / 255;
}
// Handle rgb() and rgba() formats
else if (color.startsWith('rgb')) {
const match = color.match(/rgba?\\((\\d+),\\s*(\\d+),\\s*(\\d+)/);
if (!match) {
return '0 0% 50%';
}
r = parseInt(match[1]) / 255;
g = parseInt(match[2]) / 255;
b = parseInt(match[3]) / 255;
} else {
return '0 0% 50%';
}
const max = Math.max(r, g, b);
const min = Math.min(r, g, b);
let h, s, l = (max + min) / 2;
if (max === min) {
h = s = 0;
} else {
const d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch (max) {
case r: h = ((g - b) / d + (g < b ? 6 : 0)) / 6; break;
case g: h = ((b - r) / d + 2) / 6; break;
case b: h = ((r - g) / d + 4) / 6; break;
}
}
return Math.round(h * 360) + ' ' + Math.round(s * 100) + '% ' + Math.round(l * 100) + '%';
}
// Fallback to execCommand when webview blocks navigator.clipboard.writeText.
(function patchClipboard() {
const execCopy = (text) => {
const ta = document.createElement('textarea');
ta.value = text == null ? '' : String(text);
ta.setAttribute('readonly', '');
ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';
document.body.appendChild(ta);
const sel = document.getSelection();
const prevRange = sel && sel.rangeCount > 0 ? sel.getRangeAt(0) : null;
ta.select();
ta.setSelectionRange(0, ta.value.length);
let ok = false;
try { ok = document.execCommand('copy'); } catch (_) { ok = false; }
document.body.removeChild(ta);
if (prevRange && sel) { sel.removeAllRanges(); sel.addRange(prevRange); }
return ok;
};
const native = navigator.clipboard && navigator.clipboard.writeText
? navigator.clipboard.writeText.bind(navigator.clipboard)
: null;
const writeText = async (text) => {
if (native) {
try { return await native(text); } catch (_) {}
}
// VS Code webview path: ask the extension host to write the clipboard.
if (typeof window.__mcpInspectorWriteClipboard === 'function') {
try { await window.__mcpInspectorWriteClipboard(text); return; } catch (_) {}
}
if (execCopy(text)) return;
throw new Error('Clipboard copy failed');
};
if (!navigator.clipboard) {
Object.defineProperty(navigator, 'clipboard', { value: {}, configurable: true });
}
try { navigator.clipboard.writeText = writeText; } catch (_) {}
})();
let themeStyleElement = null;
// Listen for theme color messages from parent
window.addEventListener('message', (event) => {
if (event.source !== window.parent) return;
const message = event.data;
if (message && message.type === 'vscode-theme-colors') {
// Sync the inspector's dark-mode class with VSCode's theme so its
// own theme tokens (:root for light, .dark for dark) align with our overrides.
if (typeof message.isDark === 'boolean') {
document.documentElement.classList.toggle('dark', message.isDark);
}
// Remove old theme style if exists
if (themeStyleElement) {
themeStyleElement.remove();
}
// Create new style element
themeStyleElement = document.createElement('style');
themeStyleElement.id = 'vscode-theme-override';
themeStyleElement.textContent = \`
/* Override both :root and .dark to ensure VSCode theme is always applied */
:root,
.dark {
/* Main colors */
--background: \${colorToHsl(message.colors.background)} !important;
--foreground: \${colorToHsl(message.colors.foreground)} !important;
/* Card colors */
--card: \${colorToHsl(message.colors.card)} !important;
--card-foreground: \${colorToHsl(message.colors.cardForeground)} !important;
/* Popover colors */
--popover: \${colorToHsl(message.colors.popover)} !important;
--popover-foreground: \${colorToHsl(message.colors.popoverForeground)} !important;
/* Primary colors */
--primary: \${colorToHsl(message.colors.primary)} !important;
--primary-foreground: \${colorToHsl(message.colors.primaryForeground)} !important;
/* Secondary colors */
--secondary: \${colorToHsl(message.colors.secondary)} !important;
--secondary-foreground: \${colorToHsl(message.colors.secondaryForeground)} !important;
/* Muted colors */
--muted: \${colorToHsl(message.colors.muted)} !important;
--muted-foreground: \${colorToHsl(message.colors.mutedForeground)} !important;
/* Accent colors */
--accent: \${colorToHsl(message.colors.accent)} !important;
--accent-foreground: \${colorToHsl(message.colors.accentForeground)} !important;
/* Destructive colors */
--destructive: \${colorToHsl(message.colors.destructive)} !important;
--destructive-foreground: \${colorToHsl(message.colors.destructiveForeground)} !important;
/* Input/Border/Ring */
--border: \${colorToHsl(message.colors.border)} !important;
--input: \${colorToHsl(message.colors.input)} !important;
--ring: \${colorToHsl(message.colors.ring)} !important;
}
/* Override body styles */
body {
background-color: \${message.colors.bodyBg} !important;
color: \${message.colors.bodyColor} !important;
}
/* Override the hardcoded :root colors */
:root {
color: \${message.colors.bodyColor} !important;
background-color: \${message.colors.bodyBg} !important;
}
/* Override @media (prefers-color-scheme: light) */
@media (prefers-color-scheme: light) {
:root {
color: \${message.colors.bodyColor} !important;
background-color: \${message.colors.bodyBg} !important;
}
}
/* Hide the inspector's theme switcher — VSCode owns the theme. */
#theme-select { display: none !important; }
\`;
document.head.appendChild(themeStyleElement);
}
});
</script>`;
function injectTheme() {
console.log('🎨 Injecting custom CSS theme into MCP Inspector npm package...');
// Check if index.html exists
if (!fs.existsSync(INDEX_HTML_PATH)) {
console.error(` ❌ Error: index.html not found at ${INDEX_HTML_PATH}`);
console.error(' 💡 Try running: pnpm install');
process.exit(1);
}
// Read index.html
let html = fs.readFileSync(INDEX_HTML_PATH, 'utf8');
// If a previous injection exists, strip it so we can replace with the latest version.
const existing = /\s*<!-- Dynamic Theme Injection Placeholder -->[\s\S]*?<\/script>\s*/;
if (existing.test(html)) {
html = html.replace(existing, '\n ');
console.log(' ♻️ Replacing existing theme injection...');
}
// Inject custom CSS before </head> tag
html = html.replace('</head>', `${CUSTOM_CSS}\n </head>`);
// Write back to file
fs.writeFileSync(INDEX_HTML_PATH, html, 'utf8');
console.log(' ✅ Custom CSS theme injected successfully!');
console.log(` 📍 Location: ${INDEX_HTML_PATH}`);
console.log(' 💡 Theme will be applied when MCP Inspector client server starts');
}
// Run the injection
try {
injectTheme();
} catch (error) {
console.error(' ❌ Failed to inject theme:', error.message);
process.exit(1);
}