From ec0ad4b8f47e02c7df5f9d6ab4616e422923f1fd Mon Sep 17 00:00:00 2001 From: Witek Socha Date: Mon, 30 Oct 2023 15:40:53 +0100 Subject: [PATCH 1/2] Add a new how-to for getting words and their ranges. --- docs/examples/how-tos.md | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) diff --git a/docs/examples/how-tos.md b/docs/examples/how-tos.md index 3c08485545d..abecc57e7e3 100644 --- a/docs/examples/how-tos.md +++ b/docs/examples/how-tos.md @@ -254,6 +254,43 @@ for ( const value of range.getWalker() ) { } ``` +### How to find words in a document, and get their ranges? + +``` +const model = editor.model; +const rootElement = model.document.getRoot(); +const rootRange = model.createRangeIn( rootElement ); +const wordRanges = []; + +for ( const item of rootRange.getItems() ) { + // Find `$block` elements (those accept text). + if ( item.is( 'element' ) && model.schema.checkChild( item, '$text' ) ) { + // Get the whole text from block. + // Inline elements (like softBreak or imageInline) are replaced + // with a single whitespace to keep the position offset correct. + const blockText = Array.from( item.getChildren() ) + .reduce( ( rangeText, item ) => rangeText + ( item.is( '$text' ) ? item.data : ' ' ), '' ); + + // Find all words. + for ( const match of blockText.matchAll( /\b\S+\b/g ) ) { + // The position in a text node is always parented by the block element. + const startPosition = model.createPositionAt( item, match.index ); + const endPosition = model.createPositionAt( item, match.index + match[ 0 ].length ); + + wordRanges.push( model.createRange( startPosition, endPosition ) ); + } + } +} + +// Example usage of the collected words: +for ( const range of wordRanges ) { + const fragment = model.getSelectedContent( model.createSelection( range ) ); + const html = editor.data.stringify( fragment ); + + console.log( `[${ range.start.path }] - [${ range.end.path }]`, html ); +} +``` + ### How to listen on a double click (e.g. link elements)? ```js From 4ad9564332a8180915162dc40c3d253aa477ea80 Mon Sep 17 00:00:00 2001 From: godai78 Date: Tue, 31 Oct 2023 10:01:31 +0100 Subject: [PATCH 2/2] Docs: adding description. [short flow] --- docs/examples/how-tos.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/docs/examples/how-tos.md b/docs/examples/how-tos.md index abecc57e7e3..2e31a8854c4 100644 --- a/docs/examples/how-tos.md +++ b/docs/examples/how-tos.md @@ -256,7 +256,9 @@ for ( const value of range.getWalker() ) { ### How to find words in a document, and get their ranges? -``` +If you need to search a text fragment and remap it to its model position, use the following example. It will find all words available in the document root, create a model range based on these and feed them into the console. + +```js const model = editor.model; const rootElement = model.document.getRoot(); const rootRange = model.createRangeIn( rootElement );