/
fontcommand.js
91 lines (80 loc) · 2.32 KB
/
fontcommand.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/**
* @license Copyright (c) 2003-2022, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module font/fontcommand
*/
import { Command } from 'ckeditor5/src/core';
/**
* The base font command.
*
* @extends module:core/command~Command
*/
export default class FontCommand extends Command {
/**
* Creates an instance of the command.
*
* @param {module:core/editor/editor~Editor} editor Editor instance.
* @param {String} attributeKey The name of a model attribute on which this command operates.
*/
constructor( editor, attributeKey ) {
super( editor );
/**
* When set, it reflects the {@link #attributeKey} value of the selection.
*
* @observable
* @readonly
* @member {String} module:font/fontcommand~FontCommand#value
*/
/**
* A model attribute on which this command operates.
*
* @readonly
* @member {Boolean} module:font/fontcommand~FontCommand#attributeKey
*/
this.attributeKey = attributeKey;
}
/**
* @inheritDoc
*/
refresh() {
const model = this.editor.model;
const doc = model.document;
this.value = doc.selection.getAttribute( this.attributeKey );
this.isEnabled = model.schema.checkAttributeInSelection( doc.selection, this.attributeKey );
}
/**
* Executes the command. Applies the `value` of the {@link #attributeKey} to the selection.
* If no `value` is passed, it removes the attribute from the selection.
*
* @protected
* @param {Object} [options] Options for the executed command.
* @param {String} [options.value] The value to apply.
* @fires execute
*/
execute( options = {} ) {
const model = this.editor.model;
const document = model.document;
const selection = document.selection;
const value = options.value;
model.change( writer => {
if ( selection.isCollapsed ) {
if ( value ) {
writer.setSelectionAttribute( this.attributeKey, value );
} else {
writer.removeSelectionAttribute( this.attributeKey );
}
} else {
const ranges = model.schema.getValidRanges( selection.getRanges(), this.attributeKey );
for ( const range of ranges ) {
if ( value ) {
writer.setAttribute( this.attributeKey, value, range );
} else {
writer.removeAttribute( this.attributeKey, range );
}
}
}
} );
}
}