Range.cpp 57 KB

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