Position.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 <LibUnicode/Segmentation.h>
  9. #include <LibWeb/DOM/Node.h>
  10. #include <LibWeb/DOM/Position.h>
  11. #include <LibWeb/DOM/Text.h>
  12. namespace Web::DOM {
  13. JS_DEFINE_ALLOCATOR(Position);
  14. Position::Position(JS::GCPtr<Node> node, unsigned offset)
  15. : m_node(node)
  16. , m_offset(offset)
  17. {
  18. }
  19. void Position::visit_edges(Visitor& visitor)
  20. {
  21. Base::visit_edges(visitor);
  22. visitor.visit(m_node);
  23. }
  24. ErrorOr<String> Position::to_string() const
  25. {
  26. if (!node())
  27. return String::formatted("DOM::Position(nullptr, {})", offset());
  28. return String::formatted("DOM::Position({} ({})), {})", node()->node_name(), node().ptr(), offset());
  29. }
  30. bool Position::increment_offset()
  31. {
  32. if (!is<DOM::Text>(*m_node))
  33. return false;
  34. auto& node = verify_cast<DOM::Text>(*m_node);
  35. auto text = Utf8View(node.data());
  36. if (auto offset = Unicode::next_grapheme_segmentation_boundary(text, m_offset); offset.has_value()) {
  37. m_offset = *offset;
  38. return true;
  39. }
  40. // NOTE: Already at end of current node.
  41. return false;
  42. }
  43. bool Position::decrement_offset()
  44. {
  45. if (!is<DOM::Text>(*m_node))
  46. return false;
  47. auto& node = verify_cast<DOM::Text>(*m_node);
  48. auto text = Utf8View(node.data());
  49. if (auto offset = Unicode::previous_grapheme_segmentation_boundary(text, m_offset); offset.has_value()) {
  50. m_offset = *offset;
  51. return true;
  52. }
  53. // NOTE: Already at beginning of current node.
  54. return false;
  55. }
  56. bool Position::offset_is_at_end_of_node() const
  57. {
  58. if (!is<DOM::Text>(*m_node))
  59. return false;
  60. auto& node = verify_cast<DOM::Text>(*m_node);
  61. auto text = node.data();
  62. return m_offset == text.bytes_as_string_view().length();
  63. }
  64. }