Position.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <andreas@ladybird.org>
  3. * Copyright (c) 2021, Max Wipfli <mail@maxwipfli.ch>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #pragma once
  8. #include <AK/Error.h>
  9. #include <AK/RefPtr.h>
  10. #include <AK/String.h>
  11. #include <LibJS/Heap/Heap.h>
  12. #include <LibWeb/DOM/Node.h>
  13. #include <LibWeb/Forward.h>
  14. namespace Web::DOM {
  15. class Position final : public JS::Cell {
  16. JS_CELL(Position, JS::Cell);
  17. JS_DECLARE_ALLOCATOR(Position);
  18. public:
  19. [[nodiscard]] static JS::NonnullGCPtr<Position> create(JS::Realm& realm, JS::NonnullGCPtr<Node> node, unsigned offset)
  20. {
  21. return realm.heap().allocate<Position>(realm, node, offset);
  22. }
  23. JS::GCPtr<Node> node() { return m_node; }
  24. JS::GCPtr<Node const> node() const { return m_node; }
  25. void set_node(JS::NonnullGCPtr<Node> node) { m_node = node; }
  26. unsigned offset() const { return m_offset; }
  27. bool offset_is_at_end_of_node() const;
  28. void set_offset(unsigned value) { m_offset = value; }
  29. bool increment_offset();
  30. bool decrement_offset();
  31. bool increment_offset_to_next_word();
  32. bool decrement_offset_to_previous_word();
  33. bool equals(JS::NonnullGCPtr<Position> other) const
  34. {
  35. return m_node.ptr() == other->m_node.ptr() && m_offset == other->m_offset;
  36. }
  37. ErrorOr<String> to_string() const;
  38. private:
  39. Position(JS::GCPtr<Node>, unsigned offset);
  40. virtual void visit_edges(Visitor&) override;
  41. JS::GCPtr<Node> m_node;
  42. unsigned m_offset { 0 };
  43. };
  44. }
  45. template<>
  46. struct AK::Formatter<Web::DOM::Position> : Formatter<StringView> {
  47. ErrorOr<void> format(FormatBuilder& builder, Web::DOM::Position const& value)
  48. {
  49. return Formatter<StringView>::format(builder, TRY(value.to_string()));
  50. }
  51. };