Range.cpp 57 KB

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