Range.cpp 57 KB

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