Range.cpp 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2022-2023, Andreas Kling <kling@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibWeb/Bindings/Intrinsics.h>
  9. #include <LibWeb/DOM/Comment.h>
  10. #include <LibWeb/DOM/Document.h>
  11. #include <LibWeb/DOM/DocumentFragment.h>
  12. #include <LibWeb/DOM/DocumentType.h>
  13. #include <LibWeb/DOM/ElementFactory.h>
  14. #include <LibWeb/DOM/Node.h>
  15. #include <LibWeb/DOM/ProcessingInstruction.h>
  16. #include <LibWeb/DOM/Range.h>
  17. #include <LibWeb/DOM/Text.h>
  18. #include <LibWeb/DOMParsing/InnerHTML.h>
  19. #include <LibWeb/Geometry/DOMRect.h>
  20. #include <LibWeb/HTML/HTMLHtmlElement.h>
  21. #include <LibWeb/HTML/Window.h>
  22. #include <LibWeb/Layout/Viewport.h>
  23. #include <LibWeb/Namespace.h>
  24. namespace Web::DOM {
  25. HashTable<Range*>& Range::live_ranges()
  26. {
  27. static HashTable<Range*> ranges;
  28. return ranges;
  29. }
  30. JS::NonnullGCPtr<Range> Range::create(HTML::Window& window)
  31. {
  32. return Range::create(window.associated_document());
  33. }
  34. JS::NonnullGCPtr<Range> Range::create(Document& document)
  35. {
  36. auto& realm = document.realm();
  37. return realm.heap().allocate<Range>(realm, document);
  38. }
  39. JS::NonnullGCPtr<Range> Range::create(Node& start_container, u32 start_offset, Node& end_container, u32 end_offset)
  40. {
  41. auto& realm = start_container.realm();
  42. return realm.heap().allocate<Range>(realm, start_container, start_offset, end_container, end_offset);
  43. }
  44. WebIDL::ExceptionOr<JS::NonnullGCPtr<Range>> Range::construct_impl(JS::Realm& realm)
  45. {
  46. auto& window = verify_cast<HTML::Window>(realm.global_object());
  47. return Range::create(window);
  48. }
  49. Range::Range(Document& document)
  50. : Range(document, 0, document, 0)
  51. {
  52. }
  53. Range::Range(Node& start_container, u32 start_offset, Node& end_container, u32 end_offset)
  54. : AbstractRange(start_container, start_offset, end_container, end_offset)
  55. {
  56. live_ranges().set(this);
  57. }
  58. Range::~Range()
  59. {
  60. live_ranges().remove(this);
  61. }
  62. void Range::initialize(JS::Realm& realm)
  63. {
  64. Base::initialize(realm);
  65. set_prototype(&Bindings::ensure_web_prototype<Bindings::RangePrototype>(realm, "Range"));
  66. }
  67. void Range::visit_edges(Cell::Visitor& visitor)
  68. {
  69. Base::visit_edges(visitor);
  70. visitor.visit(m_associated_selection);
  71. }
  72. void Range::set_associated_selection(Badge<Selection::Selection>, JS::GCPtr<Selection::Selection> selection)
  73. {
  74. m_associated_selection = selection;
  75. update_associated_selection();
  76. }
  77. void Range::update_associated_selection()
  78. {
  79. if (!m_associated_selection)
  80. return;
  81. if (auto* layout_root = m_associated_selection->document()->layout_node()) {
  82. layout_root->recompute_selection_states();
  83. layout_root->set_needs_display();
  84. }
  85. }
  86. // https://dom.spec.whatwg.org/#concept-range-root
  87. Node& Range::root()
  88. {
  89. // The root of a live range is the root of its start node.
  90. return m_start_container->root();
  91. }
  92. Node const& Range::root() const
  93. {
  94. return m_start_container->root();
  95. }
  96. // https://dom.spec.whatwg.org/#concept-range-bp-position
  97. RelativeBoundaryPointPosition position_of_boundary_point_relative_to_other_boundary_point(Node const& node_a, u32 offset_a, Node const& node_b, u32 offset_b)
  98. {
  99. // 1. Assert: nodeA and nodeB have the same root.
  100. VERIFY(&node_a.root() == &node_b.root());
  101. // 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.
  102. if (&node_a == &node_b) {
  103. if (offset_a == offset_b)
  104. return RelativeBoundaryPointPosition::Equal;
  105. if (offset_a < offset_b)
  106. return RelativeBoundaryPointPosition::Before;
  107. return RelativeBoundaryPointPosition::After;
  108. }
  109. // 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.
  110. if (node_a.is_following(node_b)) {
  111. auto relative_position = position_of_boundary_point_relative_to_other_boundary_point(node_b, offset_b, node_a, offset_a);
  112. if (relative_position == RelativeBoundaryPointPosition::Before)
  113. return RelativeBoundaryPointPosition::After;
  114. if (relative_position == RelativeBoundaryPointPosition::After)
  115. return RelativeBoundaryPointPosition::Before;
  116. }
  117. // 4. If nodeA is an ancestor of nodeB:
  118. if (node_a.is_ancestor_of(node_b)) {
  119. // 1. Let child be nodeB.
  120. JS::NonnullGCPtr<Node const> child = node_b;
  121. // 2. While child is not a child of nodeA, set child to its parent.
  122. while (!node_a.is_parent_of(child)) {
  123. auto* parent = child->parent();
  124. VERIFY(parent);
  125. child = *parent;
  126. }
  127. // 3. If child’s index is less than offsetA, then return after.
  128. if (child->index() < offset_a)
  129. return RelativeBoundaryPointPosition::After;
  130. }
  131. // 5. Return before.
  132. return RelativeBoundaryPointPosition::Before;
  133. }
  134. WebIDL::ExceptionOr<void> Range::set_start_or_end(Node& node, u32 offset, StartOrEnd start_or_end)
  135. {
  136. // To set the start or end of a range to a boundary point (node, offset), run these steps:
  137. // 1. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  138. if (is<DocumentType>(node))
  139. return WebIDL::InvalidNodeTypeError::create(realm(), "Node cannot be a DocumentType."_fly_string);
  140. // 2. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  141. if (offset > node.length())
  142. return WebIDL::IndexSizeError::create(realm(), MUST(String::formatted("Node does not contain a child at offset {}", offset)));
  143. // 3. Let bp be the boundary point (node, offset).
  144. if (start_or_end == StartOrEnd::Start) {
  145. // -> If these steps were invoked as "set the start"
  146. // 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.
  147. if (&root() != &node.root() || position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset) == RelativeBoundaryPointPosition::After) {
  148. m_end_container = node;
  149. m_end_offset = offset;
  150. }
  151. // 2. Set range’s start to bp.
  152. m_start_container = node;
  153. m_start_offset = offset;
  154. } else {
  155. // -> If these steps were invoked as "set the end"
  156. VERIFY(start_or_end == StartOrEnd::End);
  157. // 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.
  158. if (&root() != &node.root() || position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset) == RelativeBoundaryPointPosition::Before) {
  159. m_start_container = node;
  160. m_start_offset = offset;
  161. }
  162. // 2. Set range’s end to bp.
  163. m_end_container = node;
  164. m_end_offset = offset;
  165. }
  166. update_associated_selection();
  167. return {};
  168. }
  169. // https://dom.spec.whatwg.org/#concept-range-bp-set
  170. WebIDL::ExceptionOr<void> Range::set_start(Node& node, u32 offset)
  171. {
  172. // The setStart(node, offset) method steps are to set the start of this to boundary point (node, offset).
  173. return set_start_or_end(node, offset, StartOrEnd::Start);
  174. }
  175. WebIDL::ExceptionOr<void> Range::set_end(Node& node, u32 offset)
  176. {
  177. // The setEnd(node, offset) method steps are to set the end of this to boundary point (node, offset).
  178. return set_start_or_end(node, offset, StartOrEnd::End);
  179. }
  180. // https://dom.spec.whatwg.org/#dom-range-setstartbefore
  181. WebIDL::ExceptionOr<void> Range::set_start_before(Node& node)
  182. {
  183. // 1. Let parent be node’s parent.
  184. auto* parent = node.parent();
  185. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  186. if (!parent)
  187. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_fly_string);
  188. // 3. Set the start of this to boundary point (parent, node’s index).
  189. return set_start_or_end(*parent, node.index(), StartOrEnd::Start);
  190. }
  191. // https://dom.spec.whatwg.org/#dom-range-setstartafter
  192. WebIDL::ExceptionOr<void> Range::set_start_after(Node& node)
  193. {
  194. // 1. Let parent be node’s parent.
  195. auto* parent = node.parent();
  196. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  197. if (!parent)
  198. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_fly_string);
  199. // 3. Set the start of this to boundary point (parent, node’s index plus 1).
  200. return set_start_or_end(*parent, node.index() + 1, StartOrEnd::Start);
  201. }
  202. // https://dom.spec.whatwg.org/#dom-range-setendbefore
  203. WebIDL::ExceptionOr<void> Range::set_end_before(Node& node)
  204. {
  205. // 1. Let parent be node’s parent.
  206. auto* parent = node.parent();
  207. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  208. if (!parent)
  209. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_fly_string);
  210. // 3. Set the end of this to boundary point (parent, node’s index).
  211. return set_start_or_end(*parent, node.index(), StartOrEnd::End);
  212. }
  213. // https://dom.spec.whatwg.org/#dom-range-setendafter
  214. WebIDL::ExceptionOr<void> Range::set_end_after(Node& node)
  215. {
  216. // 1. Let parent be node’s parent.
  217. auto* parent = node.parent();
  218. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  219. if (!parent)
  220. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_fly_string);
  221. // 3. Set the end of this to boundary point (parent, node’s index plus 1).
  222. return set_start_or_end(*parent, node.index() + 1, StartOrEnd::End);
  223. }
  224. // https://dom.spec.whatwg.org/#dom-range-compareboundarypoints
  225. WebIDL::ExceptionOr<i16> Range::compare_boundary_points(u16 how, Range const& source_range) const
  226. {
  227. // 1. If how is not one of
  228. // - START_TO_START,
  229. // - START_TO_END,
  230. // - END_TO_END, and
  231. // - END_TO_START,
  232. // then throw a "NotSupportedError" DOMException.
  233. if (how != HowToCompareBoundaryPoints::START_TO_START && how != HowToCompareBoundaryPoints::START_TO_END && how != HowToCompareBoundaryPoints::END_TO_END && how != HowToCompareBoundaryPoints::END_TO_START)
  234. 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)));
  235. // 2. If this’s root is not the same as sourceRange’s root, then throw a "WrongDocumentError" DOMException.
  236. if (&root() != &source_range.root())
  237. return WebIDL::WrongDocumentError::create(realm(), "This range is not in the same tree as the source range."_fly_string);
  238. JS::GCPtr<Node> this_point_node;
  239. u32 this_point_offset = 0;
  240. JS::GCPtr<Node> other_point_node;
  241. u32 other_point_offset = 0;
  242. // 3. If how is:
  243. switch (how) {
  244. case HowToCompareBoundaryPoints::START_TO_START:
  245. // -> START_TO_START:
  246. // Let this point be this’s start. Let other point be sourceRange’s start.
  247. this_point_node = m_start_container;
  248. this_point_offset = m_start_offset;
  249. other_point_node = source_range.m_start_container;
  250. other_point_offset = source_range.m_start_offset;
  251. break;
  252. case HowToCompareBoundaryPoints::START_TO_END:
  253. // -> START_TO_END:
  254. // Let this point be this’s end. Let other point be sourceRange’s start.
  255. this_point_node = m_end_container;
  256. this_point_offset = m_end_offset;
  257. other_point_node = source_range.m_start_container;
  258. other_point_offset = source_range.m_start_offset;
  259. break;
  260. case HowToCompareBoundaryPoints::END_TO_END:
  261. // -> END_TO_END:
  262. // Let this point be this’s end. Let other point be sourceRange’s end.
  263. this_point_node = m_end_container;
  264. this_point_offset = m_end_offset;
  265. other_point_node = source_range.m_end_container;
  266. other_point_offset = source_range.m_end_offset;
  267. break;
  268. case HowToCompareBoundaryPoints::END_TO_START:
  269. // -> END_TO_START:
  270. // Let this point be this’s start. Let other point be sourceRange’s end.
  271. this_point_node = m_start_container;
  272. this_point_offset = m_start_offset;
  273. other_point_node = source_range.m_end_container;
  274. other_point_offset = source_range.m_end_offset;
  275. break;
  276. default:
  277. VERIFY_NOT_REACHED();
  278. }
  279. VERIFY(this_point_node);
  280. VERIFY(other_point_node);
  281. // 4. If the position of this point relative to other point is
  282. auto relative_position = position_of_boundary_point_relative_to_other_boundary_point(*this_point_node, this_point_offset, *other_point_node, other_point_offset);
  283. switch (relative_position) {
  284. case RelativeBoundaryPointPosition::Before:
  285. // -> before
  286. // Return −1.
  287. return -1;
  288. case RelativeBoundaryPointPosition::Equal:
  289. // -> equal
  290. // Return 0.
  291. return 0;
  292. case RelativeBoundaryPointPosition::After:
  293. // -> after
  294. // Return 1.
  295. return 1;
  296. default:
  297. VERIFY_NOT_REACHED();
  298. }
  299. }
  300. // https://dom.spec.whatwg.org/#concept-range-select
  301. WebIDL::ExceptionOr<void> Range::select(Node& node)
  302. {
  303. // 1. Let parent be node’s parent.
  304. auto* parent = node.parent();
  305. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  306. if (!parent)
  307. return WebIDL::InvalidNodeTypeError::create(realm(), "Given node has no parent."_fly_string);
  308. // 3. Let index be node’s index.
  309. auto index = node.index();
  310. // 4. Set range’s start to boundary point (parent, index).
  311. m_start_container = *parent;
  312. m_start_offset = index;
  313. // 5. Set range’s end to boundary point (parent, index plus 1).
  314. m_end_container = *parent;
  315. m_end_offset = index + 1;
  316. update_associated_selection();
  317. return {};
  318. }
  319. // https://dom.spec.whatwg.org/#dom-range-selectnode
  320. WebIDL::ExceptionOr<void> Range::select_node(Node& node)
  321. {
  322. // The selectNode(node) method steps are to select node within this.
  323. return select(node);
  324. }
  325. // https://dom.spec.whatwg.org/#dom-range-collapse
  326. void Range::collapse(bool to_start)
  327. {
  328. // The collapse(toStart) method steps are to, if toStart is true, set end to start; otherwise set start to end.
  329. if (to_start) {
  330. m_end_container = m_start_container;
  331. m_end_offset = m_start_offset;
  332. } else {
  333. m_start_container = m_end_container;
  334. m_start_offset = m_end_offset;
  335. }
  336. update_associated_selection();
  337. }
  338. // https://dom.spec.whatwg.org/#dom-range-selectnodecontents
  339. WebIDL::ExceptionOr<void> Range::select_node_contents(Node& node)
  340. {
  341. // 1. If node is a doctype, throw an "InvalidNodeTypeError" DOMException.
  342. if (is<DocumentType>(node))
  343. return WebIDL::InvalidNodeTypeError::create(realm(), "Node cannot be a DocumentType."_fly_string);
  344. // 2. Let length be the length of node.
  345. auto length = node.length();
  346. // 3. Set start to the boundary point (node, 0).
  347. m_start_container = node;
  348. m_start_offset = 0;
  349. // 4. Set end to the boundary point (node, length).
  350. m_end_container = node;
  351. m_end_offset = length;
  352. update_associated_selection();
  353. return {};
  354. }
  355. JS::NonnullGCPtr<Range> Range::clone_range() const
  356. {
  357. return heap().allocate<Range>(shape().realm(), const_cast<Node&>(*m_start_container), m_start_offset, const_cast<Node&>(*m_end_container), m_end_offset);
  358. }
  359. JS::NonnullGCPtr<Range> Range::inverted() const
  360. {
  361. return heap().allocate<Range>(shape().realm(), const_cast<Node&>(*m_end_container), m_end_offset, const_cast<Node&>(*m_start_container), m_start_offset);
  362. }
  363. JS::NonnullGCPtr<Range> Range::normalized() const
  364. {
  365. if (m_start_container.ptr() == m_end_container.ptr()) {
  366. if (m_start_offset <= m_end_offset)
  367. return clone_range();
  368. return inverted();
  369. }
  370. if (m_start_container->is_before(m_end_container))
  371. return clone_range();
  372. return inverted();
  373. }
  374. // https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer
  375. JS::NonnullGCPtr<Node> Range::common_ancestor_container() const
  376. {
  377. // 1. Let container be start node.
  378. auto container = m_start_container;
  379. // 2. While container is not an inclusive ancestor of end node, let container be container’s parent.
  380. while (!container->is_inclusive_ancestor_of(m_end_container)) {
  381. VERIFY(container->parent());
  382. container = *container->parent();
  383. }
  384. // 3. Return container.
  385. return container;
  386. }
  387. // https://dom.spec.whatwg.org/#dom-range-intersectsnode
  388. bool Range::intersects_node(Node const& node) const
  389. {
  390. // 1. If node’s root is different from this’s root, return false.
  391. if (&node.root() != &root())
  392. return false;
  393. // 2. Let parent be node’s parent.
  394. auto* parent = node.parent();
  395. // 3. If parent is null, return true.
  396. if (!parent)
  397. return true;
  398. // 4. Let offset be node’s index.
  399. auto offset = node.index();
  400. // 5. If (parent, offset) is before end and (parent, offset plus 1) is after start, return true
  401. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(*parent, offset, m_end_container, m_end_offset);
  402. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(*parent, offset + 1, m_start_container, m_start_offset);
  403. if (relative_position_to_end == RelativeBoundaryPointPosition::Before && relative_position_to_start == RelativeBoundaryPointPosition::After)
  404. return true;
  405. // 6. Return false.
  406. return false;
  407. }
  408. // https://dom.spec.whatwg.org/#dom-range-ispointinrange
  409. WebIDL::ExceptionOr<bool> Range::is_point_in_range(Node const& node, u32 offset) const
  410. {
  411. // 1. If node’s root is different from this’s root, return false.
  412. if (&node.root() != &root())
  413. return false;
  414. // 2. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  415. if (is<DocumentType>(node))
  416. return WebIDL::InvalidNodeTypeError::create(realm(), "Node cannot be a DocumentType."_fly_string);
  417. // 3. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  418. if (offset > node.length())
  419. return WebIDL::IndexSizeError::create(realm(), MUST(String::formatted("Node does not contain a child at offset {}", offset)));
  420. // 4. If (node, offset) is before start or after end, return false.
  421. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset);
  422. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset);
  423. if (relative_position_to_start == RelativeBoundaryPointPosition::Before || relative_position_to_end == RelativeBoundaryPointPosition::After)
  424. return false;
  425. // 5. Return true.
  426. return true;
  427. }
  428. // https://dom.spec.whatwg.org/#dom-range-comparepoint
  429. WebIDL::ExceptionOr<i16> Range::compare_point(Node const& node, u32 offset) const
  430. {
  431. // 1. If node’s root is different from this’s root, then throw a "WrongDocumentError" DOMException.
  432. if (&node.root() != &root())
  433. return WebIDL::WrongDocumentError::create(realm(), "Given node is not in the same document as the range."_fly_string);
  434. // 2. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  435. if (is<DocumentType>(node))
  436. return WebIDL::InvalidNodeTypeError::create(realm(), "Node cannot be a DocumentType."_fly_string);
  437. // 3. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  438. if (offset > node.length())
  439. return WebIDL::IndexSizeError::create(realm(), MUST(String::formatted("Node does not contain a child at offset {}", offset)));
  440. // 4. If (node, offset) is before start, return −1.
  441. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset);
  442. if (relative_position_to_start == RelativeBoundaryPointPosition::Before)
  443. return -1;
  444. // 5. If (node, offset) is after end, return 1.
  445. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset);
  446. if (relative_position_to_end == RelativeBoundaryPointPosition::After)
  447. return 1;
  448. // 6. Return 0.
  449. return 0;
  450. }
  451. // https://dom.spec.whatwg.org/#dom-range-stringifier
  452. String Range::to_string() const
  453. {
  454. // 1. Let s be the empty string.
  455. StringBuilder builder;
  456. // 2. If this’s start node is this’s end node and it is a Text node,
  457. // then return the substring of that Text node’s data beginning at this’s start offset and ending at this’s end offset.
  458. if (start_container() == end_container() && is<Text>(*start_container()))
  459. return MUST(static_cast<Text const&>(*start_container()).data().substring_from_byte_offset(start_offset(), end_offset() - start_offset()));
  460. // 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.
  461. if (is<Text>(*start_container()))
  462. builder.append(static_cast<Text const&>(*start_container()).data().bytes_as_string_view().substring_view(start_offset()));
  463. // 4. Append the concatenation of the data of all Text nodes that are contained in this, in tree order, to s.
  464. for (Node const* node = start_container(); node != end_container()->next_sibling(); node = node->next_in_pre_order()) {
  465. if (is<Text>(*node) && contains_node(*node))
  466. builder.append(static_cast<Text const&>(*node).data());
  467. }
  468. // 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.
  469. if (is<Text>(*end_container()))
  470. builder.append(static_cast<Text const&>(*end_container()).data().bytes_as_string_view().substring_view(0, end_offset()));
  471. // 6. Return s.
  472. return MUST(builder.to_string());
  473. }
  474. // https://dom.spec.whatwg.org/#dom-range-extractcontents
  475. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::extract_contents()
  476. {
  477. return extract();
  478. }
  479. // https://dom.spec.whatwg.org/#concept-range-extract
  480. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::extract()
  481. {
  482. // 1. Let fragment be a new DocumentFragment node whose node document is range’s start node’s node document.
  483. auto fragment = heap().allocate<DOM::DocumentFragment>(realm(), const_cast<Document&>(start_container()->document()));
  484. // 2. If range is collapsed, then return fragment.
  485. if (collapsed())
  486. return fragment;
  487. // 3. Let original start node, original start offset, original end node, and original end offset
  488. // be range’s start node, start offset, end node, and end offset, respectively.
  489. JS::NonnullGCPtr<Node> original_start_node = m_start_container;
  490. auto original_start_offset = m_start_offset;
  491. JS::NonnullGCPtr<Node> original_end_node = m_end_container;
  492. auto original_end_offset = m_end_offset;
  493. // 4. If original start node is original end node and it is a CharacterData node, then:
  494. if (original_start_node.ptr() == original_end_node.ptr() && is<CharacterData>(*original_start_node)) {
  495. // 1. Let clone be a clone of original start node.
  496. auto clone = original_start_node->clone_node();
  497. // 2. Set the data of clone to the result of substringing data with node original start node,
  498. // offset original start offset, and count original end offset minus original start offset.
  499. auto result = TRY(static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_end_offset - original_start_offset));
  500. verify_cast<CharacterData>(*clone).set_data(move(result));
  501. // 3. Append clone to fragment.
  502. TRY(fragment->append_child(clone));
  503. // 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.
  504. TRY(static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_end_offset - original_start_offset, String {}));
  505. // 5. Return fragment.
  506. return fragment;
  507. }
  508. // 5. Let common ancestor be original start node.
  509. JS::NonnullGCPtr<Node> common_ancestor = original_start_node;
  510. // 6. While common ancestor is not an inclusive ancestor of original end node, set common ancestor to its own parent.
  511. while (!common_ancestor->is_inclusive_ancestor_of(original_end_node))
  512. common_ancestor = *common_ancestor->parent_node();
  513. // 7. Let first partially contained child be null.
  514. JS::GCPtr<Node> first_partially_contained_child;
  515. // 8. If original start node is not an inclusive ancestor of original end node,
  516. // set first partially contained child to the first child of common ancestor that is partially contained in range.
  517. if (!original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  518. for (auto* child = common_ancestor->first_child(); child; child = child->next_sibling()) {
  519. if (partially_contains_node(*child)) {
  520. first_partially_contained_child = child;
  521. break;
  522. }
  523. }
  524. }
  525. // 9. Let last partially contained child be null.
  526. JS::GCPtr<Node> last_partially_contained_child;
  527. // 10. If original end node is not an inclusive ancestor of original start node,
  528. // set last partially contained child to the last child of common ancestor that is partially contained in range.
  529. if (!original_end_node->is_inclusive_ancestor_of(original_start_node)) {
  530. for (auto* child = common_ancestor->last_child(); child; child = child->previous_sibling()) {
  531. if (partially_contains_node(*child)) {
  532. last_partially_contained_child = child;
  533. break;
  534. }
  535. }
  536. }
  537. // 11. Let contained children be a list of all children of common ancestor that are contained in range, in tree order.
  538. Vector<JS::NonnullGCPtr<Node>> contained_children;
  539. for (Node* node = common_ancestor->first_child(); node; node = node->next_sibling()) {
  540. if (contains_node(*node))
  541. contained_children.append(*node);
  542. }
  543. // 12. If any member of contained children is a doctype, then throw a "HierarchyRequestError" DOMException.
  544. for (auto const& child : contained_children) {
  545. if (is<DocumentType>(*child))
  546. return WebIDL::HierarchyRequestError::create(realm(), "Contained child is a DocumentType"_fly_string);
  547. }
  548. JS::GCPtr<Node> new_node;
  549. size_t new_offset = 0;
  550. // 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.
  551. if (original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  552. new_node = original_start_node;
  553. new_offset = original_start_offset;
  554. }
  555. // 14. Otherwise:
  556. else {
  557. // 1. Let reference node equal original start node.
  558. JS::GCPtr<Node> reference_node = original_start_node;
  559. // 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.
  560. while (reference_node->parent_node() && !reference_node->parent_node()->is_inclusive_ancestor_of(original_end_node))
  561. reference_node = reference_node->parent_node();
  562. // 3. Set new node to the parent of reference node, and new offset to one plus reference node’s index.
  563. new_node = reference_node->parent_node();
  564. new_offset = 1 + reference_node->index();
  565. }
  566. // 15. If first partially contained child is a CharacterData node, then:
  567. if (first_partially_contained_child && is<CharacterData>(*first_partially_contained_child)) {
  568. // 1. Let clone be a clone of original start node.
  569. auto clone = original_start_node->clone_node();
  570. // 2. Set the data of clone to the result of substringing data with node original start node, offset original start offset,
  571. // and count original start node’s length minus original start offset.
  572. auto result = TRY(static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_start_node->length() - original_start_offset));
  573. verify_cast<CharacterData>(*clone).set_data(move(result));
  574. // 3. Append clone to fragment.
  575. TRY(fragment->append_child(clone));
  576. // 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.
  577. TRY(static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_start_node->length() - original_start_offset, String {}));
  578. }
  579. // 16. Otherwise, if first partially contained child is not null:
  580. else if (first_partially_contained_child) {
  581. // 1. Let clone be a clone of first partially contained child.
  582. auto clone = first_partially_contained_child->clone_node();
  583. // 2. Append clone to fragment.
  584. TRY(fragment->append_child(clone));
  585. // 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).
  586. auto subrange = Range::create(original_start_node, original_start_offset, *first_partially_contained_child, first_partially_contained_child->length());
  587. // 4. Let subfragment be the result of extracting subrange.
  588. auto subfragment = TRY(subrange->extract());
  589. // 5. Append subfragment to clone.
  590. TRY(clone->append_child(subfragment));
  591. }
  592. // 17. For each contained child in contained children, append contained child to fragment.
  593. for (auto& contained_child : contained_children) {
  594. TRY(fragment->append_child(contained_child));
  595. }
  596. // 18. If last partially contained child is a CharacterData node, then:
  597. if (last_partially_contained_child && is<CharacterData>(*last_partially_contained_child)) {
  598. // 1. Let clone be a clone of original end node.
  599. auto clone = original_end_node->clone_node();
  600. // 2. Set the data of clone to the result of substringing data with node original end node, offset 0, and count original end offset.
  601. auto result = TRY(static_cast<CharacterData const&>(*original_end_node).substring_data(0, original_end_offset));
  602. verify_cast<CharacterData>(*clone).set_data(move(result));
  603. // 3. Append clone to fragment.
  604. TRY(fragment->append_child(clone));
  605. // 4. Replace data with node original end node, offset 0, count original end offset, and data the empty string.
  606. TRY(verify_cast<CharacterData>(*original_end_node).replace_data(0, original_end_offset, String {}));
  607. }
  608. // 19. Otherwise, if last partially contained child is not null:
  609. else if (last_partially_contained_child) {
  610. // 1. Let clone be a clone of last partially contained child.
  611. auto clone = last_partially_contained_child->clone_node();
  612. // 2. Append clone to fragment.
  613. TRY(fragment->append_child(clone));
  614. // 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).
  615. auto subrange = Range::create(*last_partially_contained_child, 0, original_end_node, original_end_offset);
  616. // 4. Let subfragment be the result of extracting subrange.
  617. auto subfragment = TRY(subrange->extract());
  618. // 5. Append subfragment to clone.
  619. TRY(clone->append_child(subfragment));
  620. }
  621. // 20. Set range’s start and end to (new node, new offset).
  622. TRY(set_start(*new_node, new_offset));
  623. TRY(set_end(*new_node, new_offset));
  624. // 21. Return fragment.
  625. return fragment;
  626. }
  627. // https://dom.spec.whatwg.org/#contained
  628. bool Range::contains_node(Node const& node) const
  629. {
  630. // A node node is contained in a live range range if node’s root is range’s root,
  631. if (&node.root() != &root())
  632. return false;
  633. // and (node, 0) is after range’s start,
  634. if (position_of_boundary_point_relative_to_other_boundary_point(node, 0, m_start_container, m_start_offset) != RelativeBoundaryPointPosition::After)
  635. return false;
  636. // and (node, node’s length) is before range’s end.
  637. if (position_of_boundary_point_relative_to_other_boundary_point(node, node.length(), m_end_container, m_end_offset) != RelativeBoundaryPointPosition::Before)
  638. return false;
  639. return true;
  640. }
  641. // https://dom.spec.whatwg.org/#partially-contained
  642. bool Range::partially_contains_node(Node const& node) const
  643. {
  644. // 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.
  645. if (node.is_inclusive_ancestor_of(m_start_container) && &node != m_end_container.ptr())
  646. return true;
  647. if (node.is_inclusive_ancestor_of(m_end_container) && &node != m_start_container.ptr())
  648. return true;
  649. return false;
  650. }
  651. // https://dom.spec.whatwg.org/#dom-range-insertnode
  652. WebIDL::ExceptionOr<void> Range::insert_node(JS::NonnullGCPtr<Node> node)
  653. {
  654. return insert(node);
  655. }
  656. // https://dom.spec.whatwg.org/#concept-range-insert
  657. WebIDL::ExceptionOr<void> Range::insert(JS::NonnullGCPtr<Node> node)
  658. {
  659. // 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.
  660. if ((is<ProcessingInstruction>(*m_start_container) || is<Comment>(*m_start_container))
  661. || (is<Text>(*m_start_container) && !m_start_container->parent_node())
  662. || m_start_container.ptr() == node.ptr()) {
  663. return WebIDL::HierarchyRequestError::create(realm(), "Range has inappropriate start node for insertion"_fly_string);
  664. }
  665. // 2. Let referenceNode be null.
  666. JS::GCPtr<Node> reference_node;
  667. // 3. If range’s start node is a Text node, set referenceNode to that Text node.
  668. if (is<Text>(*m_start_container)) {
  669. reference_node = m_start_container;
  670. }
  671. // 4. Otherwise, set referenceNode to the child of start node whose index is start offset, and null if there is no such child.
  672. else {
  673. reference_node = m_start_container->child_at_index(m_start_offset);
  674. }
  675. // 5. Let parent be range’s start node if referenceNode is null, and referenceNode’s parent otherwise.
  676. JS::GCPtr<Node> parent;
  677. if (!reference_node)
  678. parent = m_start_container;
  679. else
  680. parent = reference_node->parent();
  681. // 6. Ensure pre-insertion validity of node into parent before referenceNode.
  682. TRY(parent->ensure_pre_insertion_validity(node, reference_node));
  683. // 7. If range’s start node is a Text node, set referenceNode to the result of splitting it with offset range’s start offset.
  684. if (is<Text>(*m_start_container))
  685. reference_node = TRY(static_cast<Text&>(*m_start_container).split_text(m_start_offset));
  686. // 8. If node is referenceNode, set referenceNode to its next sibling.
  687. if (node == reference_node)
  688. reference_node = reference_node->next_sibling();
  689. // 9. If node’s parent is non-null, then remove node.
  690. if (node->parent())
  691. node->remove();
  692. // 10. Let newOffset be parent’s length if referenceNode is null, and referenceNode’s index otherwise.
  693. size_t new_offset = 0;
  694. if (!reference_node)
  695. new_offset = parent->length();
  696. else
  697. new_offset = reference_node->index();
  698. // 11. Increase newOffset by node’s length if node is a DocumentFragment node, and one otherwise.
  699. if (is<DocumentFragment>(*node))
  700. new_offset += node->length();
  701. else
  702. new_offset += 1;
  703. // 12. Pre-insert node into parent before referenceNode.
  704. (void)TRY(parent->pre_insert(node, reference_node));
  705. // 13. If range is collapsed, then set range’s end to (parent, newOffset).
  706. if (collapsed())
  707. TRY(set_end(*parent, new_offset));
  708. return {};
  709. }
  710. // https://dom.spec.whatwg.org/#dom-range-surroundcontents
  711. WebIDL::ExceptionOr<void> Range::surround_contents(JS::NonnullGCPtr<Node> new_parent)
  712. {
  713. // 1. If a non-Text node is partially contained in this, then throw an "InvalidStateError" DOMException.
  714. Node* start_non_text_node = start_container();
  715. if (is<Text>(*start_non_text_node))
  716. start_non_text_node = start_non_text_node->parent_node();
  717. Node* end_non_text_node = end_container();
  718. if (is<Text>(*end_non_text_node))
  719. end_non_text_node = end_non_text_node->parent_node();
  720. if (start_non_text_node != end_non_text_node)
  721. return WebIDL::InvalidStateError::create(realm(), "Non-Text node is partially contained in range."_fly_string);
  722. // 2. If newParent is a Document, DocumentType, or DocumentFragment node, then throw an "InvalidNodeTypeError" DOMException.
  723. if (is<Document>(*new_parent) || is<DocumentType>(*new_parent) || is<DocumentFragment>(*new_parent))
  724. return WebIDL::InvalidNodeTypeError::create(realm(), "Invalid parent node type"_fly_string);
  725. // 3. Let fragment be the result of extracting this.
  726. auto fragment = TRY(extract());
  727. // 4. If newParent has children, then replace all with null within newParent.
  728. if (new_parent->has_children())
  729. new_parent->replace_all(nullptr);
  730. // 5. Insert newParent into this.
  731. TRY(insert(new_parent));
  732. // 6. Append fragment to newParent.
  733. (void)TRY(new_parent->append_child(fragment));
  734. // 7. Select newParent within this.
  735. return select(*new_parent);
  736. }
  737. // https://dom.spec.whatwg.org/#dom-range-clonecontents
  738. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::clone_contents()
  739. {
  740. return clone_the_contents();
  741. }
  742. // https://dom.spec.whatwg.org/#concept-range-clone
  743. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::clone_the_contents()
  744. {
  745. // 1. Let fragment be a new DocumentFragment node whose node document is range’s start node’s node document.
  746. auto fragment = heap().allocate<DOM::DocumentFragment>(realm(), const_cast<Document&>(start_container()->document()));
  747. // 2. If range is collapsed, then return fragment.
  748. if (collapsed())
  749. return fragment;
  750. // 3. Let original start node, original start offset, original end node, and original end offset
  751. // be range’s start node, start offset, end node, and end offset, respectively.
  752. JS::NonnullGCPtr<Node> original_start_node = m_start_container;
  753. auto original_start_offset = m_start_offset;
  754. JS::NonnullGCPtr<Node> original_end_node = m_end_container;
  755. auto original_end_offset = m_end_offset;
  756. // 4. If original start node is original end node and it is a CharacterData node, then:
  757. if (original_start_node.ptr() == original_end_node.ptr() && is<CharacterData>(*original_start_node)) {
  758. // 1. Let clone be a clone of original start node.
  759. auto clone = original_start_node->clone_node();
  760. // 2. Set the data of clone to the result of substringing data with node original start node,
  761. // offset original start offset, and count original end offset minus original start offset.
  762. auto result = TRY(static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_end_offset - original_start_offset));
  763. verify_cast<CharacterData>(*clone).set_data(move(result));
  764. // 3. Append clone to fragment.
  765. TRY(fragment->append_child(clone));
  766. // 4. Return fragment.
  767. return fragment;
  768. }
  769. // 5. Let common ancestor be original start node.
  770. JS::NonnullGCPtr<Node> common_ancestor = original_start_node;
  771. // 6. While common ancestor is not an inclusive ancestor of original end node, set common ancestor to its own parent.
  772. while (!common_ancestor->is_inclusive_ancestor_of(original_end_node))
  773. common_ancestor = *common_ancestor->parent_node();
  774. // 7. Let first partially contained child be null.
  775. JS::GCPtr<Node> first_partially_contained_child;
  776. // 8. If original start node is not an inclusive ancestor of original end node,
  777. // set first partially contained child to the first child of common ancestor that is partially contained in range.
  778. if (!original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  779. for (auto* child = common_ancestor->first_child(); child; child = child->next_sibling()) {
  780. if (partially_contains_node(*child)) {
  781. first_partially_contained_child = child;
  782. break;
  783. }
  784. }
  785. }
  786. // 9. Let last partially contained child be null.
  787. JS::GCPtr<Node> last_partially_contained_child;
  788. // 10. If original end node is not an inclusive ancestor of original start node,
  789. // set last partially contained child to the last child of common ancestor that is partially contained in range.
  790. if (!original_end_node->is_inclusive_ancestor_of(original_start_node)) {
  791. for (auto* child = common_ancestor->last_child(); child; child = child->previous_sibling()) {
  792. if (partially_contains_node(*child)) {
  793. last_partially_contained_child = child;
  794. break;
  795. }
  796. }
  797. }
  798. // 11. Let contained children be a list of all children of common ancestor that are contained in range, in tree order.
  799. Vector<JS::NonnullGCPtr<Node>> contained_children;
  800. for (Node* node = common_ancestor->first_child(); node; node = node->next_sibling()) {
  801. if (contains_node(*node))
  802. contained_children.append(*node);
  803. }
  804. // 12. If any member of contained children is a doctype, then throw a "HierarchyRequestError" DOMException.
  805. for (auto const& child : contained_children) {
  806. if (is<DocumentType>(*child))
  807. return WebIDL::HierarchyRequestError::create(realm(), "Contained child is a DocumentType"_fly_string);
  808. }
  809. // 13. If first partially contained child is a CharacterData node, then:
  810. if (first_partially_contained_child && is<CharacterData>(*first_partially_contained_child)) {
  811. // 1. Let clone be a clone of original start node.
  812. auto clone = original_start_node->clone_node();
  813. // 2. Set the data of clone to the result of substringing data with node original start node, offset original start offset,
  814. // and count original start node’s length minus original start offset.
  815. auto result = TRY(static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_start_node->length() - original_start_offset));
  816. verify_cast<CharacterData>(*clone).set_data(move(result));
  817. // 3. Append clone to fragment.
  818. TRY(fragment->append_child(clone));
  819. }
  820. // 14. Otherwise, if first partially contained child is not null:
  821. else if (first_partially_contained_child) {
  822. // 1. Let clone be a clone of first partially contained child.
  823. auto clone = first_partially_contained_child->clone_node();
  824. // 2. Append clone to fragment.
  825. TRY(fragment->append_child(clone));
  826. // 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).
  827. auto subrange = Range::create(original_start_node, original_start_offset, *first_partially_contained_child, first_partially_contained_child->length());
  828. // 4. Let subfragment be the result of cloning the contents of subrange.
  829. auto subfragment = TRY(subrange->clone_the_contents());
  830. // 5. Append subfragment to clone.
  831. TRY(clone->append_child(subfragment));
  832. }
  833. // 15. For each contained child in contained children.
  834. for (auto& contained_child : contained_children) {
  835. // 1. Let clone be a clone of contained child with the clone children flag set.
  836. auto clone = contained_child->clone_node(nullptr, true);
  837. // 2. Append clone to fragment.
  838. TRY(fragment->append_child(move(clone)));
  839. }
  840. // 16. If last partially contained child is a CharacterData node, then:
  841. if (last_partially_contained_child && is<CharacterData>(*last_partially_contained_child)) {
  842. // 1. Let clone be a clone of original end node.
  843. auto clone = original_end_node->clone_node();
  844. // 2. Set the data of clone to the result of substringing data with node original end node, offset 0, and count original end offset.
  845. auto result = TRY(static_cast<CharacterData const&>(*original_end_node).substring_data(0, original_end_offset));
  846. verify_cast<CharacterData>(*clone).set_data(move(result));
  847. // 3. Append clone to fragment.
  848. TRY(fragment->append_child(clone));
  849. }
  850. // 17. Otherwise, if last partially contained child is not null:
  851. else if (last_partially_contained_child) {
  852. // 1. Let clone be a clone of last partially contained child.
  853. auto clone = last_partially_contained_child->clone_node();
  854. // 2. Append clone to fragment.
  855. TRY(fragment->append_child(clone));
  856. // 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).
  857. auto subrange = Range::create(*last_partially_contained_child, 0, original_end_node, original_end_offset);
  858. // 4. Let subfragment be the result of cloning the contents of subrange.
  859. auto subfragment = TRY(subrange->clone_the_contents());
  860. // 5. Append subfragment to clone.
  861. TRY(clone->append_child(subfragment));
  862. }
  863. // 18. Return fragment.
  864. return fragment;
  865. }
  866. // https://dom.spec.whatwg.org/#dom-range-deletecontents
  867. WebIDL::ExceptionOr<void> Range::delete_contents()
  868. {
  869. // 1. If this is collapsed, then return.
  870. if (collapsed())
  871. return {};
  872. // 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.
  873. JS::NonnullGCPtr<Node> original_start_node = m_start_container;
  874. auto original_start_offset = m_start_offset;
  875. JS::NonnullGCPtr<Node> original_end_node = m_end_container;
  876. auto original_end_offset = m_end_offset;
  877. // 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,
  878. // count original end offset minus original start offset, and data the empty string, and then return.
  879. if (original_start_node.ptr() == original_end_node.ptr() && is<CharacterData>(*original_start_node)) {
  880. TRY(static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_end_offset - original_start_offset, String {}));
  881. return {};
  882. }
  883. // 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.
  884. JS::MarkedVector<Node*> nodes_to_remove(heap());
  885. for (Node const* node = start_container(); node != end_container()->next_in_pre_order(); node = node->next_in_pre_order()) {
  886. if (contains_node(*node) && (!node->parent_node() || !contains_node(*node->parent_node())))
  887. nodes_to_remove.append(const_cast<Node*>(node));
  888. }
  889. JS::GCPtr<Node> new_node;
  890. size_t new_offset = 0;
  891. // 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.
  892. if (original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  893. new_node = original_start_node;
  894. new_offset = original_start_offset;
  895. }
  896. // 6. Otherwise
  897. else {
  898. // 1. Let reference node equal original start node.
  899. auto reference_node = original_start_node;
  900. // 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.
  901. while (reference_node->parent_node() && !reference_node->parent_node()->is_inclusive_ancestor_of(original_end_node))
  902. reference_node = *reference_node->parent_node();
  903. // 3. Set new node to the parent of reference node, and new offset to one plus the index of reference node.
  904. new_node = reference_node->parent_node();
  905. new_offset = 1 + reference_node->index();
  906. }
  907. // 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.
  908. if (is<CharacterData>(*original_start_node))
  909. TRY(static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_start_node->length() - original_start_offset, String {}));
  910. // 8. For each node in nodes to remove, in tree order, remove node.
  911. for (auto& node : nodes_to_remove)
  912. node->remove();
  913. // 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.
  914. if (is<CharacterData>(*original_end_node))
  915. TRY(static_cast<CharacterData&>(*original_end_node).replace_data(0, original_end_offset, String {}));
  916. // 10. Set start and end to (new node, new offset).
  917. TRY(set_start(*new_node, new_offset));
  918. TRY(set_end(*new_node, new_offset));
  919. return {};
  920. }
  921. // https://w3c.github.io/csswg-drafts/cssom-view/#dom-range-getboundingclientrect
  922. JS::NonnullGCPtr<Geometry::DOMRect> Range::get_bounding_client_rect() const
  923. {
  924. dbgln("(STUBBED) Range::get_bounding_client_rect()");
  925. return Geometry::DOMRect::construct_impl(realm(), 0, 0, 0, 0).release_value_but_fixme_should_propagate_errors();
  926. }
  927. // https://w3c.github.io/DOM-Parsing/#dom-range-createcontextualfragment
  928. WebIDL::ExceptionOr<JS::NonnullGCPtr<DocumentFragment>> Range::create_contextual_fragment(String const& fragment)
  929. {
  930. // 1. Let node be the context object's start node.
  931. JS::NonnullGCPtr<Node> node = *start_container();
  932. // Let element be as follows, depending on node's interface:
  933. JS::GCPtr<Element> element;
  934. switch (static_cast<NodeType>(node->node_type())) {
  935. case NodeType::DOCUMENT_NODE:
  936. case NodeType::DOCUMENT_FRAGMENT_NODE:
  937. element = nullptr;
  938. break;
  939. case NodeType::ELEMENT_NODE:
  940. element = static_cast<DOM::Element&>(*node);
  941. break;
  942. case NodeType::TEXT_NODE:
  943. case NodeType::COMMENT_NODE:
  944. element = node->parent_element();
  945. break;
  946. case NodeType::DOCUMENT_TYPE_NODE:
  947. case NodeType::PROCESSING_INSTRUCTION_NODE:
  948. // [DOM4] prevents this case.
  949. VERIFY_NOT_REACHED();
  950. default:
  951. VERIFY_NOT_REACHED();
  952. }
  953. // 2. If either element is null or the following are all true:
  954. // - element's node document is an HTML document,
  955. // - element's local name is "html", and
  956. // - element's namespace is the HTML namespace;
  957. if (!element || is<HTML::HTMLHtmlElement>(*element)) {
  958. // let element be a new Element with
  959. // - "body" as its local name,
  960. // - The HTML namespace as its namespace, and
  961. // - The context object's node document as its node document.
  962. element = TRY(DOM::create_element(node->document(), "body"sv, Namespace::HTML));
  963. }
  964. // 3. Let fragment node be the result of invoking the fragment parsing algorithm with fragment as markup, and element as the context element.
  965. auto fragment_node = TRY(DOMParsing::parse_fragment(fragment.to_deprecated_string(), *element));
  966. // 4. Unmark all scripts in fragment node as "already started" and as "parser-inserted".
  967. fragment_node->for_each_in_subtree_of_type<HTML::HTMLScriptElement>([&](HTML::HTMLScriptElement& script_element) {
  968. script_element.unmark_as_already_started({});
  969. script_element.unmark_as_parser_inserted({});
  970. return IterationDecision::Continue;
  971. });
  972. // 5. Return the value of fragment node.
  973. return fragment_node;
  974. }
  975. }