Position.cpp 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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/Segmenter.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. if (auto offset = node.segmenter().next_boundary(m_offset); offset.has_value()) {
  36. m_offset = *offset;
  37. return true;
  38. }
  39. // NOTE: Already at end of current node.
  40. return false;
  41. }
  42. bool Position::decrement_offset()
  43. {
  44. if (!is<DOM::Text>(*m_node))
  45. return false;
  46. auto& node = verify_cast<DOM::Text>(*m_node);
  47. if (auto offset = node.segmenter().previous_boundary(m_offset); offset.has_value()) {
  48. m_offset = *offset;
  49. return true;
  50. }
  51. // NOTE: Already at beginning of current node.
  52. return false;
  53. }
  54. bool Position::offset_is_at_end_of_node() const
  55. {
  56. if (!is<DOM::Text>(*m_node))
  57. return false;
  58. auto& node = verify_cast<DOM::Text>(*m_node);
  59. auto text = node.data();
  60. return m_offset == text.bytes_as_string_view().length();
  61. }
  62. }