This repository has been archived by the owner on Aug 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
custom-plugin.js
77 lines (60 loc) · 1.87 KB
/
custom-plugin.js
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
import { Command, ButtonView } from 'ckeditor5';
export function Highlight( editor ) {
editor.model.schema.extend( '$text', {
allowAttributes: 'highlight'
} );
editor.conversion.attributeToElement( {
model: 'highlight',
view: 'mark'
} );
editor.commands.add( 'highlight', new HighlightCommand( editor ) );
editor.ui.componentFactory.add( 'highlight', ( locale ) => {
const button = new ButtonView( locale );
const command = editor.commands.get( 'highlight' );
const t = editor.t;
button.set( {
label: t( 'Highlight' ),
withText: true,
tooltip: true,
isToggleable: true,
keystroke: 'Ctrl+Alt+H'
} );
button.on( 'execute', () => {
editor.execute( 'highlight' );
editor.editing.view.focus();
} );
button.bind( 'isOn', 'isEnabled' ).to( command, 'value', 'isEnabled' );
return button;
} );
editor.keystrokes.set( 'Ctrl+Alt+H', 'highlight' );
}
class HighlightCommand extends Command {
refresh() {
const { document, schema } = this.editor.model;
// Check if selection is already highlighted.
this.value = document.selection.getAttribute( 'highlight' );
// Check if command is allowed on current selection.
this.isEnabled = schema.checkAttributeInSelection( document.selection, 'highlight' );
}
execute() {
const model = this.editor.model;
const selection = model.document.selection;
const newValue = !this.value;
model.change( ( writer ) => {
if ( !selection.isCollapsed ) {
const ranges = model.schema.getValidRanges( selection.getRanges(), 'highlight' );
for ( const range of ranges ) {
if ( newValue ) {
writer.setAttribute( 'highlight', newValue, range );
} else {
writer.removeAttribute( 'highlight', range );
}
}
}
if ( newValue ) {
return writer.setSelectionAttribute( 'highlight', true );
}
return writer.removeSelectionAttribute( 'highlight' );
} );
}
}