-
Notifications
You must be signed in to change notification settings - Fork 147
Expand file tree
/
Copy pathmenuItems.js
More file actions
406 lines (385 loc) · 13.7 KB
/
menuItems.js
File metadata and controls
406 lines (385 loc) · 13.7 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
397
398
399
400
401
402
403
404
405
406
import TableGrid from '../toolbar/TableGrid.vue';
import AIWriter from '../toolbar/AIWriter.vue';
import TableActions from '../toolbar/TableActions.vue';
import LinkInput from '../toolbar/LinkInput.vue';
import CellBackgroundPicker from './CellBackgroundPicker.vue';
import { TEXTS, ICONS, TRIGGERS } from './constants.js';
import { isTrackedChangeActionAllowed } from '@extensions/track-changes/permission-helpers.js';
import { readClipboardRaw } from '../../core/utilities/clipboardUtils.js';
import { handleClipboardPaste } from '../../core/InputRule.js';
/**
* Build a minimal clipboard event-like object so ProseMirror paste hooks
* can access text/html and text/plain data.
* @param {{ html?: string, text?: string }} clipboard
* @returns {{ clipboardData: { getData: (type: string) => string } }}
*/
const createPasteEventShim = (clipboard) => {
const html = clipboard?.html || '';
const text = clipboard?.text || '';
return {
type: 'paste',
preventDefault: () => {},
stopPropagation: () => {},
clipboardData: {
getData: (type) => {
if (type === 'text/html') return html;
if (type === 'text/plain') return text;
return '';
},
},
};
};
/**
* Check if a module is enabled based on editor options
* This is used for hiding menu items based on module availability
*
* Example for future use cases
* case 'comments':
* return !!editorOptions?.isCommentsEnabled;
*
* @param {Object} editorOptions - Editor options
* @param {string} moduleName - Name of the module to check (e.g. 'ai')
* @returns {boolean} Whether the module is enabled
*/
const isModuleEnabled = (editorOptions, moduleName) => {
switch (moduleName) {
case 'ai':
return !!editorOptions?.isAiEnabled;
default:
return true;
}
};
/**
* Universal menu item filtering function using showWhen logic
* @param {Object} item - Menu item to check
* @param {Object} context - Editor context with all necessary information
* @returns {boolean} Whether the item should be shown
*/
const shouldShowItem = (item, context) => {
// If item has a custom showWhen function, use it
if (typeof item.showWhen === 'function') {
try {
return Boolean(item.showWhen(context));
} catch (error) {
console.warn('[ContextMenu] showWhen error for item', item.id, ':', error);
return false;
}
}
// Items without showWhen are always shown
return true;
};
const canPerformTrackedChange = (context, action) => {
if (!context?.editor) return true;
return isTrackedChangeActionAllowed({
editor: context.editor,
action,
trackedChanges: context.trackedChanges ?? [],
});
};
/**
* Get menu sections based on context (trigger, selection, node, etc)
* @param {Object} context - { editor, selectedText, pos, node, event, trigger }
* @param {Array} customItems - Optional custom menu items from configuration
* @param {boolean} includeDefaultItems - Whether to include default items
* @returns {Array} Array of menu sections
*/
export function getItems(context, customItems = [], includeDefaultItems = true) {
const { selectedText, editor } = context;
if (editor?.options?.slashMenuConfig && !editor?.options?.contextMenuConfig) {
console.warn('[ContextMenu] editor.options.slashMenuConfig is deprecated. Use contextMenuConfig instead.');
}
const menuConfig = editor?.options?.contextMenuConfig ?? editor?.options?.slashMenuConfig;
if (arguments.length === 1 && menuConfig) {
customItems = menuConfig.items || menuConfig.customItems || [];
includeDefaultItems = menuConfig.includeDefaultItems !== false;
}
// Enhanced context object - ensure we have all necessary computed properties
const enhancedContext = {
...context,
isInTable: context.isInTable ?? false,
isInSectionNode: context.isInSectionNode ?? false,
isTrackedChange: context.isTrackedChange ?? false,
isCellSelection: context.isCellSelection ?? false,
tableSelectionKind: context.tableSelectionKind ?? null,
clipboardContent: context.clipboardContent ?? { hasContent: false },
selectedText: context.selectedText ?? '',
hasSelection: context.hasSelection ?? Boolean(context.selectedText),
};
// Define default sections with isDefault flag
const defaultSections = [
{
id: 'ai-content',
isDefault: true,
items: [
{
id: 'insert-text',
label: selectedText ? TEXTS.replaceText : TEXTS.insertText,
icon: ICONS.ai,
component: AIWriter,
isDefault: true,
action: (editor) => {
if (editor?.commands && typeof editor.commands?.insertAiMark === 'function') {
editor.commands.insertAiMark();
}
},
showWhen: (context) => {
const { trigger } = context;
const allowedTriggers = [TRIGGERS.slash, TRIGGERS.click];
return allowedTriggers.includes(trigger) && isModuleEnabled(context.editor?.options, 'ai');
},
},
],
},
{
id: 'track-changes',
isDefault: true,
items: [
{
id: 'track-changes-accept',
icon: ICONS.trackChangesAccept,
label: TEXTS.trackChangesAccept,
isDefault: true,
action: (editor, context) => {
if (context?.trackedChangeId) {
editor.commands.acceptTrackedChangeById(context.trackedChangeId);
} else {
editor.commands.acceptTrackedChangeBySelection();
}
},
showWhen: (context) => {
const { trigger, isTrackedChange } = context;
return trigger === TRIGGERS.click && isTrackedChange && canPerformTrackedChange(context, 'accept');
},
},
{
id: 'track-changes-reject',
label: TEXTS.trackChangesReject,
icon: ICONS.trackChangesReject,
isDefault: true,
action: (editor, context) => {
if (context?.trackedChangeId) {
editor.commands.rejectTrackedChangeById(context.trackedChangeId);
} else {
editor.commands.rejectTrackedChangeOnSelection();
}
},
showWhen: (context) => {
const { trigger, isTrackedChange } = context;
return trigger === TRIGGERS.click && isTrackedChange && canPerformTrackedChange(context, 'reject');
},
},
],
},
{
id: 'document-sections',
isDefault: true,
items: [
{
id: 'insert-document-section',
label: TEXTS.createDocumentSection,
icon: ICONS.addDocumentSection,
isDefault: true,
action: (editor) => {
editor.commands.createDocumentSection();
},
// TODO: Temporarily disabled - restore original: `return trigger === TRIGGERS.click;`
showWhen: () => {
return false;
},
},
{
id: 'remove-section',
label: TEXTS.removeDocumentSection,
icon: ICONS.removeDocumentSection,
isDefault: true,
action: (editor) => {
editor.commands.removeSectionAtSelection();
},
showWhen: (context) => {
const { trigger, isInSectionNode } = context;
return trigger === TRIGGERS.click && isInSectionNode;
},
},
],
},
{
id: 'general',
isDefault: true,
items: [
{
id: 'insert-link',
label: TEXTS.insertLink,
icon: ICONS.link,
component: LinkInput,
isDefault: true,
showWhen: (context) => {
const { trigger } = context;
return trigger === TRIGGERS.click;
},
},
{
id: 'insert-table',
label: TEXTS.insertTable,
icon: ICONS.table,
component: TableGrid,
isDefault: true,
showWhen: (context) => {
const { trigger, isInTable } = context;
const allowedTriggers = [TRIGGERS.slash, TRIGGERS.click];
return allowedTriggers.includes(trigger) && !isInTable;
},
},
{
id: 'edit-table',
label: TEXTS.editTable,
icon: ICONS.table,
component: TableActions,
isDefault: true,
showWhen: (context) => {
const { trigger, isInTable } = context;
const allowedTriggers = [TRIGGERS.slash, TRIGGERS.click];
return allowedTriggers.includes(trigger) && isInTable;
},
},
{
id: 'cell-background',
label: TEXTS.cellBackground,
icon: ICONS.cellBackground,
component: CellBackgroundPicker,
isDefault: true,
showWhen: (context) => {
return context.trigger === TRIGGERS.click && (context.isCellSelection || context.isInTable);
},
},
],
},
{
id: 'clipboard',
isDefault: true,
items: [
{
id: 'cut',
label: TEXTS.cut,
icon: ICONS.cut,
isDefault: true,
action: (editor) => {
editor.focus?.();
document.execCommand('cut');
},
showWhen: (context) => {
const { trigger, selectedText } = context;
return trigger === TRIGGERS.click && selectedText;
},
},
{
id: 'copy',
label: TEXTS.copy,
icon: ICONS.copy,
isDefault: true,
action: (editor) => {
editor.focus?.();
document.execCommand('copy');
},
showWhen: (context) => {
const { trigger, selectedText } = context;
return trigger === TRIGGERS.click && selectedText;
},
},
{
id: 'paste',
label: TEXTS.paste,
icon: ICONS.paste,
isDefault: true,
action: async (editor) => {
const { view } = editor ?? {};
if (!view) return;
// Save the current selection before focusing. When the context menu
// is open, its hidden search input holds focus, so the PM editor's
// contenteditable is blurred. A raw `view.dom.focus()` would restart
// ProseMirror's DOMObserver which reads the stale browser selection
// (collapsed at the document start) and overwrites the PM state.
// Using `view.focus()` (ProseMirror-aware) prevents this by writing
// the PM selection to the DOM before restarting the observer. We also
// save/restore as a safety net against async drift during clipboard reads.
const savedFrom = view.state.selection.from;
const savedTo = view.state.selection.to;
view.focus();
const { html, text } = await readClipboardRaw();
// Restore selection after the async gap — ProseMirror's DOMObserver
// may have overwritten the PM selection with a stale DOM selection
// (collapsed at document start) while awaiting the clipboard read.
if (view.state?.doc?.content) {
const { tr, doc } = view.state;
const maxPos = doc.content.size;
const safeFrom = Math.min(savedFrom, maxPos);
const safeTo = Math.min(savedTo, maxPos);
const SelectionType = view.state.selection.constructor;
if (typeof SelectionType.create === 'function') {
view.dispatch(tr.setSelection(SelectionType.create(doc, safeFrom, safeTo)));
}
}
const handled = html ? handleClipboardPaste({ editor, view }, html) : false;
if (!handled) {
const pasteEvent = createPasteEventShim({ html, text });
if (html && typeof view.pasteHTML === 'function') {
view.pasteHTML(html, pasteEvent);
return;
}
if (text && typeof view.pasteText === 'function') {
view.pasteText(text, pasteEvent);
return;
}
if (text && editor.commands?.insertContent) {
editor.commands.insertContent(text, { contentType: 'text' });
}
}
},
showWhen: (context) => {
const { trigger } = context;
const allowedTriggers = [TRIGGERS.click, TRIGGERS.slash];
return allowedTriggers.includes(trigger);
},
},
],
},
];
let allSections = [];
if (includeDefaultItems) {
allSections = [...defaultSections];
}
if (customItems.length > 0) {
customItems.forEach((customSection) => {
const existingSectionIndex = allSections.findIndex((section) => section.id === customSection.id);
if (existingSectionIndex !== -1) {
allSections[existingSectionIndex].items = [
...allSections[existingSectionIndex].items,
...customSection.items.map((item) => ({ ...item, isDefault: false })),
];
} else {
allSections.push({
...customSection,
isDefault: false,
items: customSection.items.map((item) => ({ ...item, isDefault: false })),
});
}
});
}
// Apply menuProvider if present - advanced use case
if (menuConfig?.menuProvider) {
try {
allSections = menuConfig.menuProvider(enhancedContext, allSections) || allSections;
} catch (error) {
console.warn('[ContextMenu] menuProvider error:', error);
}
}
const filteredSections = allSections
.map((section) => {
const filteredItems = section.items.filter((item) => shouldShowItem(item, enhancedContext));
return {
...section,
items: filteredItems,
};
})
.filter((section) => section.items.length > 0);
return filteredSections;
}