Position.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. Position::Position(Node& node, unsigned offset)
  14. : m_node(JS::make_handle(node))
  15. , m_offset(offset)
  16. {
  17. }
  18. ErrorOr<String> Position::to_string() const
  19. {
  20. if (!node())
  21. return String::formatted("DOM::Position(nullptr, {})", offset());
  22. return String::formatted("DOM::Position({} ({})), {})", node()->node_name(), node(), offset());
  23. }
  24. bool Position::increment_offset()
  25. {
  26. if (!is<DOM::Text>(*m_node))
  27. return false;
  28. auto& node = verify_cast<DOM::Text>(*m_node);
  29. auto text = Utf8View(node.data());
  30. if (auto offset = Unicode::next_grapheme_segmentation_boundary(text, m_offset); offset.has_value()) {
  31. m_offset = *offset;
  32. return true;
  33. }
  34. // NOTE: Already at end of current node.
  35. return false;
  36. }
  37. bool Position::decrement_offset()
  38. {
  39. if (!is<DOM::Text>(*m_node))
  40. return false;
  41. auto& node = verify_cast<DOM::Text>(*m_node);
  42. auto text = Utf8View(node.data());
  43. if (auto offset = Unicode::previous_grapheme_segmentation_boundary(text, m_offset); offset.has_value()) {
  44. m_offset = *offset;
  45. return true;
  46. }
  47. // NOTE: Already at beginning of current node.
  48. return false;
  49. }
  50. bool Position::offset_is_at_end_of_node() const
  51. {
  52. if (!is<DOM::Text>(*m_node))
  53. return false;
  54. auto& node = verify_cast<DOM::Text>(*m_node);
  55. auto text = node.data();
  56. return m_offset == text.length();
  57. }
  58. }