|
| 1 | +import { Notification, showDialog, Dialog } from '@jupyterlab/apputils'; |
| 2 | +import { Widget } from '@lumino/widgets'; |
| 3 | + |
| 4 | +const MAX_VISIBLE_CHARS = 140; |
| 5 | +const VIEW_DETAILS_LABEL = 'View details'; |
| 6 | + |
| 7 | +function toPlainText(value: unknown): string { |
| 8 | + try { |
| 9 | + return typeof value === 'string' ? value : JSON.stringify(value, null, 2); |
| 10 | + } catch { |
| 11 | + return String(value ?? ''); |
| 12 | + } |
| 13 | +} |
| 14 | + |
| 15 | +function createViewDetailsAction(fullMessage: string, dialogTitle = 'Details'): Notification.IAction { |
| 16 | + return { |
| 17 | + label: VIEW_DETAILS_LABEL, |
| 18 | + caption: 'Show full message', |
| 19 | + callback: async () => { |
| 20 | + const dialogBody = new Widget(); |
| 21 | + dialogBody.addClass('xircuits-notification-details'); |
| 22 | + |
| 23 | + const pre = document.createElement('pre'); |
| 24 | + pre.textContent = fullMessage; |
| 25 | + dialogBody.node.appendChild(pre); |
| 26 | + |
| 27 | + const copyButton = Dialog.createButton({ label: 'Copy' }); |
| 28 | + const closeButton = Dialog.okButton({ label: 'Close' }); |
| 29 | + |
| 30 | + const result = await showDialog({ |
| 31 | + title: dialogTitle, |
| 32 | + body: dialogBody, |
| 33 | + buttons: [copyButton, closeButton] |
| 34 | + }); |
| 35 | + |
| 36 | + if (result.button.label === 'Copy') { |
| 37 | + await navigator.clipboard.writeText(fullMessage); |
| 38 | + } |
| 39 | + } |
| 40 | + }; |
| 41 | +} |
| 42 | + |
| 43 | +function ensureViewDetailsAction( |
| 44 | + messageText: string, |
| 45 | + options: any = {}, |
| 46 | + title?: string |
| 47 | +): any { |
| 48 | + if (messageText.length <= MAX_VISIBLE_CHARS) return options; |
| 49 | + const actions = [...(options.actions ?? [])]; |
| 50 | + if (!actions.some((a: any) => a?.label === VIEW_DETAILS_LABEL)) { |
| 51 | + actions.push(createViewDetailsAction(messageText, title)); |
| 52 | + } |
| 53 | + return { ...options, actions }; |
| 54 | +} |
| 55 | + |
| 56 | +export function augmentNotifications(): void { |
| 57 | + const NotificationObj: any = Notification as any; |
| 58 | + if (NotificationObj.__xircuitsAugmented) return; |
| 59 | + |
| 60 | + const wrap = (method: 'error' | 'warning' | 'info' | 'success') => { |
| 61 | + const original = NotificationObj[method]?.bind(Notification); |
| 62 | + if (!original) return; |
| 63 | + |
| 64 | + NotificationObj[method] = (...args: any[]) => { |
| 65 | + const [rawMessage, rawOptions] = args; |
| 66 | + const text = toPlainText(rawMessage); |
| 67 | + const options = ensureViewDetailsAction(text, rawOptions); |
| 68 | + return original(text, options); |
| 69 | + }; |
| 70 | + }; |
| 71 | + |
| 72 | + ['error', 'warning', 'info', 'success'].forEach(wrap); |
| 73 | + NotificationObj.__xircuitsAugmented = true; |
| 74 | +} |
0 commit comments