Range.cpp 53 KB

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