Range.cpp 53 KB

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