Position.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  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. String Position::to_string() const
  18. {
  19. if (!node())
  20. return String::formatted("DOM::Position(nullptr, {})", offset());
  21. return String::formatted("DOM::Position({} ({})), {})", node()->node_name(), node(), offset());
  22. }
  23. bool Position::increment_offset()
  24. {
  25. if (!is<DOM::Text>(*m_node))
  26. return false;
  27. auto& node = verify_cast<DOM::Text>(*m_node);
  28. auto text = Utf8View(node.data());
  29. for (auto iterator = text.begin(); !iterator.done(); ++iterator) {
  30. if (text.byte_offset_of(iterator) >= m_offset) {
  31. // NOTE: If the current offset is inside a multi-byte code point, it will be moved to the start of the next code point.
  32. m_offset = text.byte_offset_of(++iterator);
  33. return true;
  34. }
  35. }
  36. // NOTE: Already at end of current node.
  37. return false;
  38. }
  39. bool Position::decrement_offset()
  40. {
  41. if (m_offset == 0 || !is<DOM::Text>(*m_node))
  42. return false;
  43. auto& node = verify_cast<DOM::Text>(*m_node);
  44. auto text = Utf8View(node.data());
  45. size_t last_smaller_offset = 0;
  46. for (auto iterator = text.begin(); !iterator.done(); ++iterator) {
  47. auto byte_offset = text.byte_offset_of(iterator);
  48. if (byte_offset >= m_offset) {
  49. break;
  50. }
  51. last_smaller_offset = text.byte_offset_of(iterator);
  52. }
  53. // NOTE: If the current offset is inside a multi-byte code point, it will be moved to the start of that code point.
  54. m_offset = last_smaller_offset;
  55. return true;
  56. }
  57. bool Position::offset_is_at_end_of_node() const
  58. {
  59. if (!is<DOM::Text>(*m_node))
  60. return false;
  61. auto& node = verify_cast<DOM::Text>(*m_node);
  62. auto text = node.data();
  63. return m_offset == text.length();
  64. }
  65. }