Range.cpp 52 KB

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