Range.cpp 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. /*
  2. * Copyright (c) 2020, the SerenityOS developers.
  3. * Copyright (c) 2022, Luke Wilde <lukew@serenityos.org>
  4. * Copyright (c) 2022, Andreas Kling <kling@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <LibWeb/DOM/Comment.h>
  9. #include <LibWeb/DOM/Document.h>
  10. #include <LibWeb/DOM/DocumentFragment.h>
  11. #include <LibWeb/DOM/DocumentType.h>
  12. #include <LibWeb/DOM/Node.h>
  13. #include <LibWeb/DOM/ProcessingInstruction.h>
  14. #include <LibWeb/DOM/Range.h>
  15. #include <LibWeb/DOM/Text.h>
  16. #include <LibWeb/HTML/Window.h>
  17. namespace Web::DOM {
  18. HashTable<Range*>& Range::live_ranges()
  19. {
  20. static HashTable<Range*> ranges;
  21. return ranges;
  22. }
  23. NonnullRefPtr<Range> Range::create(HTML::Window& window)
  24. {
  25. return Range::create(window.associated_document());
  26. }
  27. NonnullRefPtr<Range> Range::create(Document& document)
  28. {
  29. return adopt_ref(*new Range(document));
  30. }
  31. NonnullRefPtr<Range> Range::create(Node& start_container, u32 start_offset, Node& end_container, u32 end_offset)
  32. {
  33. return adopt_ref(*new Range(start_container, start_offset, end_container, end_offset));
  34. }
  35. NonnullRefPtr<Range> Range::create_with_global_object(Bindings::WindowObject& window)
  36. {
  37. return Range::create(window.impl());
  38. }
  39. Range::Range(Document& document)
  40. : Range(document, 0, document, 0)
  41. {
  42. }
  43. Range::Range(Node& start_container, u32 start_offset, Node& end_container, u32 end_offset)
  44. : AbstractRange(start_container, start_offset, end_container, end_offset)
  45. {
  46. live_ranges().set(this);
  47. }
  48. Range::~Range()
  49. {
  50. live_ranges().remove(this);
  51. }
  52. // https://dom.spec.whatwg.org/#concept-range-root
  53. Node& Range::root()
  54. {
  55. // The root of a live range is the root of its start node.
  56. return m_start_container->root();
  57. }
  58. Node const& Range::root() const
  59. {
  60. return m_start_container->root();
  61. }
  62. enum class RelativeBoundaryPointPosition {
  63. Equal,
  64. Before,
  65. After,
  66. };
  67. // https://dom.spec.whatwg.org/#concept-range-bp-position
  68. static RelativeBoundaryPointPosition position_of_boundary_point_relative_to_other_boundary_point(Node const& node_a, u32 offset_a, Node const& node_b, u32 offset_b)
  69. {
  70. // 1. Assert: nodeA and nodeB have the same root.
  71. VERIFY(&node_a.root() == &node_b.root());
  72. // 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.
  73. if (&node_a == &node_b) {
  74. if (offset_a == offset_b)
  75. return RelativeBoundaryPointPosition::Equal;
  76. if (offset_a < offset_b)
  77. return RelativeBoundaryPointPosition::Before;
  78. return RelativeBoundaryPointPosition::After;
  79. }
  80. // 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.
  81. if (node_a.is_following(node_b)) {
  82. auto relative_position = position_of_boundary_point_relative_to_other_boundary_point(node_b, offset_b, node_a, offset_a);
  83. if (relative_position == RelativeBoundaryPointPosition::Before)
  84. return RelativeBoundaryPointPosition::After;
  85. if (relative_position == RelativeBoundaryPointPosition::After)
  86. return RelativeBoundaryPointPosition::Before;
  87. }
  88. // 4. If nodeA is an ancestor of nodeB:
  89. if (node_a.is_ancestor_of(node_b)) {
  90. // 1. Let child be nodeB.
  91. NonnullRefPtr<Node> child = node_b;
  92. // 2. While child is not a child of nodeA, set child to its parent.
  93. while (!node_a.is_parent_of(child)) {
  94. auto* parent = child->parent();
  95. VERIFY(parent);
  96. child = *parent;
  97. }
  98. // 3. If child’s index is less than offsetA, then return after.
  99. if (child->index() < offset_a)
  100. return RelativeBoundaryPointPosition::After;
  101. }
  102. // 5. Return before.
  103. return RelativeBoundaryPointPosition::Before;
  104. }
  105. ExceptionOr<void> Range::set_start_or_end(Node& node, u32 offset, StartOrEnd start_or_end)
  106. {
  107. // FIXME: If the incoming node is part of a document that's in the process of being destroyed,
  108. // we just ignore this. This prevents us from trying to re-ref a document during its
  109. // destruction process. This is a hack and should be replaced with some smarter form
  110. // of lifetime management.
  111. if (node.document().in_removed_last_ref())
  112. return {};
  113. // To set the start or end of a range to a boundary point (node, offset), run these steps:
  114. // 1. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  115. if (is<DocumentType>(node))
  116. return InvalidNodeTypeError::create("Node cannot be a DocumentType.");
  117. // 2. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  118. if (offset > node.length())
  119. return IndexSizeError::create(String::formatted("Node does not contain a child at offset {}", offset));
  120. // 3. Let bp be the boundary point (node, offset).
  121. if (start_or_end == StartOrEnd::Start) {
  122. // -> If these steps were invoked as "set the start"
  123. // 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.
  124. if (&root() != &node.root() || position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset) == RelativeBoundaryPointPosition::After) {
  125. m_end_container = node;
  126. m_end_offset = offset;
  127. }
  128. // 2. Set range’s start to bp.
  129. m_start_container = node;
  130. m_start_offset = offset;
  131. } else {
  132. // -> If these steps were invoked as "set the end"
  133. VERIFY(start_or_end == StartOrEnd::End);
  134. // 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.
  135. if (&root() != &node.root() || position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset) == RelativeBoundaryPointPosition::Before) {
  136. m_start_container = node;
  137. m_start_offset = offset;
  138. }
  139. // 2. Set range’s end to bp.
  140. m_end_container = node;
  141. m_end_offset = offset;
  142. }
  143. return {};
  144. }
  145. // https://dom.spec.whatwg.org/#concept-range-bp-set
  146. ExceptionOr<void> Range::set_start(Node& node, u32 offset)
  147. {
  148. // The setStart(node, offset) method steps are to set the start of this to boundary point (node, offset).
  149. return set_start_or_end(node, offset, StartOrEnd::Start);
  150. }
  151. ExceptionOr<void> Range::set_end(Node& node, u32 offset)
  152. {
  153. // The setEnd(node, offset) method steps are to set the end of this to boundary point (node, offset).
  154. return set_start_or_end(node, offset, StartOrEnd::End);
  155. }
  156. // https://dom.spec.whatwg.org/#dom-range-setstartbefore
  157. ExceptionOr<void> Range::set_start_before(Node& node)
  158. {
  159. // 1. Let parent be node’s parent.
  160. auto* parent = node.parent();
  161. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  162. if (!parent)
  163. return InvalidNodeTypeError::create("Given node has no parent.");
  164. // 3. Set the start of this to boundary point (parent, node’s index).
  165. return set_start_or_end(*parent, node.index(), StartOrEnd::Start);
  166. }
  167. // https://dom.spec.whatwg.org/#dom-range-setstartafter
  168. ExceptionOr<void> Range::set_start_after(Node& node)
  169. {
  170. // 1. Let parent be node’s parent.
  171. auto* parent = node.parent();
  172. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  173. if (!parent)
  174. return InvalidNodeTypeError::create("Given node has no parent.");
  175. // 3. Set the start of this to boundary point (parent, node’s index plus 1).
  176. return set_start_or_end(*parent, node.index() + 1, StartOrEnd::Start);
  177. }
  178. // https://dom.spec.whatwg.org/#dom-range-setendbefore
  179. ExceptionOr<void> Range::set_end_before(Node& node)
  180. {
  181. // 1. Let parent be node’s parent.
  182. auto* parent = node.parent();
  183. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  184. if (!parent)
  185. return InvalidNodeTypeError::create("Given node has no parent.");
  186. // 3. Set the end of this to boundary point (parent, node’s index).
  187. return set_start_or_end(*parent, node.index(), StartOrEnd::End);
  188. }
  189. // https://dom.spec.whatwg.org/#dom-range-setendafter
  190. ExceptionOr<void> Range::set_end_after(Node& node)
  191. {
  192. // 1. Let parent be node’s parent.
  193. auto* parent = node.parent();
  194. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  195. if (!parent)
  196. return InvalidNodeTypeError::create("Given node has no parent.");
  197. // 3. Set the end of this to boundary point (parent, node’s index plus 1).
  198. return set_start_or_end(*parent, node.index() + 1, StartOrEnd::End);
  199. }
  200. // https://dom.spec.whatwg.org/#dom-range-compareboundarypoints
  201. ExceptionOr<i16> Range::compare_boundary_points(u16 how, Range const& source_range) const
  202. {
  203. // 1. If how is not one of
  204. // - START_TO_START,
  205. // - START_TO_END,
  206. // - END_TO_END, and
  207. // - END_TO_START,
  208. // then throw a "NotSupportedError" DOMException.
  209. if (how != HowToCompareBoundaryPoints::START_TO_START && how != HowToCompareBoundaryPoints::START_TO_END && how != HowToCompareBoundaryPoints::END_TO_END && how != HowToCompareBoundaryPoints::END_TO_START)
  210. return NotSupportedError::create(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));
  211. // 2. If this’s root is not the same as sourceRange’s root, then throw a "WrongDocumentError" DOMException.
  212. if (&root() != &source_range.root())
  213. return WrongDocumentError::create("This range is not in the same tree as the source range.");
  214. RefPtr<Node> this_point_node;
  215. u32 this_point_offset = 0;
  216. RefPtr<Node> other_point_node;
  217. u32 other_point_offset = 0;
  218. // 3. If how is:
  219. switch (how) {
  220. case HowToCompareBoundaryPoints::START_TO_START:
  221. // -> START_TO_START:
  222. // Let this point be this’s start. Let other point be sourceRange’s start.
  223. this_point_node = m_start_container;
  224. this_point_offset = m_start_offset;
  225. other_point_node = source_range.m_start_container;
  226. other_point_offset = source_range.m_start_offset;
  227. break;
  228. case HowToCompareBoundaryPoints::START_TO_END:
  229. // -> START_TO_END:
  230. // Let this point be this’s end. Let other point be sourceRange’s start.
  231. this_point_node = m_end_container;
  232. this_point_offset = m_end_offset;
  233. other_point_node = source_range.m_start_container;
  234. other_point_offset = source_range.m_start_offset;
  235. break;
  236. case HowToCompareBoundaryPoints::END_TO_END:
  237. // -> END_TO_END:
  238. // Let this point be this’s end. Let other point be sourceRange’s end.
  239. this_point_node = m_end_container;
  240. this_point_offset = m_end_offset;
  241. other_point_node = source_range.m_end_container;
  242. other_point_offset = source_range.m_end_offset;
  243. break;
  244. case HowToCompareBoundaryPoints::END_TO_START:
  245. // -> END_TO_START:
  246. // Let this point be this’s start. Let other point be sourceRange’s end.
  247. this_point_node = m_start_container;
  248. this_point_offset = m_start_offset;
  249. other_point_node = source_range.m_end_container;
  250. other_point_offset = source_range.m_end_offset;
  251. break;
  252. default:
  253. VERIFY_NOT_REACHED();
  254. }
  255. VERIFY(this_point_node);
  256. VERIFY(other_point_node);
  257. // 4. If the position of this point relative to other point is
  258. auto relative_position = position_of_boundary_point_relative_to_other_boundary_point(*this_point_node, this_point_offset, *other_point_node, other_point_offset);
  259. switch (relative_position) {
  260. case RelativeBoundaryPointPosition::Before:
  261. // -> before
  262. // Return −1.
  263. return -1;
  264. case RelativeBoundaryPointPosition::Equal:
  265. // -> equal
  266. // Return 0.
  267. return 0;
  268. case RelativeBoundaryPointPosition::After:
  269. // -> after
  270. // Return 1.
  271. return 1;
  272. default:
  273. VERIFY_NOT_REACHED();
  274. }
  275. }
  276. // https://dom.spec.whatwg.org/#concept-range-select
  277. ExceptionOr<void> Range::select(Node& node)
  278. {
  279. // 1. Let parent be node’s parent.
  280. auto* parent = node.parent();
  281. // 2. If parent is null, then throw an "InvalidNodeTypeError" DOMException.
  282. if (!parent)
  283. return InvalidNodeTypeError::create("Given node has no parent.");
  284. // 3. Let index be node’s index.
  285. auto index = node.index();
  286. // 4. Set range’s start to boundary point (parent, index).
  287. m_start_container = *parent;
  288. m_start_offset = index;
  289. // 5. Set range’s end to boundary point (parent, index plus 1).
  290. m_end_container = *parent;
  291. m_end_offset = index + 1;
  292. return {};
  293. }
  294. // https://dom.spec.whatwg.org/#dom-range-selectnode
  295. ExceptionOr<void> Range::select_node(Node& node)
  296. {
  297. // The selectNode(node) method steps are to select node within this.
  298. return select(node);
  299. }
  300. // https://dom.spec.whatwg.org/#dom-range-collapse
  301. void Range::collapse(bool to_start)
  302. {
  303. // The collapse(toStart) method steps are to, if toStart is true, set end to start; otherwise set start to end.
  304. if (to_start) {
  305. m_end_container = m_start_container;
  306. m_end_offset = m_start_offset;
  307. return;
  308. }
  309. m_start_container = m_end_container;
  310. m_start_offset = m_end_offset;
  311. }
  312. // https://dom.spec.whatwg.org/#dom-range-selectnodecontents
  313. ExceptionOr<void> Range::select_node_contents(Node const& node)
  314. {
  315. // 1. If node is a doctype, throw an "InvalidNodeTypeError" DOMException.
  316. if (is<DocumentType>(node))
  317. return InvalidNodeTypeError::create("Node cannot be a DocumentType.");
  318. // 2. Let length be the length of node.
  319. auto length = node.length();
  320. // 3. Set start to the boundary point (node, 0).
  321. m_start_container = node;
  322. m_start_offset = 0;
  323. // 4. Set end to the boundary point (node, length).
  324. m_end_container = node;
  325. m_end_offset = length;
  326. return {};
  327. }
  328. NonnullRefPtr<Range> Range::clone_range() const
  329. {
  330. return adopt_ref(*new Range(const_cast<Node&>(*m_start_container), m_start_offset, const_cast<Node&>(*m_end_container), m_end_offset));
  331. }
  332. NonnullRefPtr<Range> Range::inverted() const
  333. {
  334. return adopt_ref(*new Range(const_cast<Node&>(*m_end_container), m_end_offset, const_cast<Node&>(*m_start_container), m_start_offset));
  335. }
  336. NonnullRefPtr<Range> Range::normalized() const
  337. {
  338. if (m_start_container.ptr() == m_end_container.ptr()) {
  339. if (m_start_offset <= m_end_offset)
  340. return clone_range();
  341. return inverted();
  342. }
  343. if (m_start_container->is_before(m_end_container))
  344. return clone_range();
  345. return inverted();
  346. }
  347. // https://dom.spec.whatwg.org/#dom-range-commonancestorcontainer
  348. NonnullRefPtr<Node> Range::common_ancestor_container() const
  349. {
  350. // 1. Let container be start node.
  351. auto container = m_start_container;
  352. // 2. While container is not an inclusive ancestor of end node, let container be container’s parent.
  353. while (!container->is_inclusive_ancestor_of(m_end_container)) {
  354. VERIFY(container->parent());
  355. container = *container->parent();
  356. }
  357. // 3. Return container.
  358. return container;
  359. }
  360. // https://dom.spec.whatwg.org/#dom-range-intersectsnode
  361. bool Range::intersects_node(Node const& node) const
  362. {
  363. // 1. If node’s root is different from this’s root, return false.
  364. if (&node.root() != &root())
  365. return false;
  366. // 2. Let parent be node’s parent.
  367. auto* parent = node.parent();
  368. // 3. If parent is null, return true.
  369. if (!parent)
  370. return true;
  371. // 4. Let offset be node’s index.
  372. auto offset = node.index();
  373. // 5. If (parent, offset) is before end and (parent, offset plus 1) is after start, return true
  374. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(*parent, offset, m_end_container, m_end_offset);
  375. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(*parent, offset + 1, m_start_container, m_start_offset);
  376. if (relative_position_to_end == RelativeBoundaryPointPosition::Before && relative_position_to_start == RelativeBoundaryPointPosition::After)
  377. return true;
  378. // 6. Return false.
  379. return false;
  380. }
  381. // https://dom.spec.whatwg.org/#dom-range-ispointinrange
  382. ExceptionOr<bool> Range::is_point_in_range(Node const& node, u32 offset) const
  383. {
  384. // 1. If node’s root is different from this’s root, return false.
  385. if (&node.root() != &root())
  386. return false;
  387. // 2. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  388. if (is<DocumentType>(node))
  389. return InvalidNodeTypeError::create("Node cannot be a DocumentType.");
  390. // 3. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  391. if (offset > node.length())
  392. return IndexSizeError::create(String::formatted("Node does not contain a child at offset {}", offset));
  393. // 4. If (node, offset) is before start or after end, return false.
  394. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset);
  395. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset);
  396. if (relative_position_to_start == RelativeBoundaryPointPosition::Before || relative_position_to_end == RelativeBoundaryPointPosition::After)
  397. return false;
  398. // 5. Return true.
  399. return true;
  400. }
  401. // https://dom.spec.whatwg.org/#dom-range-comparepoint
  402. ExceptionOr<i16> Range::compare_point(Node const& node, u32 offset) const
  403. {
  404. // 1. If node’s root is different from this’s root, then throw a "WrongDocumentError" DOMException.
  405. if (&node.root() != &root())
  406. return WrongDocumentError::create("Given node is not in the same document as the range.");
  407. // 2. If node is a doctype, then throw an "InvalidNodeTypeError" DOMException.
  408. if (is<DocumentType>(node))
  409. return InvalidNodeTypeError::create("Node cannot be a DocumentType.");
  410. // 3. If offset is greater than node’s length, then throw an "IndexSizeError" DOMException.
  411. if (offset > node.length())
  412. return IndexSizeError::create(String::formatted("Node does not contain a child at offset {}", offset));
  413. // 4. If (node, offset) is before start, return −1.
  414. auto relative_position_to_start = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_start_container, m_start_offset);
  415. if (relative_position_to_start == RelativeBoundaryPointPosition::Before)
  416. return -1;
  417. // 5. If (node, offset) is after end, return 1.
  418. auto relative_position_to_end = position_of_boundary_point_relative_to_other_boundary_point(node, offset, m_end_container, m_end_offset);
  419. if (relative_position_to_end == RelativeBoundaryPointPosition::After)
  420. return 1;
  421. // 6. Return 0.
  422. return 0;
  423. }
  424. // https://dom.spec.whatwg.org/#dom-range-stringifier
  425. String Range::to_string() const
  426. {
  427. // 1. Let s be the empty string.
  428. StringBuilder builder;
  429. // 2. If this’s start node is this’s end node and it is a Text node,
  430. // then return the substring of that Text node’s data beginning at this’s start offset and ending at this’s end offset.
  431. if (start_container() == end_container() && is<Text>(*start_container()))
  432. return static_cast<Text const&>(*start_container()).data().substring(start_offset(), end_offset() - start_offset());
  433. // 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.
  434. if (is<Text>(*start_container()))
  435. builder.append(static_cast<Text const&>(*start_container()).data().substring_view(start_offset()));
  436. // 4. Append the concatenation of the data of all Text nodes that are contained in this, in tree order, to s.
  437. for (Node const* node = start_container(); node != end_container()->next_sibling(); node = node->next_in_pre_order()) {
  438. if (is<Text>(*node) && contains_node(*node))
  439. builder.append(static_cast<Text const&>(*node).data());
  440. }
  441. // 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.
  442. if (is<Text>(*end_container()))
  443. builder.append(static_cast<Text const&>(*end_container()).data().substring_view(0, end_offset()));
  444. // 6. Return s.
  445. return builder.to_string();
  446. }
  447. // https://dom.spec.whatwg.org/#dom-range-extractcontents
  448. ExceptionOr<NonnullRefPtr<DocumentFragment>> Range::extract_contents()
  449. {
  450. return extract();
  451. }
  452. // https://dom.spec.whatwg.org/#concept-range-extract
  453. ExceptionOr<NonnullRefPtr<DocumentFragment>> Range::extract()
  454. {
  455. // 1. Let fragment be a new DocumentFragment node whose node document is range’s start node’s node document.
  456. auto fragment = adopt_ref(*new DocumentFragment(const_cast<Document&>(start_container()->document())));
  457. // 2. If range is collapsed, then return fragment.
  458. if (collapsed())
  459. return fragment;
  460. // 3. Let original start node, original start offset, original end node, and original end offset
  461. // be range’s start node, start offset, end node, and end offset, respectively.
  462. NonnullRefPtr<Node> original_start_node = m_start_container;
  463. auto original_start_offset = m_start_offset;
  464. NonnullRefPtr<Node> original_end_node = m_end_container;
  465. auto original_end_offset = m_end_offset;
  466. // 4. If original start node is original end node and it is a CharacterData node, then:
  467. if (original_start_node.ptr() == original_end_node.ptr() && is<CharacterData>(*original_start_node)) {
  468. // 1. Let clone be a clone of original start node.
  469. auto clone = original_start_node->clone_node();
  470. // 2. Set the data of clone to the result of substringing data with node original start node,
  471. // offset original start offset, and count original end offset minus original start offset.
  472. auto result = static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_end_offset - original_start_offset);
  473. if (result.is_exception())
  474. return result.exception();
  475. verify_cast<CharacterData>(*clone).set_data(result.release_value());
  476. // 3. Append clone to fragment.
  477. fragment->append_child(clone);
  478. // 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.
  479. static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_end_offset - original_start_offset, "");
  480. // 5. Return fragment.
  481. return fragment;
  482. }
  483. // 5. Let common ancestor be original start node.
  484. NonnullRefPtr<Node> common_ancestor = original_start_node;
  485. // 6. While common ancestor is not an inclusive ancestor of original end node, set common ancestor to its own parent.
  486. while (!common_ancestor->is_inclusive_ancestor_of(original_end_node))
  487. common_ancestor = *common_ancestor->parent_node();
  488. // 7. Let first partially contained child be null.
  489. RefPtr<Node> first_partially_contained_child;
  490. // 8. If original start node is not an inclusive ancestor of original end node,
  491. // set first partially contained child to the first child of common ancestor that is partially contained in range.
  492. if (!original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  493. for (auto* child = common_ancestor->first_child(); child; child = child->next_sibling()) {
  494. if (partially_contains_node(*child)) {
  495. first_partially_contained_child = child;
  496. break;
  497. }
  498. }
  499. }
  500. // 9. Let last partially contained child be null.
  501. RefPtr<Node> last_partially_contained_child;
  502. // 10. If original end node is not an inclusive ancestor of original start node,
  503. // set last partially contained child to the last child of common ancestor that is partially contained in range.
  504. if (!original_end_node->is_inclusive_ancestor_of(original_start_node)) {
  505. for (auto* child = common_ancestor->last_child(); child; child = child->previous_sibling()) {
  506. if (partially_contains_node(*child)) {
  507. last_partially_contained_child = child;
  508. break;
  509. }
  510. }
  511. }
  512. // 11. Let contained children be a list of all children of common ancestor that are contained in range, in tree order.
  513. Vector<NonnullRefPtr<Node>> contained_children;
  514. for (Node const* node = common_ancestor->first_child(); node; node = node->next_sibling()) {
  515. if (contains_node(*node))
  516. contained_children.append(*node);
  517. }
  518. // 12. If any member of contained children is a doctype, then throw a "HierarchyRequestError" DOMException.
  519. for (auto const& child : contained_children) {
  520. if (is<DocumentType>(*child))
  521. return DOM::HierarchyRequestError::create("Contained child is a DocumentType");
  522. }
  523. RefPtr<Node> new_node;
  524. size_t new_offset = 0;
  525. // 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.
  526. if (original_start_node->is_inclusive_ancestor_of(original_end_node)) {
  527. new_node = original_start_node;
  528. new_offset = original_start_offset;
  529. }
  530. // 14. Otherwise:
  531. else {
  532. // 1. Let reference node equal original start node.
  533. RefPtr<Node> reference_node = original_start_node;
  534. // 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.
  535. while (reference_node->parent_node() && !reference_node->parent_node()->is_inclusive_ancestor_of(original_end_node))
  536. reference_node = reference_node->parent_node();
  537. // 3. Set new node to the parent of reference node, and new offset to one plus reference node’s index.
  538. new_node = reference_node->parent_node();
  539. new_offset = 1 + reference_node->index();
  540. }
  541. // 15. If first partially contained child is a CharacterData node, then:
  542. if (first_partially_contained_child && is<CharacterData>(*first_partially_contained_child)) {
  543. // 1. Let clone be a clone of original start node.
  544. auto clone = original_start_node->clone_node();
  545. // 2. Set the data of clone to the result of substringing data with node original start node, offset original start offset,
  546. // and count original start node’s length minus original start offset.
  547. auto result = static_cast<CharacterData const&>(*original_start_node).substring_data(original_start_offset, original_start_node->length() - original_start_offset);
  548. if (result.is_exception())
  549. return result.exception();
  550. verify_cast<CharacterData>(*clone).set_data(result.release_value());
  551. // 3. Append clone to fragment.
  552. fragment->append_child(clone);
  553. // 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.
  554. static_cast<CharacterData&>(*original_start_node).replace_data(original_start_offset, original_start_node->length() - original_start_offset, "");
  555. }
  556. // 16. Otherwise, if first partially contained child is not null:
  557. else if (first_partially_contained_child) {
  558. // 1. Let clone be a clone of first partially contained child.
  559. auto clone = first_partially_contained_child->clone_node();
  560. // 2. Append clone to fragment.
  561. fragment->append_child(clone);
  562. // 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).
  563. auto subrange = Range::create(original_start_node, original_start_offset, *first_partially_contained_child, first_partially_contained_child->length());
  564. // 4. Let subfragment be the result of extracting subrange.
  565. auto result = subrange->extract();
  566. if (result.is_exception())
  567. return result.exception();
  568. auto subfragment = result.release_value();
  569. // 5. Append subfragment to clone.
  570. clone->append_child(subfragment);
  571. }
  572. // 17. For each contained child in contained children, append contained child to fragment.
  573. for (auto& contained_child : contained_children) {
  574. fragment->append_child(contained_child);
  575. }
  576. // 18. If last partially contained child is a CharacterData node, then:
  577. if (last_partially_contained_child && is<CharacterData>(*last_partially_contained_child)) {
  578. // 1. Let clone be a clone of original end node.
  579. auto clone = original_end_node->clone_node();
  580. // 2. Set the data of clone to the result of substringing data with node original end node, offset 0, and count original end offset.
  581. auto result = static_cast<CharacterData const&>(*original_end_node).substring_data(0, original_end_offset);
  582. if (result.is_exception())
  583. return result.exception();
  584. verify_cast<CharacterData>(*clone).set_data(result.release_value());
  585. // 3. Append clone to fragment.
  586. fragment->append_child(clone);
  587. // 4. Replace data with node original end node, offset 0, count original end offset, and data the empty string.
  588. verify_cast<CharacterData>(*original_end_node).replace_data(0, original_end_offset, "");
  589. }
  590. // 19. Otherwise, if last partially contained child is not null:
  591. else if (last_partially_contained_child) {
  592. // 1. Let clone be a clone of last partially contained child.
  593. auto clone = last_partially_contained_child->clone_node();
  594. // 2. Append clone to fragment.
  595. fragment->append_child(clone);
  596. // 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).
  597. auto subrange = Range::create(*last_partially_contained_child, 0, original_end_node, original_end_offset);
  598. // 4. Let subfragment be the result of extracting subrange.
  599. auto result = subrange->extract();
  600. if (result.is_exception())
  601. return result.exception();
  602. auto subfragment = result.release_value();
  603. // 5. Append subfragment to clone.
  604. clone->append_child(subfragment);
  605. }
  606. // 20. Set range’s start and end to (new node, new offset).
  607. set_start(*new_node, new_offset);
  608. set_end(*new_node, new_offset);
  609. // 21. Return fragment.
  610. return fragment;
  611. }
  612. // https://dom.spec.whatwg.org/#contained
  613. bool Range::contains_node(Node const& node) const
  614. {
  615. // A node node is contained in a live range range if node’s root is range’s root,
  616. if (&node.root() != &root())
  617. return false;
  618. // and (node, 0) is after range’s start,
  619. if (position_of_boundary_point_relative_to_other_boundary_point(node, 0, m_start_container, m_start_offset) != RelativeBoundaryPointPosition::After)
  620. return false;
  621. // and (node, node’s length) is before range’s end.
  622. if (position_of_boundary_point_relative_to_other_boundary_point(node, node.length(), m_end_container, m_end_offset) != RelativeBoundaryPointPosition::Before)
  623. return false;
  624. return true;
  625. }
  626. // https://dom.spec.whatwg.org/#partially-contained
  627. bool Range::partially_contains_node(Node const& node) const
  628. {
  629. // 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.
  630. if (node.is_inclusive_ancestor_of(m_start_container) && &node != m_end_container.ptr())
  631. return true;
  632. if (node.is_inclusive_ancestor_of(m_end_container) && &node != m_start_container.ptr())
  633. return true;
  634. return false;
  635. }
  636. // https://dom.spec.whatwg.org/#dom-range-insertnode
  637. ExceptionOr<void> Range::insert_node(NonnullRefPtr<Node> node)
  638. {
  639. return insert(node);
  640. }
  641. // https://dom.spec.whatwg.org/#concept-range-insert
  642. ExceptionOr<void> Range::insert(NonnullRefPtr<Node> node)
  643. {
  644. // 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.
  645. if ((is<ProcessingInstruction>(*m_start_container) || is<Comment>(*m_start_container))
  646. || (is<Text>(*m_start_container) && !m_start_container->parent_node())
  647. || m_start_container == node.ptr()) {
  648. return DOM::HierarchyRequestError::create("Range has inappropriate start node for insertion");
  649. }
  650. // 2. Let referenceNode be null.
  651. RefPtr<Node> reference_node;
  652. // 3. If range’s start node is a Text node, set referenceNode to that Text node.
  653. if (is<Text>(*m_start_container)) {
  654. reference_node = m_start_container;
  655. }
  656. // 4. Otherwise, set referenceNode to the child of start node whose index is start offset, and null if there is no such child.
  657. else {
  658. reference_node = m_start_container->child_at_index(m_start_offset);
  659. }
  660. // 5. Let parent be range’s start node if referenceNode is null, and referenceNode’s parent otherwise.
  661. RefPtr<Node> parent;
  662. if (!reference_node)
  663. parent = m_start_container;
  664. else
  665. parent = reference_node->parent();
  666. // 6. Ensure pre-insertion validity of node into parent before referenceNode.
  667. if (auto result = parent->ensure_pre_insertion_validity(node, reference_node); result.is_exception())
  668. return result.exception();
  669. // 7. If range’s start node is a Text node, set referenceNode to the result of splitting it with offset range’s start offset.
  670. if (is<Text>(*m_start_container)) {
  671. auto result = static_cast<Text&>(*m_start_container).split_text(m_start_offset);
  672. if (result.is_exception())
  673. return result.exception();
  674. reference_node = result.release_value();
  675. }
  676. // 8. If node is referenceNode, set referenceNode to its next sibling.
  677. if (node == reference_node)
  678. reference_node = reference_node->next_sibling();
  679. // 9. If node’s parent is non-null, then remove node.
  680. if (node->parent())
  681. node->remove();
  682. // 10. Let newOffset be parent’s length if referenceNode is null, and referenceNode’s index otherwise.
  683. size_t new_offset = 0;
  684. if (!reference_node)
  685. new_offset = parent->length();
  686. else
  687. new_offset = reference_node->index();
  688. // 11. Increase newOffset by node’s length if node is a DocumentFragment node, and one otherwise.
  689. if (is<DocumentFragment>(*node))
  690. new_offset += node->length();
  691. else
  692. new_offset += 1;
  693. // 12. Pre-insert node into parent before referenceNode.
  694. if (auto result = parent->pre_insert(node, reference_node); result.is_exception())
  695. return result.exception();
  696. // 13. If range is collapsed, then set range’s end to (parent, newOffset).
  697. if (collapsed())
  698. set_end(*parent, new_offset);
  699. return {};
  700. }
  701. // https://dom.spec.whatwg.org/#dom-range-surroundcontents
  702. ExceptionOr<void> Range::surround_contents(NonnullRefPtr<Node> new_parent)
  703. {
  704. // 1. If a non-Text node is partially contained in this, then throw an "InvalidStateError" DOMException.
  705. Node* start_non_text_node = start_container();
  706. if (is<Text>(*start_non_text_node))
  707. start_non_text_node = start_non_text_node->parent_node();
  708. Node* end_non_text_node = end_container();
  709. if (is<Text>(*end_non_text_node))
  710. end_non_text_node = end_non_text_node->parent_node();
  711. if (start_non_text_node != end_non_text_node)
  712. return InvalidStateError::create("Non-Text node is partially contained in range.");
  713. // 2. If newParent is a Document, DocumentType, or DocumentFragment node, then throw an "InvalidNodeTypeError" DOMException.
  714. if (is<Document>(*new_parent) || is<DocumentType>(*new_parent) || is<DocumentFragment>(*new_parent))
  715. return InvalidNodeTypeError::create("Invalid parent node type");
  716. // 3. Let fragment be the result of extracting this.
  717. auto fragment_or_error = extract();
  718. if (fragment_or_error.is_exception())
  719. return fragment_or_error.exception();
  720. auto fragment = fragment_or_error.release_value();
  721. // 4. If newParent has children, then replace all with null within newParent.
  722. if (new_parent->has_children())
  723. new_parent->replace_all(nullptr);
  724. // 5. Insert newParent into this.
  725. if (auto result = insert(new_parent); result.is_exception())
  726. return result.exception();
  727. // 6. Append fragment to newParent.
  728. new_parent->append_child(fragment);
  729. // 7. Select newParent within this.
  730. return select(*new_parent);
  731. }
  732. }