Re: [w3c/selection-api] Support multi range selection (#41)

An enumeration of text nodes seems a bit awkward to work with for use cases that want to do something to _elements_ in the selection, but perhaps it works for most cases.  What worries me with returning an array though is the issue of DOM mutations, let's say the user made this (multi-range) selection:
`"[foo] bar [baz]"` (a single text node)
Your API would return:  `[{node: "foo...", start: 0, end: 3}, {node: "foo...", start: 8, end: 11}]`
Let's say I want to make the selected text bold by wrapping it in `<b>` elements, so I iterate and wrap "foo" ... but this makes the second SelectedNode invalid!
(Ranges are so much nicer in this situation since they update their offsets in response to mutations.)

A callback approach seems better in that respect, something like this perhaps:
`selection.forEachNode(function (node,start,end) {})`
For my multi-range example above, this would result in two callbacks: with "foo...",0,3 and " bar...",5,8 and it would work correctly.

Perhaps we could also support a selector to make it easier to work with selected elements?
`selection.forEachNode(function (node,start,end) {}, "b")`
(like querySelectorAll restricted to selected nodes)

If we invent some selector for text nodes we would get something like your proposal, except the caller doesn't have to deal with mutations (in most cases):
`selection.forEachNode(function (node,start,end) {}, "::text")`

There might be better alternatives like ES6 generators/iterables or something. Like, `for ([node,start,end] in selection.querySelectorAll("b")) ...` (assuming that this also let's us control each returned result as we go so we can deal with mutations).

I think the primary requirements for a new API should be (in no particular order):
1. easy to upgrade existing code
2. easy to use
3. robust even when DOM mutations occur
4. hide multi-range selection behind the scene so web developers don't have to know about them
5. offer more features than the existing API (and be extensible for more in the future)

I think the last point is important to persuade web developers to use the new API instead of what they are currently doing, which is crucial for solving this problem.


-- 
You are receiving this because you are subscribed to this thread.
Reply to this email directly or view it on GitHub:
https://github.com/w3c/selection-api/issues/41#issuecomment-289904604

Received on Tuesday, 28 March 2017 21:05:54 UTC