timdown / rangy

A cross-browser JavaScript range and selection library.
MIT License
2.24k stars 368 forks source link

Question - selection IDs #477

Closed YOUR1 closed 1 year ago

YOUR1 commented 1 year ago

Hi;

Let say we have the following text:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ultrices nunc eget erat rhoncus elementum. Nunc sed commodo ante. Ut faucibus dui at sollicitudin venenatis. Ut finibus ex et dolor ultrices, ut cursus felis semper. Aenean aliquet ex quis sem hendrerit eleifend. Nunc vel lectus at odio congue sodales dignissim ut nisi. Aliquam elementum lorem a turpis interdum, eget consectetur tortor facilisis. Curabitur porttitor quis nunc at lacinia.

As you can see; we have multiple 'at'-text nodes, 3 to be exact. Is it possible to determine what number is selected?

For example if I select the 'at' in the last line, I want to have something like 'at#3'.

Is this possible with the Rangy library?

Thanks in advance.

lijie1129 commented 1 year ago

I think the rangy can tell us the current text of selection.

But the determining of '#3' needs to use other libraries.

YOUR1 commented 1 year ago

I solved it relative simply by using the Search addon;

getTextAndIndex: function( selection, wrap ) {
        wrap = typeof wrap === "undefined" ? true : wrap;
        var baseEl = getNodeRoot(),
            selectionPos = rangy.serializeSelection( selection ),
            searchFor = selection.toString(),
            range = rangy.createRange(),
            searchScopeRange = rangy.createRange(),
            i = 0,
            res = {
                text: searchFor,
                index: i
        };

        range.selectNodeContents( baseEl );
        searchScopeRange.selectNodeContents( baseEl );

        var options = {
            caseSensitive: true,
            withinRange: searchScopeRange
        };

        if ( searchFor !== "" ) {
            while( range.findText( searchFor, options ) ) {
                if ( rangy.serializeRange( range ) === selectionPos ) {
                    res.index = i;
                }
                range.collapse(false);
                ++i;
            }
        }

        return res;
    },