-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
legacytodolistediting.ts
291 lines (246 loc) · 9.28 KB
/
legacytodolistediting.ts
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
/**
* @license Copyright (c) 2003-2024, CKSource Holding sp. z o.o. All rights reserved.
* For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
*/
/**
* @module list/legacytodolist/legacytodolistediting
*/
import type {
DowncastAttributeEvent,
DowncastInsertEvent,
Element,
Item,
MapperModelToViewPositionEvent,
Model,
ModelApplyOperationEvent,
UpcastElementEvent,
ViewDocumentArrowKeyEvent,
ViewDocumentKeyDownEvent,
AttributeOperation,
RenameOperation,
SelectionChangeRangeEvent,
DocumentFragment
} from 'ckeditor5/src/engine.js';
import { Plugin } from 'ckeditor5/src/core.js';
import {
getCode,
parseKeystroke,
getLocalizedArrowKeyCodeDirection,
type Locale,
type GetCallback
} from 'ckeditor5/src/utils.js';
import LegacyListCommand from '../legacylist/legacylistcommand.js';
import LegacyListEditing from '../legacylist/legacylistediting.js';
import LegacyCheckTodoListCommand from './legacychecktodolistcommand.js';
import {
dataModelViewInsertion,
dataViewModelCheckmarkInsertion,
mapModelToViewPosition,
modelViewChangeChecked,
modelViewChangeType,
modelViewInsertion
} from './legacytodolistconverters.js';
const ITEM_TOGGLE_KEYSTROKE = /* #__PURE__ */ parseKeystroke( 'Ctrl+Enter' );
/**
* The engine of the to-do list feature. It handles creating, editing and removing to-do lists and their items.
*
* It registers the entire functionality of the {@link module:list/legacylist/legacylistediting~LegacyListEditing legacy list editing
* plugin} and extends it with the commands:
*
* - `'todoList'`,
* - `'checkTodoList'`,
* - `'todoListCheck'` as an alias for `checkTodoList` command.
*/
export default class LegacyTodoListEditing extends Plugin {
/**
* @inheritDoc
*/
public static get pluginName() {
return 'LegacyTodoListEditing' as const;
}
/**
* @inheritDoc
*/
public static get requires() {
return [ LegacyListEditing ] as const;
}
/**
* @inheritDoc
*/
public init(): void {
const editor = this.editor;
const { editing, data, model } = editor;
// Extend schema.
model.schema.extend( 'listItem', {
allowAttributes: [ 'todoListChecked' ]
} );
// Disallow todoListChecked attribute on other nodes than listItem with to-do listType.
model.schema.addAttributeCheck( ( context: any, attributeName ) => {
const item = context.last;
if ( attributeName == 'todoListChecked' && item.name == 'listItem' && item.getAttribute( 'listType' ) != 'todo' ) {
return false;
}
} );
// Register `todoList` command.
editor.commands.add( 'todoList', new LegacyListCommand( editor, 'todo' ) );
const checkTodoListCommand = new LegacyCheckTodoListCommand( editor );
// Register `checkTodoList` command and add `todoListCheck` command as an alias for backward compatibility.
editor.commands.add( 'checkTodoList', checkTodoListCommand );
editor.commands.add( 'todoListCheck', checkTodoListCommand );
// Define converters.
data.downcastDispatcher.on<DowncastInsertEvent<Element>>(
'insert:listItem',
dataModelViewInsertion( model ),
{ priority: 'high' }
);
data.upcastDispatcher.on<UpcastElementEvent>(
'element:input',
dataViewModelCheckmarkInsertion,
{ priority: 'high' }
);
editing.downcastDispatcher.on<DowncastInsertEvent<Element>>(
'insert:listItem',
modelViewInsertion( model, listItem => this._handleCheckmarkChange( listItem ) ),
{ priority: 'high' }
);
editing.downcastDispatcher.on<DowncastAttributeEvent<Element>>(
'attribute:listType:listItem',
modelViewChangeType( listItem => this._handleCheckmarkChange( listItem ), editing.view )
);
editing.downcastDispatcher.on<DowncastAttributeEvent<Element>>(
'attribute:todoListChecked:listItem',
modelViewChangeChecked( listItem => this._handleCheckmarkChange( listItem ) )
);
editing.mapper.on<MapperModelToViewPositionEvent>( 'modelToViewPosition', mapModelToViewPosition( editing.view ) );
data.mapper.on<MapperModelToViewPositionEvent>( 'modelToViewPosition', mapModelToViewPosition( editing.view ) );
// Jump at the end of the previous node on left arrow key press, when selection is after the checkbox.
//
// <blockquote><p>Foo</p></blockquote>
// <ul><li><checkbox/>{}Bar</li></ul>
//
// press: `<-`
//
// <blockquote><p>Foo{}</p></blockquote>
// <ul><li><checkbox/>Bar</li></ul>
//
this.listenTo<ViewDocumentArrowKeyEvent>(
editing.view.document,
'arrowKey',
jumpOverCheckmarkOnSideArrowKeyPress( model, editor.locale ),
{ context: 'li' }
);
// Toggle check state of selected to-do list items on keystroke.
this.listenTo<ViewDocumentKeyDownEvent>( editing.view.document, 'keydown', ( evt, data ) => {
if ( getCode( data ) === ITEM_TOGGLE_KEYSTROKE ) {
editor.execute( 'checkTodoList' );
evt.stop();
}
}, { priority: 'high' } );
// Remove `todoListChecked` attribute when a host element is no longer a to-do list item.
const listItemsToFix = new Set<Item>();
this.listenTo<ModelApplyOperationEvent>( model, 'applyOperation', ( evt, args ) => {
const operation = args[ 0 ] as RenameOperation | AttributeOperation;
if ( operation.type == 'rename' && operation.oldName == 'listItem' ) {
const item = operation.position.nodeAfter!;
if ( item.hasAttribute( 'todoListChecked' ) ) {
listItemsToFix.add( item );
}
} else if ( operation.type == 'changeAttribute' && operation.key == 'listType' && operation.oldValue === 'todo' ) {
for ( const item of operation.range.getItems() ) {
if ( item.hasAttribute( 'todoListChecked' ) && item.getAttribute( 'listType' ) !== 'todo' ) {
listItemsToFix.add( item );
}
}
}
} );
model.document.registerPostFixer( writer => {
let hasChanged = false;
for ( const listItem of listItemsToFix ) {
writer.removeAttribute( 'todoListChecked', listItem );
hasChanged = true;
}
listItemsToFix.clear();
return hasChanged;
} );
this._initAriaAnnouncements();
}
/**
* Handles the checkbox element change, moves the selection to the corresponding model item to make it possible
* to toggle the `todoListChecked` attribute using the command, and restores the selection position.
*
* Some say it's a hack :) Moving the selection only for executing the command on a certain node and restoring it after,
* is not a clear solution. We need to design an API for using commands beyond the selection range.
* See https://github.com/ckeditor/ckeditor5/issues/1954.
*/
private _handleCheckmarkChange( listItem: Element ) {
const editor = this.editor;
const model = editor.model;
const previousSelectionRanges = Array.from( model.document.selection.getRanges() );
model.change( writer => {
writer.setSelection( listItem, 'end' );
editor.execute( 'checkTodoList' );
writer.setSelection( previousSelectionRanges );
} );
}
/**
* Observe when user enters or leaves todo list and set proper aria value in global live announcer.
* This allows screen readers to indicate when the user has entered and left the specified todo list.
*
* @internal
*/
private _initAriaAnnouncements( ) {
const { model, ui, t } = this.editor;
let lastFocusedCodeBlock: Element | DocumentFragment | null = null;
if ( !ui ) {
return;
}
model.document.selection.on<SelectionChangeRangeEvent>( 'change:range', () => {
const focusParent = model.document.selection.focus!.parent;
const lastElementIsTodoList = isLegacyTodoListItemElement( lastFocusedCodeBlock );
const currentElementIsTodoList = isLegacyTodoListItemElement( focusParent );
if ( lastElementIsTodoList && !currentElementIsTodoList ) {
ui.ariaLiveAnnouncer.announce( t( 'Leaving a to-do list' ) );
} else if ( !lastElementIsTodoList && currentElementIsTodoList ) {
ui.ariaLiveAnnouncer.announce( t( 'Entering a to-do list' ) );
}
lastFocusedCodeBlock = focusParent;
} );
}
}
/**
* Handles the left/right (LTR/RTL content) arrow key and moves the selection at the end of the previous block element
* if the selection is just after the checkbox element. In other words, it jumps over the checkbox element when
* moving the selection to the left/right (LTR/RTL).
*
* @returns Callback for 'keydown' events.
*/
function jumpOverCheckmarkOnSideArrowKeyPress( model: Model, locale: Locale ): GetCallback<ViewDocumentArrowKeyEvent> {
return ( eventInfo, domEventData ) => {
const direction = getLocalizedArrowKeyCodeDirection( domEventData.keyCode, locale.contentLanguageDirection );
if ( direction != 'left' ) {
return;
}
const schema = model.schema;
const selection = model.document.selection;
if ( !selection.isCollapsed ) {
return;
}
const position = selection.getFirstPosition()!;
const parent = position.parent;
if ( parent.name === 'listItem' && parent.getAttribute( 'listType' ) == 'todo' && position.isAtStart ) {
const newRange = schema.getNearestSelectionRange( model.createPositionBefore( parent ), 'backward' );
if ( newRange ) {
model.change( writer => writer.setSelection( newRange ) );
}
domEventData.preventDefault();
domEventData.stopPropagation();
eventInfo.stop();
}
};
}
/**
* Returns true if the given element is a list item model element of a to-do list.
*/
function isLegacyTodoListItemElement( element: Element | DocumentFragment | null ): boolean {
return !!element && element.is( 'element', 'listItem' ) && element.getAttribute( 'listType' ) === 'todo';
}