Range.cpp 53 KB

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