Range.cpp 60 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2022-2023, Andreas Kling <andreas@ladybird.org>
  5. * Copyright (c) 2024, Jelle Raaijmakers <jelle@ladybird.org>
  6. *
  7. * SPDX-License-Identifier: BSD-2-Clause
  8. */
  9. #include <LibWeb/Bindings/Intrinsics.h>
  10. #include <LibWeb/Bindings/RangePrototype.h>
  11. #include <LibWeb/DOM/Comment.h>
  12. #include <LibWeb/DOM/Document.h>
  13. #include <LibWeb/DOM/DocumentFragment.h>
  14. #include <LibWeb/DOM/DocumentType.h>
  15. #include <LibWeb/DOM/ElementFactory.h>
  16. #include <LibWeb/DOM/Event.h>
  17. #include <LibWeb/DOM/Node.h>
  18. #include <LibWeb/DOM/ProcessingInstruction.h>
  19. #include <LibWeb/DOM/Range.h>
  20. #include <LibWeb/DOM/Text.h>
  21. #include <LibWeb/Geometry/DOMRect.h>
  22. #include <LibWeb/Geometry/DOMRectList.h>
  23. #include <LibWeb/HTML/HTMLHtmlElement.h>
  24. #include <LibWeb/HTML/HTMLInputElement.h>
  25. #include <LibWeb/HTML/HTMLTextAreaElement.h>
  26. #include <LibWeb/HTML/Window.h>
  27. #include <LibWeb/Layout/Viewport.h>
  28. #include <LibWeb/Namespace.h>
  29. #include <LibWeb/Painting/ViewportPaintable.h>
  30. namespace Web::DOM {
  31. JS_DEFINE_ALLOCATOR(Range);
  32. HashTable<Range*>& Range::live_ranges()
  33. {
  34. static HashTable<Range*> ranges;
  35. return ranges;
  36. }
  37. JS::NonnullGCPtr<Range> Range::create(HTML::Window& window)
  38. {
  39. return Range::create(window.associated_document());
  40. }
  41. JS::NonnullGCPtr<Range> Range::create(Document& document)
  42. {
  43. auto& realm = document.realm();
  44. return realm.heap().allocate<Range>(realm, document);
  45. }
  46. JS::NonnullGCPtr<Range> Range::create(Node& start_container, WebIDL::UnsignedLong start_offset, Node& end_container, WebIDL::UnsignedLong end_offset)
  47. {
  48. auto& realm = start_container.realm();
  49. return realm.heap().allocate<Range>(realm, start_container, start_offset, end_container, end_offset);
  50. }
  51. WebIDL::ExceptionOr<JS::NonnullGCPtr<Range>> Range::construct_impl(JS::Realm& realm)
  52. {
  53. auto& window = verify_cast<HTML::Window>(realm.global_object());
  54. return Range::create(window);
  55. }
  56. Range::Range(Document& document)
  57. : Range(document, 0, document, 0)
  58. {
  59. }
  60. Range::Range(Node& start_container, WebIDL::UnsignedLong start_offset, Node& end_container, WebIDL::UnsignedLong end_offset)
  61. : AbstractRange(start_container, start_offset, end_container, end_offset)
  62. {
  63. live_ranges().set(this);
  64. }
  65. Range::~Range()
  66. {
  67. live_ranges().remove(this);
  68. }
  69. void Range::initialize(JS::Realm& realm)
  70. {
  71. Base::initialize(realm);
  72. WEB_SET_PROTOTYPE_FOR_INTERFACE(Range);
  73. }
  74. void Range::visit_edges(Cell::Visitor& visitor)
  75. {
  76. Base::visit_edges(visitor);
  77. visitor.visit(m_associated_selection);
  78. }
  79. void Range::set_associated_selection(Badge<Selection::Selection>, JS::GCPtr<Selection::Selection> selection)
  80. {
  81. m_associated_selection = selection;
  82. update_associated_selection();
  83. }
  84. void Range::update_associated_selection()
  85. {
  86. auto& document = m_start_container->document();
  87. if (auto* viewport = document.paintable()) {
  88. viewport->recompute_selection_states(*this);
  89. viewport->update_selection();
  90. viewport->set_needs_display();
  91. }
  92. // https://w3c.github.io/selection-api/#selectionchange-event
  93. // When the selection is dissociated with its range, associated with a new range, or the
  94. // associated range's boundary point is mutated either by the user or the content script, the
  95. // user agent must schedule a selectionchange event on document.
  96. schedule_a_selectionchange_event(document);
  97. // When an input or textarea element provide a text selection and its selection changes (in
  98. // either extent or direction), the user agent must schedule a selectionchange event on the
  99. // element.
  100. if (m_start_container == m_end_container) {
  101. if (is<HTML::HTMLInputElement>(*m_start_container))
  102. schedule_a_selectionchange_event(verify_cast<HTML::HTMLInputElement>(*m_start_container));
  103. if (is<HTML::HTMLTextAreaElement>(*m_start_container))
  104. schedule_a_selectionchange_event(verify_cast<HTML::HTMLTextAreaElement>(*m_start_container));
  105. }
  106. }
  107. // https://w3c.github.io/selection-api/#scheduling-selectionhange-event
  108. template<SelectionChangeTarget T>
  109. void Range::schedule_a_selectionchange_event(T& target)
  110. {
  111. // 1. If target's has scheduled selectionchange event is true, abort these steps.
  112. if (target.has_scheduled_selectionchange_event())
  113. return;
  114. // AD-HOC (https://github.com/w3c/selection-api/issues/338):
  115. // Set target's has scheduled selectionchange event to true
  116. target.set_scheduled_selectionchange_event(true);
  117. // 2. Queue a task on the user interaction task source to fire a selectionchange event on
  118. // target.
  119. JS::NonnullGCPtr<Document> document = m_start_container->document();
  120. queue_global_task(HTML::Task::Source::UserInteraction, relevant_global_object(*document), JS::create_heap_function(document->heap(), [&] {
  121. fire_a_selectionchange_event(target);
  122. }));
  123. }
  124. // https://w3c.github.io/selection-api/#firing-selectionhange-event
  125. template<SelectionChangeTarget T>
  126. void Range::fire_a_selectionchange_event(T& target)
  127. {
  128. // 1. Set target's has scheduled selectionchange event to false.
  129. target.set_scheduled_selectionchange_event(false);
  130. // 2. If target is an element, fire an event named selectionchange, which bubbles and not
  131. // cancelable, at target.
  132. // 3. Otherwise, if target is a document, fire an event named selectionchange, which does not
  133. // bubble and not cancelable, at target.
  134. EventInit event_init;
  135. event_init.bubbles = SameAs<T, Element>;
  136. event_init.cancelable = false;
  137. auto& realm = m_start_container->document().realm();
  138. auto event = DOM::Event::create(realm, HTML::EventNames::selectionchange, event_init);
  139. target.dispatch_event(event);
  140. }
  141. // https://dom.spec.whatwg.org/#concept-range-root
  142. Node& Range::root()
  143. {
  144. // The root of a live range is the root of its start node.
  145. return m_start_container->root();
  146. }
  147. Node const& Range::root() const
  148. {
  149. return m_start_container->root();
  150. }
  151. // https://dom.spec.whatwg.org/#concept-range-bp-position
  152. RelativeBoundaryPointPosition position_of_boundary_point_relative_to_other_boundary_point(Node const& node_a, u32 offset_a, Node const& node_b, u32 offset_b)
  153. {
  154. // 1. Assert: nodeA and nodeB have the same root.
  155. VERIFY(&node_a.root() == &node_b.root());
  156. // 2. If nodeA is nodeB, then return equal if offsetA is offsetB, before if offsetA is less than offsetB, and after if offsetA is greater than offsetB.
  157. if (&node_a == &node_b) {
  158. if (offset_a == offset_b)
  159. return RelativeBoundaryPointPosition::Equal;
  160. if (offset_a < offset_b)
  161. return RelativeBoundaryPointPosition::Before;
  162. return RelativeBoundaryPointPosition::After;
  163. }
  164. // 3. If nodeA is following nodeB, then if the position of (nodeB, offsetB) relative to (nodeA, offsetA) is before, return after, and if it is after, return before.
  165. if (node_a.is_following(node_b)) {
  166. auto relative_position = position_of_boundary_point_relative_to_other_boundary_point(node_b, offset_b, node_a, offset_a);
  167. if (relative_position == RelativeBoundaryPointPosition::Before)
  168. return RelativeBoundaryPointPosition::After;
  169. if (relative_position == RelativeBoundaryPointPosition::After)
  170. return RelativeBoundaryPointPosition::Before;
  171. }
  172. // 4. If nodeA is an ancestor of nodeB:
  173. if (node_a.is_ancestor_of(node_b)) {
  174. // 1. Let child be nodeB.
  175. JS::NonnullGCPtr<Node const> child = node_b;
  176. // 2. While child is not a child of nodeA, set child to its parent.
  177. while (!node_a.is_parent_of(child)) {
  178. auto* parent = child->parent();
  179. VERIFY(parent);
  180. child = *parent;
  181. }
  182. // 3. If child’s index is less than offsetA, then return after.
  183. if (child->index() < offset_a)
  184. return RelativeBoundaryPointPosition::After;
  185. }
  186. // 5. Return before.
  187. return RelativeBoundaryPointPosition::Before;
  188. }
  189. WebIDL::ExceptionOr<void> Range::set_start_or_end(Node& node, u32 offset, StartOrEnd start_or_end)
  190. {
  191. // To set the start or end of a range to a boundary point (node, offset), run these steps:
  192. // 1. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  193. if (is<DocumentType>(node))
  194. return WebIDL::InvalidNodeTypeError::create(realm(), "Node cannot be a DocumentType."_string);
  195. // 2. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  196. if (offset > node.length())
  197. return WebIDL::IndexSizeError::create(realm(), MUST(String::formatted("Node does not contain a child at offset {}", offset)));
  198. // 3. Let bp be the boundary point (node, offset).
  199. if (start_or_end == StartOrEnd::Start) {
  200. // -> If these steps were invoked as "set the start"
  201. // 1. If range’s root is not equal to node’s root, or if bp is after the range’s end, set range’s end to bp.
  202. if (&root() != &node.root() || position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset) == RelativeBoundaryPointPosition::After) {
  203. m_end_container = node;
  204. m_end_offset = offset;
  205. }
  206. // 2. Set range’s start to bp.
  207. m_start_container = node;
  208. m_start_offset = offset;
  209. } else {
  210. // -> If these steps were invoked as "set the end"
  211. VERIFY(start_or_end == StartOrEnd::End);
  212. // 1. If range’s root is not equal to node’s root, or if bp is before the range’s start, set range’s start to bp.
  213. if (&root() != &node.root() || position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset) == RelativeBoundaryPointPosition::Before) {
  214. m_start_container = node;
  215. m_start_offset = offset;
  216. }
  217. // 2. Set range’s end to bp.
  218. m_end_container = node;
  219. m_end_offset = offset;
  220. }
  221. update_associated_selection();
  222. return {};
  223. }
  224. // https://dom.spec.whatwg.org/#concept-range-bp-set
  225. WebIDL::ExceptionOr<void> Range::set_start(Node& node, WebIDL::UnsignedLong offset)
  226. {
  227. // The setStart(node, offset) method steps are to set the start of this to boundary point (node, offset).
  228. return set_start_or_end(node, offset, StartOrEnd::Start);
  229. }
  230. WebIDL::ExceptionOr<void> Range::set_end(Node& node, WebIDL::UnsignedLong offset)
  231. {
  232. // The setEnd(node, offset) method steps are to set the end of this to boundary point (node, offset).
  233. return set_start_or_end(node, offset, StartOrEnd::End);
  234. }
  235. // https://dom.spec.whatwg.org/#dom-range-setstartbefore
  236. WebIDL::ExceptionOr<void> Range::set_start_before(Node& node)
  237. {
  238. // 1. Let parent be node’s parent.
  239. auto* parent = node.parent();
  240. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  241. if (!parent)
  242. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_string);
  243. // 3. Set the start of this to boundary point (parent, node’s index).
  244. return set_start_or_end(*parent, node.index(), StartOrEnd::Start);
  245. }
  246. // https://dom.spec.whatwg.org/#dom-range-setstartafter
  247. WebIDL::ExceptionOr<void> Range::set_start_after(Node& node)
  248. {
  249. // 1. Let parent be node’s parent.
  250. auto* parent = node.parent();
  251. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  252. if (!parent)
  253. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_string);
  254. // 3. Set the start of this to boundary point (parent, node’s index plus 1).
  255. return set_start_or_end(*parent, node.index() + 1, StartOrEnd::Start);
  256. }
  257. // https://dom.spec.whatwg.org/#dom-range-setendbefore
  258. WebIDL::ExceptionOr<void> Range::set_end_before(Node& node)
  259. {
  260. // 1. Let parent be node’s parent.
  261. auto* parent = node.parent();
  262. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  263. if (!parent)
  264. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_string);
  265. // 3. Set the end of this to boundary point (parent, node’s index).
  266. return set_start_or_end(*parent, node.index(), StartOrEnd::End);
  267. }
  268. // https://dom.spec.whatwg.org/#dom-range-setendafter
  269. WebIDL::ExceptionOr<void> Range::set_end_after(Node& node)
  270. {
  271. // 1. Let parent be node’s parent.
  272. auto* parent = node.parent();
  273. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  274. if (!parent)
  275. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_string);
  276. // 3. Set the end of this to boundary point (parent, node’s index plus 1).
  277. return set_start_or_end(*parent, node.index() + 1, StartOrEnd::End);
  278. }
  279. // https://dom.spec.whatwg.org/#dom-range-compareboundarypoints
  280. WebIDL::ExceptionOr<WebIDL::Short> Range::compare_boundary_points(WebIDL::UnsignedShort how, Range const& source_range) const
  281. {
  282. // 1. If how is not one of
  283. // - START_TO_START,
  284. // - START_TO_END,
  285. // - END_TO_END, and
  286. // - END_TO_START,
  287. // then throw a "NotSupportedError" DOMException.
  288. if (how != HowToCompareBoundaryPoints::START_TO_START && how != HowToCompareBoundaryPoints::START_TO_END && how != HowToCompareBoundaryPoints::END_TO_END && how != HowToCompareBoundaryPoints::END_TO_START)
  289. return WebIDL::NotSupportedError::create(realm(), MUST(String::formatted("Expected 'how' to be one of START_TO_START (0), START_TO_END (1), END_TO_END (2) or END_TO_START (3), got {}", how)));
  290. // 2. If this’s root is not the same as sourceRange’s root, then throw a "WrongDocumentError" DOMException.
  291. if (&root() != &source_range.root())
  292. return WebIDL::WrongDocumentError::create(realm(), "This range is not in the same tree as the source range."_string);
  293. JS::GCPtr<Node> this_point_node;
  294. u32 this_point_offset = 0;
  295. JS::GCPtr<Node> other_point_node;
  296. u32 other_point_offset = 0;
  297. // 3. If how is:
  298. switch (how) {
  299. case HowToCompareBoundaryPoints::START_TO_START:
  300. // -> START_TO_START:
  301. // Let this point be this’s start. Let other point be sourceRange’s start.
  302. this_point_node = m_start_container;
  303. this_point_offset = m_start_offset;
  304. other_point_node = source_range.m_start_container;
  305. other_point_offset = source_range.m_start_offset;
  306. break;
  307. case HowToCompareBoundaryPoints::START_TO_END:
  308. // -> START_TO_END:
  309. // Let this point be this’s end. Let other point be sourceRange’s start.
  310. this_point_node = m_end_container;
  311. this_point_offset = m_end_offset;
  312. other_point_node = source_range.m_start_container;
  313. other_point_offset = source_range.m_start_offset;
  314. break;
  315. case HowToCompareBoundaryPoints::END_TO_END:
  316. // -> END_TO_END:
  317. // Let this point be this’s end. Let other point be sourceRange’s end.
  318. this_point_node = m_end_container;
  319. this_point_offset = m_end_offset;
  320. other_point_node = source_range.m_end_container;
  321. other_point_offset = source_range.m_end_offset;
  322. break;
  323. case HowToCompareBoundaryPoints::END_TO_START:
  324. // -> END_TO_START:
  325. // Let this point be this’s start. Let other point be sourceRange’s end.
  326. this_point_node = m_start_container;
  327. this_point_offset = m_start_offset;
  328. other_point_node = source_range.m_end_container;
  329. other_point_offset = source_range.m_end_offset;
  330. break;
  331. default:
  332. VERIFY_NOT_REACHED();
  333. }
  334. VERIFY(this_point_node);
  335. VERIFY(other_point_node);
  336. // 4. If the position of this point relative to other point is
  337. auto relative_position = position_of_boundary_point_relative_to_other_boundary_point(*this_point_node, this_point_offset, *other_point_node, other_point_offset);
  338. switch (relative_position) {
  339. case RelativeBoundaryPointPosition::Before:
  340. // -> before
  341. // Return −1.
  342. return -1;
  343. case RelativeBoundaryPointPosition::Equal:
  344. // -> equal
  345. // Return 0.
  346. return 0;
  347. case RelativeBoundaryPointPosition::After:
  348. // -> after
  349. // Return 1.
  350. return 1;
  351. default:
  352. VERIFY_NOT_REACHED();
  353. }
  354. }
  355. // https://dom.spec.whatwg.org/#concept-range-select
  356. WebIDL::ExceptionOr<void> Range::select(Node& node)
  357. {
  358. // 1. Let parent be node’s parent.
  359. auto* parent = node.parent();
  360. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  361. if (!parent)
  362. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_string);
  363. // 3. Let index be node’s index.
  364. auto index = node.index();
  365. // 4. Set range’s start to boundary point (parent, index).
  366. m_start_container = *parent;
  367. m_start_offset = index;
  368. // 5. Set range’s end to boundary point (parent, index plus 1).
  369. m_end_container = *parent;
  370. m_end_offset = index + 1;
  371. update_associated_selection();
  372. return {};
  373. }
  374. // https://dom.spec.whatwg.org/#dom-range-selectnode
  375. WebIDL::ExceptionOr<void> Range::select_node(Node& node)
  376. {
  377. // The selectNode(node) method steps are to select node within this.
  378. return select(node);
  379. }
  380. // https://dom.spec.whatwg.org/#dom-range-collapse
  381. void Range::collapse(bool to_start)
  382. {
  383. // The collapse(toStart) method steps are to, if toStart is true, set end to start; otherwise set start to end.
  384. if (to_start) {
  385. m_end_container = m_start_container;
  386. m_end_offset = m_start_offset;
  387. } else {
  388. m_start_container = m_end_container;
  389. m_start_offset = m_end_offset;
  390. }
  391. update_associated_selection();
  392. }
  393. // https://dom.spec.whatwg.org/#dom-range-selectnodecontents
  394. WebIDL::ExceptionOr<void> Range::select_node_contents(Node& node)
  395. {
  396. // 1. If node is a doctype, throw an "InvalidNodeTypeError" DOMException.
  397. if (is<DocumentType>(node))
  398. return WebIDL::InvalidNodeTypeError::create(realm(), "Node cannot be a DocumentType."_string);
  399. // 2. Let length be the length of node.
  400. auto length = node.length();
  401. // 3. Set start to the boundary point (node, 0).
  402. m_start_container = node;
  403. m_start_offset = 0;
  404. // 4. Set end to the boundary point (node, length).
  405. m_end_container = node;
  406. m_end_offset = length;
  407. update_associated_selection();
  408. return {};
  409. }
  410. JS::NonnullGCPtr<Range> Range::clone_range() const
  411. {
  412. return heap().allocate<Range>(shape().realm(), const_cast<Node&>(*m_start_container), m_start_offset, const_cast<Node&>(*m_end_container), m_end_offset);
  413. }
  414. JS::NonnullGCPtr<Range> Range::inverted() const
  415. {
  416. return heap().allocate<Range>(shape().realm(), const_cast<Node&>(*m_end_container), m_end_offset, const_cast<Node&>(*m_start_container), m_start_offset);
  417. }
  418. JS::NonnullGCPtr<Range> Range::normalized() const
  419. {
  420. if (m_start_container.ptr() == m_end_container.ptr()) {
  421. if (m_start_offset <= m_end_offset)
  422. return clone_range();
  423. return inverted();
  424. }
  425. if (m_start_container->is_before(m_end_container))
  426. return clone_range();
  427. return inverted();
  428. }
  429. // https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer
  430. JS::NonnullGCPtr<Node> Range::common_ancestor_container() const
  431. {
  432. // 1. Let container be start node.
  433. auto container = m_start_container;
  434. // 2. While container is not an inclusive ancestor of end node, let container be container’s parent.
  435. while (!container->is_inclusive_ancestor_of(m_end_container)) {
  436. VERIFY(container->parent());
  437. container = *container->parent();
  438. }
  439. // 3. Return container.
  440. return container;
  441. }
  442. // https://dom.spec.whatwg.org/#dom-range-intersectsnode
  443. bool Range::intersects_node(Node const& node) const
  444. {
  445. // 1. If node’s root is different from this’s root, return false.
  446. if (&node.root() != &root())
  447. return false;
  448. // 2. Let parent be node’s parent.
  449. auto* parent = node.parent();
  450. // 3. If parent is null, return true.
  451. if (!parent)
  452. return true;
  453. // 4. Let offset be node’s index.
  454. auto offset = node.index();
  455. // 5. If (parent, offset) is before end and (parent, offset plus 1) is after start, return true
  456. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(*parent, offset, m_end_container, m_end_offset);
  457. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(*parent, offset + 1, m_start_container, m_start_offset);
  458. if (relative_position_to_end == RelativeBoundaryPointPosition::Before && relative_position_to_start == RelativeBoundaryPointPosition::After)
  459. return true;
  460. // 6. Return false.
  461. return false;
  462. }
  463. // https://dom.spec.whatwg.org/#dom-range-ispointinrange
  464. WebIDL::ExceptionOr<bool> Range::is_point_in_range(Node const& node, WebIDL::UnsignedLong offset) const
  465. {
  466. // 1. If node’s root is different from this’s root, return false.
  467. if (&node.root() != &root())
  468. return false;
  469. // 2. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  470. if (is<DocumentType>(node))
  471. return WebIDL::InvalidNodeTypeError::create(realm(), "Node cannot be a DocumentType."_string);
  472. // 3. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  473. if (offset > node.length())
  474. return WebIDL::IndexSizeError::create(realm(), MUST(String::formatted("Node does not contain a child at offset {}", offset)));
  475. // 4. If (node, offset) is before start or after end, return false.
  476. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset);
  477. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset);
  478. if (relative_position_to_start == RelativeBoundaryPointPosition::Before || relative_position_to_end == RelativeBoundaryPointPosition::After)
  479. return false;
  480. // 5. Return true.
  481. return true;
  482. }
  483. // https://dom.spec.whatwg.org/#dom-range-comparepoint
  484. WebIDL::ExceptionOr<WebIDL::Short> Range::compare_point(Node const& node, WebIDL::UnsignedLong offset) const
  485. {
  486. // 1. If node’s root is different from this’s root, then throw a "WrongDocumentError" DOMException.
  487. if (&node.root() != &root())
  488. return WebIDL::WrongDocumentError::create(realm(), "Given node is not in the same document as the range."_string);
  489. // 2. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  490. if (is<DocumentType>(node))
  491. return WebIDL::InvalidNodeTypeError::create(realm(), "Node cannot be a DocumentType."_string);
  492. // 3. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  493. if (offset > node.length())
  494. return WebIDL::IndexSizeError::create(realm(), MUST(String::formatted("Node does not contain a child at offset {}", offset)));
  495. // 4. If (node, offset) is before start, return −1.
  496. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset);
  497. if (relative_position_to_start == RelativeBoundaryPointPosition::Before)
  498. return -1;
  499. // 5. If (node, offset) is after end, return 1.
  500. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset);
  501. if (relative_position_to_end == RelativeBoundaryPointPosition::After)
  502. return 1;
  503. // 6. Return 0.
  504. return 0;
  505. }
  506. // https://dom.spec.whatwg.org/#dom-range-stringifier
  507. String Range::to_string() const
  508. {
  509. // 1. Let s be the empty string.
  510. StringBuilder builder;
  511. // 2. If this’s start node is this’s end node and it is a Text node,
  512. // then return the substring of that Text node’s data beginning at this’s start offset and ending at this’s end offset.
  513. if (start_container() == end_container() && is<Text>(*start_container())) {
  514. auto const& text = static_cast<Text const&>(*start_container());
  515. return MUST(text.substring_data(start_offset(), end_offset() - start_offset()));
  516. }
  517. // 3. If this’s start node is a Text node, then append the substring of that node’s data from this’s start offset until the end to s.
  518. if (is<Text>(*start_container())) {
  519. auto const& text = static_cast<Text const&>(*start_container());
  520. builder.append(MUST(text.substring_data(start_offset(), text.length_in_utf16_code_units() - start_offset())));
  521. }
  522. // 4. Append the concatenation of the data of all Text nodes that are contained in this, in tree order, to s.
  523. for (Node const* node = start_container(); node != end_container()->next_sibling(); node = node->next_in_pre_order()) {
  524. if (is<Text>(*node) && contains_node(*node))
  525. builder.append(static_cast<Text const&>(*node).data());
  526. }
  527. // 5. If this’s end node is a Text node, then append the substring of that node’s data from its start until this’s end offset to s.
  528. if (is<Text>(*end_container())) {
  529. auto const& text = static_cast<Text const&>(*end_container());
  530. builder.append(MUST(text.substring_data(0, end_offset())));
  531. }
  532. // 6. Return s.
  533. return MUST(builder.to_string());
  534. }
  535. // https://dom.spec.whatwg.org/#dom-range-extractcontents
  536. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::extract_contents()
  537. {
  538. return extract();
  539. }
  540. // https://dom.spec.whatwg.org/#concept-range-extract
  541. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::extract()
  542. {
  543. // 1. Let fragment be a new DocumentFragment node whose node document is range’s start node’s node document.
  544. auto fragment = heap().allocate<DOM::DocumentFragment>(realm(), const_cast<Document&>(start_container()->document()));
  545. // 2. If range is collapsed, then return fragment.
  546. if (collapsed())
  547. return fragment;
  548. // 3. Let original start node, original start offset, original end node, and original end offset
  549. // be range’s start node, start offset, end node, and end offset, respectively.
  550. JS::NonnullGCPtr<Node> original_start_node = m_start_container;
  551. auto original_start_offset = m_start_offset;
  552. JS::NonnullGCPtr<Node> original_end_node = m_end_container;
  553. auto original_end_offset = m_end_offset;
  554. // 4. If original start node is original end node and it is a CharacterData node, then:
  555. if (original_start_node.ptr() == original_end_node.ptr() && is<CharacterData>(*original_start_node)) {
  556. // 1. Let clone be a clone of original start node.
  557. auto clone = TRY(original_start_node->clone_node());
  558. // 2. Set the data of clone to the result of substringing data with node original start node,
  559. // offset original start offset, and count original end offset minus original start offset.
  560. auto result = TRY(static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_end_offset - original_start_offset));
  561. verify_cast<CharacterData>(*clone).set_data(move(result));
  562. // 3. Append clone to fragment.
  563. TRY(fragment->append_child(clone));
  564. // 4. Replace data with node original start node, offset original start offset, count original end offset minus original start offset, and data the empty string.
  565. TRY(static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_end_offset - original_start_offset, String {}));
  566. // 5. Return fragment.
  567. return fragment;
  568. }
  569. // 5. Let common ancestor be original start node.
  570. JS::NonnullGCPtr<Node> common_ancestor = original_start_node;
  571. // 6. While common ancestor is not an inclusive ancestor of original end node, set common ancestor to its own parent.
  572. while (!common_ancestor->is_inclusive_ancestor_of(original_end_node))
  573. common_ancestor = *common_ancestor->parent_node();
  574. // 7. Let first partially contained child be null.
  575. JS::GCPtr<Node> first_partially_contained_child;
  576. // 8. If original start node is not an inclusive ancestor of original end node,
  577. // set first partially contained child to the first child of common ancestor that is partially contained in range.
  578. if (!original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  579. for (auto* child = common_ancestor->first_child(); child; child = child->next_sibling()) {
  580. if (partially_contains_node(*child)) {
  581. first_partially_contained_child = child;
  582. break;
  583. }
  584. }
  585. }
  586. // 9. Let last partially contained child be null.
  587. JS::GCPtr<Node> last_partially_contained_child;
  588. // 10. If original end node is not an inclusive ancestor of original start node,
  589. // set last partially contained child to the last child of common ancestor that is partially contained in range.
  590. if (!original_end_node->is_inclusive_ancestor_of(original_start_node)) {
  591. for (auto* child = common_ancestor->last_child(); child; child = child->previous_sibling()) {
  592. if (partially_contains_node(*child)) {
  593. last_partially_contained_child = child;
  594. break;
  595. }
  596. }
  597. }
  598. // 11. Let contained children be a list of all children of common ancestor that are contained in range, in tree order.
  599. Vector<JS::NonnullGCPtr<Node>> contained_children;
  600. for (Node* node = common_ancestor->first_child(); node; node = node->next_sibling()) {
  601. if (contains_node(*node))
  602. contained_children.append(*node);
  603. }
  604. // 12. If any member of contained children is a doctype, then throw a "HierarchyRequestError" DOMException.
  605. for (auto const& child : contained_children) {
  606. if (is<DocumentType>(*child))
  607. return WebIDL::HierarchyRequestError::create(realm(), "Contained child is a DocumentType"_string);
  608. }
  609. JS::GCPtr<Node> new_node;
  610. size_t new_offset = 0;
  611. // 13. If original start node is an inclusive ancestor of original end node, set new node to original start node and new offset to original start offset.
  612. if (original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  613. new_node = original_start_node;
  614. new_offset = original_start_offset;
  615. }
  616. // 14. Otherwise:
  617. else {
  618. // 1. Let reference node equal original start node.
  619. JS::GCPtr<Node> reference_node = original_start_node;
  620. // 2. While reference node’s parent is not null and is not an inclusive ancestor of original end node, set reference node to its parent.
  621. while (reference_node->parent_node() && !reference_node->parent_node()->is_inclusive_ancestor_of(original_end_node))
  622. reference_node = reference_node->parent_node();
  623. // 3. Set new node to the parent of reference node, and new offset to one plus reference node’s index.
  624. new_node = reference_node->parent_node();
  625. new_offset = 1 + reference_node->index();
  626. }
  627. // 15. If first partially contained child is a CharacterData node, then:
  628. if (first_partially_contained_child && is<CharacterData>(*first_partially_contained_child)) {
  629. // 1. Let clone be a clone of original start node.
  630. auto clone = TRY(original_start_node->clone_node());
  631. // 2. Set the data of clone to the result of substringing data with node original start node, offset original start offset,
  632. // and count original start node’s length minus original start offset.
  633. auto result = TRY(static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_start_node->length() - original_start_offset));
  634. verify_cast<CharacterData>(*clone).set_data(move(result));
  635. // 3. Append clone to fragment.
  636. TRY(fragment->append_child(clone));
  637. // 4. Replace data with node original start node, offset original start offset, count original start node’s length minus original start offset, and data the empty string.
  638. TRY(static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_start_node->length() - original_start_offset, String {}));
  639. }
  640. // 16. Otherwise, if first partially contained child is not null:
  641. else if (first_partially_contained_child) {
  642. // 1. Let clone be a clone of first partially contained child.
  643. auto clone = TRY(first_partially_contained_child->clone_node());
  644. // 2. Append clone to fragment.
  645. TRY(fragment->append_child(clone));
  646. // 3. Let subrange be a new live range whose start is (original start node, original start offset) and whose end is (first partially contained child, first partially contained child’s length).
  647. auto subrange = Range::create(original_start_node, original_start_offset, *first_partially_contained_child, first_partially_contained_child->length());
  648. // 4. Let subfragment be the result of extracting subrange.
  649. auto subfragment = TRY(subrange->extract());
  650. // 5. Append subfragment to clone.
  651. TRY(clone->append_child(subfragment));
  652. }
  653. // 17. For each contained child in contained children, append contained child to fragment.
  654. for (auto& contained_child : contained_children) {
  655. TRY(fragment->append_child(contained_child));
  656. }
  657. // 18. If last partially contained child is a CharacterData node, then:
  658. if (last_partially_contained_child && is<CharacterData>(*last_partially_contained_child)) {
  659. // 1. Let clone be a clone of original end node.
  660. auto clone = TRY(original_end_node->clone_node());
  661. // 2. Set the data of clone to the result of substringing data with node original end node, offset 0, and count original end offset.
  662. auto result = TRY(static_cast<CharacterData const&>(*original_end_node).substring_data(0, original_end_offset));
  663. verify_cast<CharacterData>(*clone).set_data(move(result));
  664. // 3. Append clone to fragment.
  665. TRY(fragment->append_child(clone));
  666. // 4. Replace data with node original end node, offset 0, count original end offset, and data the empty string.
  667. TRY(verify_cast<CharacterData>(*original_end_node).replace_data(0, original_end_offset, String {}));
  668. }
  669. // 19. Otherwise, if last partially contained child is not null:
  670. else if (last_partially_contained_child) {
  671. // 1. Let clone be a clone of last partially contained child.
  672. auto clone = TRY(last_partially_contained_child->clone_node());
  673. // 2. Append clone to fragment.
  674. TRY(fragment->append_child(clone));
  675. // 3. Let subrange be a new live range whose start is (last partially contained child, 0) and whose end is (original end node, original end offset).
  676. auto subrange = Range::create(*last_partially_contained_child, 0, original_end_node, original_end_offset);
  677. // 4. Let subfragment be the result of extracting subrange.
  678. auto subfragment = TRY(subrange->extract());
  679. // 5. Append subfragment to clone.
  680. TRY(clone->append_child(subfragment));
  681. }
  682. // 20. Set range’s start and end to (new node, new offset).
  683. TRY(set_start(*new_node, new_offset));
  684. TRY(set_end(*new_node, new_offset));
  685. // 21. Return fragment.
  686. return fragment;
  687. }
  688. // https://dom.spec.whatwg.org/#contained
  689. bool Range::contains_node(Node const& node) const
  690. {
  691. // A node node is contained in a live range range if node’s root is range’s root,
  692. if (&node.root() != &root())
  693. return false;
  694. // and (node, 0) is after range’s start,
  695. if (position_of_boundary_point_relative_to_other_boundary_point(node, 0, m_start_container, m_start_offset) != RelativeBoundaryPointPosition::After)
  696. return false;
  697. // and (node, node’s length) is before range’s end.
  698. if (position_of_boundary_point_relative_to_other_boundary_point(node, node.length(), m_end_container, m_end_offset) != RelativeBoundaryPointPosition::Before)
  699. return false;
  700. return true;
  701. }
  702. // https://dom.spec.whatwg.org/#partially-contained
  703. bool Range::partially_contains_node(Node const& node) const
  704. {
  705. // A node is partially contained in a live range if it’s an inclusive ancestor of the live range’s start node but not its end node, or vice versa.
  706. if (node.is_inclusive_ancestor_of(m_start_container) && &node != m_end_container.ptr())
  707. return true;
  708. if (node.is_inclusive_ancestor_of(m_end_container) && &node != m_start_container.ptr())
  709. return true;
  710. return false;
  711. }
  712. // https://dom.spec.whatwg.org/#dom-range-insertnode
  713. WebIDL::ExceptionOr<void> Range::insert_node(JS::NonnullGCPtr<Node> node)
  714. {
  715. return insert(node);
  716. }
  717. // https://dom.spec.whatwg.org/#concept-range-insert
  718. WebIDL::ExceptionOr<void> Range::insert(JS::NonnullGCPtr<Node> node)
  719. {
  720. // 1. If range’s start node is a ProcessingInstruction or Comment node, is a Text node whose parent is null, or is node, then throw a "HierarchyRequestError" DOMException.
  721. if ((is<ProcessingInstruction>(*m_start_container) || is<Comment>(*m_start_container))
  722. || (is<Text>(*m_start_container) && !m_start_container->parent_node())
  723. || m_start_container.ptr() == node.ptr()) {
  724. return WebIDL::HierarchyRequestError::create(realm(), "Range has inappropriate start node for insertion"_string);
  725. }
  726. // 2. Let referenceNode be null.
  727. JS::GCPtr<Node> reference_node;
  728. // 3. If range’s start node is a Text node, set referenceNode to that Text node.
  729. if (is<Text>(*m_start_container)) {
  730. reference_node = m_start_container;
  731. }
  732. // 4. Otherwise, set referenceNode to the child of start node whose index is start offset, and null if there is no such child.
  733. else {
  734. reference_node = m_start_container->child_at_index(m_start_offset);
  735. }
  736. // 5. Let parent be range’s start node if referenceNode is null, and referenceNode’s parent otherwise.
  737. JS::GCPtr<Node> parent;
  738. if (!reference_node)
  739. parent = m_start_container;
  740. else
  741. parent = reference_node->parent();
  742. // 6. Ensure pre-insertion validity of node into parent before referenceNode.
  743. TRY(parent->ensure_pre_insertion_validity(node, reference_node));
  744. // 7. If range’s start node is a Text node, set referenceNode to the result of splitting it with offset range’s start offset.
  745. if (is<Text>(*m_start_container))
  746. reference_node = TRY(static_cast<Text&>(*m_start_container).split_text(m_start_offset));
  747. // 8. If node is referenceNode, set referenceNode to its next sibling.
  748. if (node == reference_node)
  749. reference_node = reference_node->next_sibling();
  750. // 9. If node’s parent is non-null, then remove node.
  751. if (node->parent())
  752. node->remove();
  753. // 10. Let newOffset be parent’s length if referenceNode is null, and referenceNode’s index otherwise.
  754. size_t new_offset = 0;
  755. if (!reference_node)
  756. new_offset = parent->length();
  757. else
  758. new_offset = reference_node->index();
  759. // 11. Increase newOffset by node’s length if node is a DocumentFragment node, and one otherwise.
  760. if (is<DocumentFragment>(*node))
  761. new_offset += node->length();
  762. else
  763. new_offset += 1;
  764. // 12. Pre-insert node into parent before referenceNode.
  765. (void)TRY(parent->pre_insert(node, reference_node));
  766. // 13. If range is collapsed, then set range’s end to (parent, newOffset).
  767. if (collapsed())
  768. TRY(set_end(*parent, new_offset));
  769. return {};
  770. }
  771. // https://dom.spec.whatwg.org/#dom-range-surroundcontents
  772. WebIDL::ExceptionOr<void> Range::surround_contents(JS::NonnullGCPtr<Node> new_parent)
  773. {
  774. // 1. If a non-Text node is partially contained in this, then throw an "InvalidStateError" DOMException.
  775. Node* start_non_text_node = start_container();
  776. if (is<Text>(*start_non_text_node))
  777. start_non_text_node = start_non_text_node->parent_node();
  778. Node* end_non_text_node = end_container();
  779. if (is<Text>(*end_non_text_node))
  780. end_non_text_node = end_non_text_node->parent_node();
  781. if (start_non_text_node != end_non_text_node)
  782. return WebIDL::InvalidStateError::create(realm(), "Non-Text node is partially contained in range."_string);
  783. // 2. If newParent is a Document, DocumentType, or DocumentFragment node, then throw an "InvalidNodeTypeError" DOMException.
  784. if (is<Document>(*new_parent) || is<DocumentType>(*new_parent) || is<DocumentFragment>(*new_parent))
  785. return WebIDL::InvalidNodeTypeError::create(realm(), "Invalid parent node type"_string);
  786. // 3. Let fragment be the result of extracting this.
  787. auto fragment = TRY(extract());
  788. // 4. If newParent has children, then replace all with null within newParent.
  789. if (new_parent->has_children())
  790. new_parent->replace_all(nullptr);
  791. // 5. Insert newParent into this.
  792. TRY(insert(new_parent));
  793. // 6. Append fragment to newParent.
  794. (void)TRY(new_parent->append_child(fragment));
  795. // 7. Select newParent within this.
  796. return select(*new_parent);
  797. }
  798. // https://dom.spec.whatwg.org/#dom-range-clonecontents
  799. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::clone_contents()
  800. {
  801. return clone_the_contents();
  802. }
  803. // https://dom.spec.whatwg.org/#concept-range-clone
  804. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::clone_the_contents()
  805. {
  806. // 1. Let fragment be a new DocumentFragment node whose node document is range’s start node’s node document.
  807. auto fragment = heap().allocate<DOM::DocumentFragment>(realm(), const_cast<Document&>(start_container()->document()));
  808. // 2. If range is collapsed, then return fragment.
  809. if (collapsed())
  810. return fragment;
  811. // 3. Let original start node, original start offset, original end node, and original end offset
  812. // be range’s start node, start offset, end node, and end offset, respectively.
  813. JS::NonnullGCPtr<Node> original_start_node = m_start_container;
  814. auto original_start_offset = m_start_offset;
  815. JS::NonnullGCPtr<Node> original_end_node = m_end_container;
  816. auto original_end_offset = m_end_offset;
  817. // 4. If original start node is original end node and it is a CharacterData node, then:
  818. if (original_start_node.ptr() == original_end_node.ptr() && is<CharacterData>(*original_start_node)) {
  819. // 1. Let clone be a clone of original start node.
  820. auto clone = TRY(original_start_node->clone_node());
  821. // 2. Set the data of clone to the result of substringing data with node original start node,
  822. // offset original start offset, and count original end offset minus original start offset.
  823. auto result = TRY(static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_end_offset - original_start_offset));
  824. verify_cast<CharacterData>(*clone).set_data(move(result));
  825. // 3. Append clone to fragment.
  826. TRY(fragment->append_child(clone));
  827. // 4. Return fragment.
  828. return fragment;
  829. }
  830. // 5. Let common ancestor be original start node.
  831. JS::NonnullGCPtr<Node> common_ancestor = original_start_node;
  832. // 6. While common ancestor is not an inclusive ancestor of original end node, set common ancestor to its own parent.
  833. while (!common_ancestor->is_inclusive_ancestor_of(original_end_node))
  834. common_ancestor = *common_ancestor->parent_node();
  835. // 7. Let first partially contained child be null.
  836. JS::GCPtr<Node> first_partially_contained_child;
  837. // 8. If original start node is not an inclusive ancestor of original end node,
  838. // set first partially contained child to the first child of common ancestor that is partially contained in range.
  839. if (!original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  840. for (auto* child = common_ancestor->first_child(); child; child = child->next_sibling()) {
  841. if (partially_contains_node(*child)) {
  842. first_partially_contained_child = child;
  843. break;
  844. }
  845. }
  846. }
  847. // 9. Let last partially contained child be null.
  848. JS::GCPtr<Node> last_partially_contained_child;
  849. // 10. If original end node is not an inclusive ancestor of original start node,
  850. // set last partially contained child to the last child of common ancestor that is partially contained in range.
  851. if (!original_end_node->is_inclusive_ancestor_of(original_start_node)) {
  852. for (auto* child = common_ancestor->last_child(); child; child = child->previous_sibling()) {
  853. if (partially_contains_node(*child)) {
  854. last_partially_contained_child = child;
  855. break;
  856. }
  857. }
  858. }
  859. // 11. Let contained children be a list of all children of common ancestor that are contained in range, in tree order.
  860. Vector<JS::NonnullGCPtr<Node>> contained_children;
  861. for (Node* node = common_ancestor->first_child(); node; node = node->next_sibling()) {
  862. if (contains_node(*node))
  863. contained_children.append(*node);
  864. }
  865. // 12. If any member of contained children is a doctype, then throw a "HierarchyRequestError" DOMException.
  866. for (auto const& child : contained_children) {
  867. if (is<DocumentType>(*child))
  868. return WebIDL::HierarchyRequestError::create(realm(), "Contained child is a DocumentType"_string);
  869. }
  870. // 13. If first partially contained child is a CharacterData node, then:
  871. if (first_partially_contained_child && is<CharacterData>(*first_partially_contained_child)) {
  872. // 1. Let clone be a clone of original start node.
  873. auto clone = TRY(original_start_node->clone_node());
  874. // 2. Set the data of clone to the result of substringing data with node original start node, offset original start offset,
  875. // and count original start node’s length minus original start offset.
  876. auto result = TRY(static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_start_node->length() - original_start_offset));
  877. verify_cast<CharacterData>(*clone).set_data(move(result));
  878. // 3. Append clone to fragment.
  879. TRY(fragment->append_child(clone));
  880. }
  881. // 14. Otherwise, if first partially contained child is not null:
  882. else if (first_partially_contained_child) {
  883. // 1. Let clone be a clone of first partially contained child.
  884. auto clone = TRY(first_partially_contained_child->clone_node());
  885. // 2. Append clone to fragment.
  886. TRY(fragment->append_child(clone));
  887. // 3. Let subrange be a new live range whose start is (original start node, original start offset) and whose end is (first partially contained child, first partially contained child’s length).
  888. auto subrange = Range::create(original_start_node, original_start_offset, *first_partially_contained_child, first_partially_contained_child->length());
  889. // 4. Let subfragment be the result of cloning the contents of subrange.
  890. auto subfragment = TRY(subrange->clone_the_contents());
  891. // 5. Append subfragment to clone.
  892. TRY(clone->append_child(subfragment));
  893. }
  894. // 15. For each contained child in contained children.
  895. for (auto& contained_child : contained_children) {
  896. // 1. Let clone be a clone of contained child with the clone children flag set.
  897. auto clone = TRY(contained_child->clone_node(nullptr, true));
  898. // 2. Append clone to fragment.
  899. TRY(fragment->append_child(move(clone)));
  900. }
  901. // 16. If last partially contained child is a CharacterData node, then:
  902. if (last_partially_contained_child && is<CharacterData>(*last_partially_contained_child)) {
  903. // 1. Let clone be a clone of original end node.
  904. auto clone = TRY(original_end_node->clone_node());
  905. // 2. Set the data of clone to the result of substringing data with node original end node, offset 0, and count original end offset.
  906. auto result = TRY(static_cast<CharacterData const&>(*original_end_node).substring_data(0, original_end_offset));
  907. verify_cast<CharacterData>(*clone).set_data(move(result));
  908. // 3. Append clone to fragment.
  909. TRY(fragment->append_child(clone));
  910. }
  911. // 17. Otherwise, if last partially contained child is not null:
  912. else if (last_partially_contained_child) {
  913. // 1. Let clone be a clone of last partially contained child.
  914. auto clone = TRY(last_partially_contained_child->clone_node());
  915. // 2. Append clone to fragment.
  916. TRY(fragment->append_child(clone));
  917. // 3. Let subrange be a new live range whose start is (last partially contained child, 0) and whose end is (original end node, original end offset).
  918. auto subrange = Range::create(*last_partially_contained_child, 0, original_end_node, original_end_offset);
  919. // 4. Let subfragment be the result of cloning the contents of subrange.
  920. auto subfragment = TRY(subrange->clone_the_contents());
  921. // 5. Append subfragment to clone.
  922. TRY(clone->append_child(subfragment));
  923. }
  924. // 18. Return fragment.
  925. return fragment;
  926. }
  927. // https://dom.spec.whatwg.org/#dom-range-deletecontents
  928. WebIDL::ExceptionOr<void> Range::delete_contents()
  929. {
  930. // 1. If this is collapsed, then return.
  931. if (collapsed())
  932. return {};
  933. // 2. Let original start node, original start offset, original end node, and original end offset be this’s start node, start offset, end node, and end offset, respectively.
  934. JS::NonnullGCPtr<Node> original_start_node = m_start_container;
  935. auto original_start_offset = m_start_offset;
  936. JS::NonnullGCPtr<Node> original_end_node = m_end_container;
  937. auto original_end_offset = m_end_offset;
  938. // 3. If original start node is original end node and it is a CharacterData node, then replace data with node original start node, offset original start offset,
  939. // count original end offset minus original start offset, and data the empty string, and then return.
  940. if (original_start_node.ptr() == original_end_node.ptr() && is<CharacterData>(*original_start_node)) {
  941. TRY(static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_end_offset - original_start_offset, String {}));
  942. return {};
  943. }
  944. // 4. Let nodes to remove be a list of all the nodes that are contained in this, in tree order, omitting any node whose parent is also contained in this.
  945. JS::MarkedVector<Node*> nodes_to_remove(heap());
  946. for (Node const* node = start_container(); node != end_container()->next_sibling(); node = node->next_in_pre_order()) {
  947. if (contains_node(*node) && (!node->parent_node() || !contains_node(*node->parent_node())))
  948. nodes_to_remove.append(const_cast<Node*>(node));
  949. }
  950. JS::GCPtr<Node> new_node;
  951. size_t new_offset = 0;
  952. // 5. If original start node is an inclusive ancestor of original end node, set new node to original start node and new offset to original start offset.
  953. if (original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  954. new_node = original_start_node;
  955. new_offset = original_start_offset;
  956. }
  957. // 6. Otherwise
  958. else {
  959. // 1. Let reference node equal original start node.
  960. auto reference_node = original_start_node;
  961. // 2. While reference node’s parent is not null and is not an inclusive ancestor of original end node, set reference node to its parent.
  962. while (reference_node->parent_node() && !reference_node->parent_node()->is_inclusive_ancestor_of(original_end_node))
  963. reference_node = *reference_node->parent_node();
  964. // 3. Set new node to the parent of reference node, and new offset to one plus the index of reference node.
  965. new_node = reference_node->parent_node();
  966. new_offset = 1 + reference_node->index();
  967. }
  968. // 7. If original start node is a CharacterData node, then replace data with node original start node, offset original start offset, count original start node’s length minus original start offset, data the empty string.
  969. if (is<CharacterData>(*original_start_node))
  970. TRY(static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_start_node->length() - original_start_offset, String {}));
  971. // 8. For each node in nodes to remove, in tree order, remove node.
  972. for (auto& node : nodes_to_remove)
  973. node->remove();
  974. // 9. If original end node is a CharacterData node, then replace data with node original end node, offset 0, count original end offset and data the empty string.
  975. if (is<CharacterData>(*original_end_node))
  976. TRY(static_cast<CharacterData&>(*original_end_node).replace_data(0, original_end_offset, String {}));
  977. // 10. Set start and end to (new node, new offset).
  978. TRY(set_start(*new_node, new_offset));
  979. TRY(set_end(*new_node, new_offset));
  980. return {};
  981. }
  982. // https://drafts.csswg.org/cssom-view/#dom-element-getclientrects
  983. // https://drafts.csswg.org/cssom-view/#extensions-to-the-range-interface
  984. JS::NonnullGCPtr<Geometry::DOMRectList> Range::get_client_rects()
  985. {
  986. // 1. return an empty DOMRectList object if the range is not in the document
  987. if (!start_container()->document().navigable())
  988. return Geometry::DOMRectList::create(realm(), {});
  989. start_container()->document().update_layout();
  990. update_associated_selection();
  991. Vector<JS::Handle<Geometry::DOMRect>> rects;
  992. // FIXME: take Range collapsed into consideration
  993. // 2. Iterate the node included in Range
  994. auto start_node = start_container();
  995. auto end_node = end_container();
  996. if (!is<DOM::Text>(start_node)) {
  997. start_node = start_node->child_at_index(m_start_offset);
  998. }
  999. if (!is<DOM::Text>(end_node)) {
  1000. // end offset shouldn't be 0
  1001. if (m_end_offset == 0)
  1002. return Geometry::DOMRectList::create(realm(), {});
  1003. end_node = end_node->child_at_index(m_end_offset - 1);
  1004. }
  1005. for (Node const* node = start_node; node && node != end_node->next_in_pre_order(); node = node->next_in_pre_order()) {
  1006. auto node_type = static_cast<NodeType>(node->node_type());
  1007. if (node_type == NodeType::ELEMENT_NODE) {
  1008. // 1. For each element selected by the range, whose parent is not selected by the range, include the border
  1009. // areas returned by invoking getClientRects() on the element.
  1010. if (contains_node(*node) && !contains_node(*node->parent())) {
  1011. auto const& element = static_cast<DOM::Element const&>(*node);
  1012. JS::NonnullGCPtr<Geometry::DOMRectList> const element_rects = element.get_client_rects();
  1013. for (u32 i = 0; i < element_rects->length(); i++) {
  1014. auto rect = element_rects->item(i);
  1015. rects.append(Geometry::DOMRect::create(realm(),
  1016. Gfx::FloatRect(rect->x(), rect->y(), rect->width(), rect->height())));
  1017. }
  1018. }
  1019. } else if (node_type == NodeType::TEXT_NODE) {
  1020. // 2. For each Text node selected or partially selected by the range (including when the boundary-points
  1021. // are identical), include scaled DOMRect object (for the part that is selected, not the whole line box).
  1022. auto const& text = static_cast<DOM::Text const&>(*node);
  1023. auto const* paintable = text.paintable();
  1024. if (paintable) {
  1025. auto const* containing_block = paintable->containing_block();
  1026. if (is<Painting::PaintableWithLines>(*containing_block)) {
  1027. auto const& paintable_lines = static_cast<Painting::PaintableWithLines const&>(*containing_block);
  1028. auto fragments = paintable_lines.fragments();
  1029. auto const& font = paintable->layout_node().first_available_font();
  1030. for (auto frag = fragments.begin(); frag != fragments.end(); frag++) {
  1031. auto rect = frag->range_rect(font, start_offset(), end_offset());
  1032. if (rect.is_empty())
  1033. continue;
  1034. rects.append(Geometry::DOMRect::create(realm(),
  1035. Gfx::FloatRect(rect)));
  1036. }
  1037. } else {
  1038. dbgln("FIXME: Failed to get client rects for node {}", node->debug_description());
  1039. }
  1040. }
  1041. }
  1042. }
  1043. return Geometry::DOMRectList::create(realm(), move(rects));
  1044. }
  1045. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-range-getboundingclientrect
  1046. JS::NonnullGCPtr<Geometry::DOMRect> Range::get_bounding_client_rect()
  1047. {
  1048. // 1. Let list be the result of invoking getClientRects() on element.
  1049. auto list = get_client_rects();
  1050. // 2. If the list is empty return a DOMRect object whose x, y, width and height members are zero.
  1051. if (list->length() == 0)
  1052. return Geometry::DOMRect::construct_impl(realm(), 0, 0, 0, 0).release_value_but_fixme_should_propagate_errors();
  1053. // 3. If all rectangles in list have zero width or height, return the first rectangle in list.
  1054. auto all_rectangle_has_zero_width_or_height = true;
  1055. for (auto i = 0u; i < list->length(); ++i) {
  1056. auto const& rect = list->item(i);
  1057. if (rect->width() != 0 && rect->height() != 0) {
  1058. all_rectangle_has_zero_width_or_height = false;
  1059. break;
  1060. }
  1061. }
  1062. if (all_rectangle_has_zero_width_or_height)
  1063. return JS::NonnullGCPtr { *const_cast<Geometry::DOMRect*>(list->item(0)) };
  1064. // 4. Otherwise, return a DOMRect object describing the smallest rectangle that includes all of the rectangles in
  1065. // list of which the height or width is not zero.
  1066. auto const* first_rect = list->item(0);
  1067. auto bounding_rect = Gfx::Rect { first_rect->x(), first_rect->y(), first_rect->width(), first_rect->height() };
  1068. for (auto i = 1u; i < list->length(); ++i) {
  1069. auto const& rect = list->item(i);
  1070. if (rect->width() == 0 || rect->height() == 0)
  1071. continue;
  1072. bounding_rect = bounding_rect.united({ rect->x(), rect->y(), rect->width(), rect->height() });
  1073. }
  1074. return Geometry::DOMRect::create(realm(), bounding_rect.to_type<float>());
  1075. }
  1076. // https://html.spec.whatwg.org/multipage/dynamic-markup-insertion.html#dom-range-createcontextualfragment
  1077. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::create_contextual_fragment(String const& string)
  1078. {
  1079. // FIXME: Let compliantString be the result of invoking the Get Trusted Type compliant string algorithm with TrustedHTML, this's relevant global object, string, and "Range createContextualFragment".
  1080. // 2. Let node be this's start node.
  1081. JS::NonnullGCPtr<Node> node = *start_container();
  1082. // 3. Let element be null.
  1083. JS::GCPtr<Element> element = nullptr;
  1084. auto node_type = static_cast<NodeType>(node->node_type());
  1085. // 4. If node implements Element, set element to node.
  1086. if (node_type == NodeType::ELEMENT_NODE)
  1087. element = static_cast<DOM::Element&>(*node);
  1088. // 5. Otherwise, if node implements Text or Comment node, set element to node's parent element.
  1089. else if (first_is_one_of(node_type, NodeType::TEXT_NODE, NodeType::COMMENT_NODE))
  1090. element = node->parent_element();
  1091. // 6. If either element is null or all of the following are true:
  1092. // - element's node document is an HTML document,
  1093. // - element's local name is "html"; and
  1094. // - element's namespace is the HTML namespace;
  1095. if (!element || is<HTML::HTMLHtmlElement>(*element)) {
  1096. // then set element to the result of creating an element given this's node document,
  1097. // body, and the HTML namespace.
  1098. element = TRY(DOM::create_element(node->document(), HTML::TagNames::body, Namespace::HTML));
  1099. }
  1100. // 7. Let fragment node be the result of invoking the fragment parsing algorithm steps with element and compliantString. FIXME: Use compliantString.
  1101. auto fragment_node = TRY(element->parse_fragment(string));
  1102. // 8. For each script of fragment node's script element descendants:
  1103. fragment_node->for_each_in_subtree_of_type<HTML::HTMLScriptElement>([&](HTML::HTMLScriptElement& script_element) {
  1104. // 8.1 Set scripts already started to false.
  1105. script_element.unmark_as_already_started({});
  1106. // 8.2 Set scripts parser document to null.
  1107. script_element.unmark_as_parser_inserted({});
  1108. return TraversalDecision::Continue;
  1109. });
  1110. // 5. Return fragment node.
  1111. return fragment_node;
  1112. }
  1113. void Range::increase_start_offset(Badge<Node>, WebIDL::UnsignedLong count)
  1114. {
  1115. m_start_offset += count;
  1116. }
  1117. void Range::increase_end_offset(Badge<Node>, WebIDL::UnsignedLong count)
  1118. {
  1119. m_end_offset += count;
  1120. }
  1121. void Range::decrease_start_offset(Badge<Node>, WebIDL::UnsignedLong count)
  1122. {
  1123. m_start_offset -= count;
  1124. }
  1125. void Range::decrease_end_offset(Badge<Node>, WebIDL::UnsignedLong count)
  1126. {
  1127. m_end_offset -= count;
  1128. }
  1129. }