Position.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Max Wipfli <mail@maxwipfli.ch>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Utf8View.h>
  8. #include <LibWeb/DOM/Node.h>
  9. #include <LibWeb/DOM/Position.h>
  10. #include <LibWeb/DOM/Text.h>
  11. namespace Web::DOM {
  12. Position::Position(Node& node, unsigned offset)
  13. : m_node(node)
  14. , m_offset(offset)
  15. {
  16. }
  17. Position::~Position()
  18. {
  19. }
  20. String Position::to_string() const
  21. {
  22. if (!node())
  23. return String::formatted("DOM::Position(nullptr, {})", offset());
  24. return String::formatted("DOM::Position({} ({})), {})", node()->node_name(), node(), offset());
  25. }
  26. bool Position::increment_offset()
  27. {
  28. if (!is<DOM::Text>(*m_node))
  29. return false;
  30. auto& node = verify_cast<DOM::Text>(*m_node);
  31. auto text = Utf8View(node.data());
  32. for (auto iterator = text.begin(); !iterator.done(); ++iterator) {
  33. if (text.byte_offset_of(iterator) >= m_offset) {
  34. // NOTE: If the current offset is inside a multi-byte code point, it will be moved to the start of the next code point.
  35. m_offset = text.byte_offset_of(++iterator);
  36. return true;
  37. }
  38. }
  39. // NOTE: Already at end of current node.
  40. return false;
  41. }
  42. bool Position::decrement_offset()
  43. {
  44. if (m_offset == 0 || !is<DOM::Text>(*m_node))
  45. return false;
  46. auto& node = verify_cast<DOM::Text>(*m_node);
  47. auto text = Utf8View(node.data());
  48. size_t last_smaller_offset = 0;
  49. for (auto iterator = text.begin(); !iterator.done(); ++iterator) {
  50. auto byte_offset = text.byte_offset_of(iterator);
  51. if (byte_offset >= m_offset) {
  52. break;
  53. }
  54. last_smaller_offset = text.byte_offset_of(iterator);
  55. }
  56. // NOTE: If the current offset is inside a multi-byte code point, it will be moved to the start of that code point.
  57. m_offset = last_smaller_offset;
  58. return true;
  59. }
  60. bool Position::offset_is_at_end_of_node() const
  61. {
  62. if (!is<DOM::Text>(*m_node))
  63. return false;
  64. auto& node = verify_cast<DOM::Text>(*m_node);
  65. auto text = node.data();
  66. return m_offset == text.length();
  67. }
  68. }