@ckeditor/ckeditor5-find-and-replace 36.0.0 → 37.0.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,12 +2,12 @@
2
2
  * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3
3
  * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
4
  */
5
-
6
5
  /**
7
6
  * @module find-and-replace/findandreplaceediting
8
7
  */
9
-
10
8
  import { Plugin } from 'ckeditor5/src/core';
9
+ // eslint-disable-next-line ckeditor5-rules/ckeditor-imports
10
+ import { scrollViewportToShowTarget } from '@ckeditor/ckeditor5-utils/src/dom/scroll';
11
11
  import FindCommand from './findcommand';
12
12
  import ReplaceCommand from './replacecommand';
13
13
  import ReplaceAllCommand from './replaceallcommand';
@@ -15,249 +15,188 @@ import FindNextCommand from './findnextcommand';
15
15
  import FindPreviousCommand from './findpreviouscommand';
16
16
  import FindAndReplaceState from './findandreplacestate';
17
17
  import FindAndReplaceUtils from './findandreplaceutils';
18
-
19
- // eslint-disable-next-line ckeditor5-rules/ckeditor-imports
20
- import { scrollViewportToShowTarget } from '@ckeditor/ckeditor5-utils/src/dom/scroll';
21
-
22
18
  import { debounce } from 'lodash-es';
23
-
24
19
  import '../theme/findandreplace.css';
25
-
26
20
  const HIGHLIGHT_CLASS = 'ck-find-result_selected';
