w3c / csswg-drafts

CSS Working Group Editor Drafts
https://drafts.csswg.org/
Other
4.37k stars 642 forks source link

[cssom-view] Proposal: Document.elementsFromRect() #10398

Open justinfagnani opened 1 month ago

justinfagnani commented 1 month ago

elementsFromPoint() allows us to utilize browser hit-testing to get all elements under a specific coordinate. This is great for things like interactive editors that use DOM elements as the editable objects.

But such editors often have other kinds of selection gestures than just a single click that selects at a single coordinate. Often we'll have click-and-drag gestures for selecting all elements under a rectangular window. Some editors will have a lasso tool that lets users draw an irregular selection window. elementsFromPoint() is insufficient for these cases.

Existing solutions

There are two rough approaches I know of for finding all elements under a rect:

  1. Call elementsFromPoint() repeatedly in a grid pattern. This uses the native hit-testing mechanism, but it can obviously miss elements that fall between the grid points.

  2. Re-implement hit testing and crawl the entire DOM looking for intersecting elements. This is very difficult and prone to error.

Proposal

Add elementsFromRect() (and possibly elementsFromPath()) that return all elements intersecting the given rect, to Document and ShadowRoot.

Relevant spec section? https://drafts.csswg.org/cssom-view/#extensions-to-the-document-interface

Originally opened at: https://github.com/whatwg/dom/issues/1286

jogibear9988 commented 3 weeks ago

I did this in my designer (see code sample here: https://github.com/node-projects/web-component-designer/blob/484413259c68585d40846351367fee941741aeaf/packages/web-component-designer/src/elements/widgets/designerView/tools/MagicWandSelectorTool.ts#L58), but it does not work correctly for transformed elements. For this an API like elementsFromPath would be usefull.

SebastianZ commented 3 weeks ago

If such shape APIs are added, they should probably also provide an option to specify whether elements partly covered by the area should be included or only fully included ones.

Sebastian

jogibear9988 commented 3 weeks ago

Or at least we should have an API to get the Shape of an element: https://github.com/whatwg/dom/issues/1294