27
-
28
- // Reacts to document changes in order to update search list.
29
- function onDocumentChange( results, editor, searchCallback ) {
30
- const changedNodes = new Set();
31
- const removedMarkers = new Set();
32
- const model = editor.model;
33
-
34
- const changes = model.document.differ.getChanges();
35
-
36
- // Get nodes in which changes happened to re-run a search callback on them.
37
- changes.forEach( change => {
38
- if ( change.name === '$text' || model.schema.isInline( change.position.nodeAfter ) ) {
39
- changedNodes.add( change.position.parent );
40
-
41
- [ ...model.markers.getMarkersAtPosition( change.position ) ].forEach( markerAtChange => {
42
- removedMarkers.add( markerAtChange.name );
43
- } );
44
- } else if ( change.type === 'insert' ) {
45
- changedNodes.add( change.position.nodeAfter );
46
- }
47
- } );
48
-
49
- // Get markers from removed nodes also.
50
- model.document.differ.getChangedMarkers().forEach( ( { name, data: { newRange } } ) => {
51
- if ( newRange && newRange.start.root.rootName === '$graveyard' ) {
52
- removedMarkers.add( name );
53
- }
54
- } );
55
-
56
- // Get markers from the updated nodes and remove all (search will be re-run on these nodes).
57
- changedNodes.forEach( node => {
58
- const markersInNode = [ ...model.markers.getMarkersIntersectingRange( model.createRangeIn( node ) ) ];
59
-
60
- markersInNode.forEach( marker => removedMarkers.add( marker.name ) );
61
- } );
62
-
63
- // Remove results & markers from the changed part of content.
64
- model.change( writer => {
65
- removedMarkers.forEach( markerName => {
66
- // Remove the result first - in order to prevent rendering a removed marker.
67
- if ( results.has( markerName ) ) {
68
- results.remove( markerName );
69
- }
70
-
71
- writer.removeMarker( markerName );
72
- } );
73
- } );
74
-
75
- // Run search callback again on updated nodes.
76
- changedNodes.forEach( nodeToCheck => {
77
- const findAndReplaceUtils = editor.plugins.get( 'FindAndReplaceUtils' );
78
- findAndReplaceUtils.updateFindResultFromRange( model.createRangeOn( nodeToCheck ), model, searchCallback, results );
79
- } );
21
+ /**
22
+ * Reacts to document changes in order to update search list.
23
+ */
24
+ function onDocumentChange(results, editor, searchCallback) {
25
+ const changedNodes = new Set();
26
+ const removedMarkers = new Set();
27
+ const model = editor.model;
28
+ const changes = model.document.differ.getChanges();
29
+ // Get nodes in which changes happened to re-run a search callback on them.
30
+ changes.forEach(change => {
31
+ if (change.name === '$text' || model.schema.isInline(change.position.nodeAfter)) {
32
+ changedNodes.add(change.position.parent);
33
+ [...model.markers.getMarkersAtPosition(change.position)].forEach(markerAtChange => {
34
+ removedMarkers.add(markerAtChange.name);
35
+ });
36
+ }
37
+ else if (change.type === 'insert') {
38
+ changedNodes.add(change.position.nodeAfter);
39
+ }
40
+ });
41
+ // Get markers from removed nodes also.
42
+ model.document.differ.getChangedMarkers().forEach(({ name, data: { newRange } }) => {
43
+ if (newRange && newRange.start.root.rootName === '$graveyard') {
44
+ removedMarkers.add(name);
45
+ }
46
+ });
47
+ // Get markers from the updated nodes and remove all (search will be re-run on these nodes).
48
+ changedNodes.forEach(node => {
49
+ const markersInNode = [...model.markers.getMarkersIntersectingRange(model.createRangeIn(node))];
50
+ markersInNode.forEach(marker => removedMarkers.add(marker.name));
51
+ });
52
+ // Remove results & markers from the changed part of content.
53
+ model.change(writer => {
54
+ removedMarkers.forEach(markerName => {
55
+ // Remove the result first - in order to prevent rendering a removed marker.
56
+ if (results.has(markerName)) {
57
+ results.remove(markerName);
58
+ }
59
+ writer.removeMarker(markerName);
60
+ });
61
+ });
62
+ // Run search callback again on updated nodes.
63
+ changedNodes.forEach(nodeToCheck => {
64
+ const findAndReplaceUtils = editor.plugins.get('FindAndReplaceUtils');
65
+ findAndReplaceUtils.updateFindResultFromRange(model.createRangeOn(nodeToCheck), model, searchCallback, results);
66
+ });
80
67
  }
81
-
82
68
  /**
83
69
  * Implements the editing part for find and replace plugin. For example conversion, commands etc.
84
- *
85
- * @extends module:core/plugin~Plugin
86
70
  */
87
71
  export default class FindAndReplaceEditing extends Plugin {
88
- /**
89
- * @inheritDoc
90
- */
91
- static get requires() {
92
- return [ FindAndReplaceUtils ];
93
- }
94
-
95
- /**
96
- * @inheritDoc
97
- */
98
- static get pluginName() {
99
- return 'FindAndReplaceEditing';
100
- }
101
-
102
- /**
103
- * @inheritDoc
104
- */
105
- init() {
106
- /**
107
- * The collection of currently highlighted search results.
108
- *
109
- * @private
110
- * @member {module:utils/collection~Collection} #_activeResults
111
- */
112
- this._activeResults = null;
113
-
114
- /**
115
- * An object storing the find and replace state within a given editor instance.
116
- *
117
- * @member {module:find-and-replace/findandreplacestate~FindAndReplaceState} #state
118
- */
119
- this.state = new FindAndReplaceState( this.editor.model );
120
-
121
- this._defineConverters();
122
- this._defineCommands();
123
-
124
- this.listenTo( this.state, 'change:highlightedResult', ( eventInfo, name, newValue, oldValue ) => {
125
- const { model } = this.editor;
126
-
127
- model.change( writer => {
128
- if ( oldValue ) {
129
- const oldMatchId = oldValue.marker.name.split( ':' )[ 1 ];
130
- const oldMarker = model.markers.get( `findResultHighlighted:${ oldMatchId }` );
131
-
132
- if ( oldMarker ) {
133
- writer.removeMarker( oldMarker );
134
- }
135
- }
136
-
137
- if ( newValue ) {
138
- const newMatchId = newValue.marker.name.split( ':' )[ 1 ];
139
- writer.addMarker( `findResultHighlighted:${ newMatchId }`, {
140
- usingOperation: false,
141
- affectsData: false,
142
- range: newValue.marker.getRange()
143
- } );
144
- }
145
- } );
146
- } );
147
-
148
- const debouncedScrollListener = debounce( scrollToHighlightedResult.bind( this ), 32 );
149
- // Debounce scroll as highlight might be changed very frequently, e.g. when there's a replace all command.
150
- this.listenTo( this.state, 'change:highlightedResult', debouncedScrollListener, { priority: 'low' } );
151
-
152
- // It's possible that the editor will get destroyed before debounced call kicks in.
153
- // This would result with accessing a view three that is no longer in DOM.
154
- this.listenTo( this.editor, 'destroy', debouncedScrollListener.cancel );
155
-
156
- /* istanbul ignore next */
157
- function scrollToHighlightedResult( eventInfo, name, newValue ) {
158
- if ( newValue ) {
159
- const domConverter = this.editor.editing.view.domConverter;
160
- const viewRange = this.editor.editing.mapper.toViewRange( newValue.marker.getRange() );
161
-
162
- scrollViewportToShowTarget( {
163
- target: domConverter.viewRangeToDom( viewRange ),
164
- viewportOffset: 40
165
- } );
166
- }
167
- }
168
- }
169
-
170
- /**
171
- * Initiate a search.
172
- *
173
- * @param {Function|String} callbackOrText
174
- * @returns {module:utils/collection~Collection}
175
- */
176
- find( callbackOrText ) {
177
- const { editor } = this;
178
- const { model } = editor;
179
-
180
- const { findCallback, results } = editor.execute( 'find', callbackOrText );
181
-
182
- this._activeResults = results;
183
-
184
- // @todo: handle this listener, another copy is in findcommand.js file.
185
- this.listenTo( model.document, 'change:data', () => onDocumentChange( this._activeResults, editor, findCallback ) );
186
-
187
- return this._activeResults;
188
- }
189
-
190
- /**
191
- * Stops active results from updating, and clears out the results.
192
- */
193
- stop() {
194
- if ( !this._activeResults ) {
195
- return;
196
- }
197
-
198
- this.stopListening( this.editor.model.document );
199
-
200
- this.state.clear( this.editor.model );
201
-
202
- this._activeResults = null;
203
- }
204
-
205
- /**
206
- * Sets up the commands.
207
- *
208
- * @private
209
- */
210
- _defineCommands() {
211
- this.editor.commands.add( 'find', new FindCommand( this.editor, this.state ) );
212
- this.editor.commands.add( 'findNext', new FindNextCommand( this.editor, this.state ) );
213
- this.editor.commands.add( 'findPrevious', new FindPreviousCommand( this.editor, this.state ) );
214
- this.editor.commands.add( 'replace', new ReplaceCommand( this.editor, this.state ) );
215
- this.editor.commands.add( 'replaceAll', new ReplaceAllCommand( this.editor, this.state ) );
216
- }
217
-
218
- /**
219
- * Sets up the marker downcast converters for search results highlighting.
220
- *
221
- * @private
222
- */
223
- _defineConverters() {
224
- const { editor } = this;
225
-
226
- // Setup the marker highlighting conversion.
227
- editor.conversion.for( 'editingDowncast' ).markerToHighlight( {
228
- model: 'findResult',
229
- view: ( { markerName } ) => {
230
- const [ , id ] = markerName.split( ':' );
231
-
232
- // Marker removal from the view has a bug: https://github.com/ckeditor/ckeditor5/issues/7499
233
- // A minimal option is to return a new object for each converted marker...
234
- return {
235
- name: 'span',
236
- classes: [ 'ck-find-result' ],
237
- attributes: {
238
- // ...however, adding a unique attribute should be future-proof..
239
- 'data-find-result': id
240
- }
241
- };
242
- }
243
- } );
244
-
245
- editor.conversion.for( 'editingDowncast' ).markerToHighlight( {
246
- model: 'findResultHighlighted',
247
- view: ( { markerName } ) => {
248
- const [ , id ] = markerName.split( ':' );
249
-
250
- // Marker removal from the view has a bug: https://github.com/ckeditor/ckeditor5/issues/7499
251
- // A minimal option is to return a new object for each converted marker...
252
- return {
253
- name: 'span',
254
- classes: [ HIGHLIGHT_CLASS ],
255
- attributes: {
256
- // ...however, adding a unique attribute should be future-proof..
257
- 'data-find-result': id
258
- }
259
- };
260
- }
261
- } );
262
- }
72
+ /**
73
+ * @inheritDoc
74
+ */
75
+ static get requires() {
76
+ return [FindAndReplaceUtils];
77
+ }
78
+ /**
79
+ * @inheritDoc
80
+ */
81
+ static get pluginName() {
82
+ return 'FindAndReplaceEditing';
83
+ }
84
+ /**
85
+ * @inheritDoc
86
+ */
87
+ init() {
88
+ this._activeResults = null;
89
+ this.state = new FindAndReplaceState(this.editor.model);
90
+ this._defineConverters();
91
+ this._defineCommands();
92
+ this.listenTo(this.state, 'change:highlightedResult', (eventInfo, name, newValue, oldValue) => {
93
+ const { model } = this.editor;
94
+ model.change(writer => {
95
+ if (oldValue) {
96
+ const oldMatchId = oldValue.marker.name.split(':')[1];
97
+ const oldMarker = model.markers.get(`findResultHighlighted:${oldMatchId}`);
98
+ if (oldMarker) {
99
+ writer.removeMarker(oldMarker);
100
+ }
101
+ }
102
+ if (newValue) {
103
+ const newMatchId = newValue.marker.name.split(':')[1];
104
+ writer.addMarker(`findResultHighlighted:${newMatchId}`, {
105
+ usingOperation: false,
106
+ affectsData: false,
107
+ range: newValue.marker.getRange()
108
+ });
109
+ }
110
+ });
111
+ });
112
+ /* istanbul ignore next */
113
+ const scrollToHighlightedResult = (eventInfo, name, newValue) => {
114
+ if (newValue) {
115
+ const domConverter = this.editor.editing.view.domConverter;
116
+ const viewRange = this.editor.editing.mapper.toViewRange(newValue.marker.getRange());
117
+ scrollViewportToShowTarget({
118
+ target: domConverter.viewRangeToDom(viewRange),
119
+ viewportOffset: 40
120
+ });
121
+ }
122
+ };
123
+ const debouncedScrollListener = debounce(scrollToHighlightedResult.bind(this), 32);
124
+ // Debounce scroll as highlight might be changed very frequently, e.g. when there's a replace all command.
125
+ this.listenTo(this.state, 'change:highlightedResult', debouncedScrollListener, { priority: 'low' });
126
+ // It's possible that the editor will get destroyed before debounced call kicks in.
127
+ // This would result with accessing a view three that is no longer in DOM.
128
+ this.listenTo(this.editor, 'destroy', debouncedScrollListener.cancel);
129
+ }
130
+ /**
131
+ * Initiate a search.
132
+ */
133
+ find(callbackOrText) {
134
+ const { editor } = this;
135
+ const { model } = editor;
136
+ const { findCallback, results } = editor.execute('find', callbackOrText);
137
+ this._activeResults = results;
138
+ // @todo: handle this listener, another copy is in findcommand.js file.
139
+ this.listenTo(model.document, 'change:data', () => onDocumentChange(this._activeResults, editor, findCallback));
140
+ return this._activeResults;
141
+ }
142
+ /**
143
+ * Stops active results from updating, and clears out the results.
144
+ */
145
+ stop() {
146
+ if (!this._activeResults) {
147
+ return;
148
+ }
149
+ this.stopListening(this.editor.model.document);
150
+ this.state.clear(this.editor.model);
151
+ this._activeResults = null;
152
+ }
153
+ /**
154
+ * Sets up the commands.
155
+ */
156
+ _defineCommands() {
157
+ this.editor.commands.add('find', new FindCommand(this.editor, this.state));
158
+ this.editor.commands.add('findNext', new FindNextCommand(this.editor, this.state));
159
+ this.editor.commands.add('findPrevious', new FindPreviousCommand(this.editor, this.state));
160
+ this.editor.commands.add('replace', new ReplaceCommand(this.editor, this.state));
161
+ this.editor.commands.add('replaceAll', new ReplaceAllCommand(this.editor, this.state));
162
+ }
163
+ /**
164
+ * Sets up the marker downcast converters for search results highlighting.
165
+ */
166
+ _defineConverters() {
167
+ const { editor } = this;
168
+ // Setup the marker highlighting conversion.
169
+ editor.conversion.for('editingDowncast').markerToHighlight({
170
+ model: 'findResult',
171
+ view: ({ markerName }) => {
172
+ const [, id] = markerName.split(':');
173
+ // Marker removal from the view has a bug: https://github.com/ckeditor/ckeditor5/issues/7499
174
+ // A minimal option is to return a new object for each converted marker...
175
+ return {
176
+ name: 'span',
177
+ classes: ['ck-find-result'],
178
+ attributes: {
179
+ // ...however, adding a unique attribute should be future-proof..
180
+ 'data-find-result': id
181
+ }
182
+ };
183
+ }
184
+ });
185
+ editor.conversion.for('editingDowncast').markerToHighlight({
186
+ model: 'findResultHighlighted',
187
+ view: ({ markerName }) => {
188
+ const [, id] = markerName.split(':');
189
+ // Marker removal from the view has a bug: https://github.com/ckeditor/ckeditor5/issues/7499
190
+ // A minimal option is to return a new object for each converted marker...
191
+ return {
192
+ name: 'span',
193
+ classes: [HIGHLIGHT_CLASS],
194
+ attributes: {
195
+ // ...however, adding a unique attribute should be future-proof..
196
+ 'data-find-result': id
197
+ }
198
+ };
199
+ }
200
+ });
201
+ }
263
202
  }
@@ -0,0 +1,69 @@
1
+ /**
2
+ * @license Copyright (c) 2003-2023, CKSource Holding sp. z o.o. All rights reserved.
3
+ * For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license
4
+ */
5
+ /**
6
+ * @module find-and-replace/findandreplacestate
7
+ */
8
+ import type { Model } from 'ckeditor5/src/engine';
9
+ import { Collection } from 'ckeditor5/src/utils';
10
+ import type { ResultType } from './findandreplace';
11
+ declare const FindAndReplaceState_base: {
12
+ new (): import("ckeditor5/src/utils").Observable;
13
+ prototype: import("ckeditor5/src/utils").Observable;
14
+ };
15
+ /**
16
+ * The object storing find and replace plugin state for a given editor instance.
17
+ */
18
+ export default class FindAndReplaceState extends FindAndReplaceState_base {
19
+ /**
20
+ * A collection of find matches.
21
+ *
22
+ * @observable
23
+ */
24
+ results: Collection<ResultType>;
25
+ /**
26
+ * Currently highlighted search result in {@link #results matched results}.
27
+ *
28
+ * @readonly
29
+ * @observable
30
+ */
31
+ highlightedResult: ResultType | null;
32
+ /**
33
+ * Searched text value.
34
+ *
35
+ * @readonly
36
+ * @observable
37
+ */
38
+ searchText: string;
39
+ /**
40
+ * Replace text value.
41
+ *
42
+ * @readonly
43
+ * @observable
44
+ */
45
+ replaceText: string;
46
+ /**
47
+ * Indicates whether the matchCase checkbox has been checked.
48
+ *
49
+ * @readonly
50
+ * @observable
51
+ */
52
+ matchCase: boolean;
53
+ /**
54
+ * Indicates whether the matchWholeWords checkbox has been checked.
55
+ *
56
+ * @readonly
57
+ * @observable
58
+ */
59
+ matchWholeWords: boolean;
60
+ /**
61
+ * Creates an instance of the state.
62
+ */
63
+ constructor(model: Model);
64
+ /**
65
+ * Cleans the state up and removes markers from the model.
66
+ */
67
+ clear(model: Model): void;
68
+ }
69
+ export {};