Position.h 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. #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 equals(JS::NonnullGCPtr<Position> other) const
  32. {
  33. return m_node.ptr() == other->m_node.ptr() && m_offset == other->m_offset;
  34. }
  35. ErrorOr<String> to_string() const;
  36. private:
  37. Position(JS::GCPtr<Node>, unsigned offset);
  38. virtual void visit_edges(Visitor&) override;
  39. JS::GCPtr<Node> m_node;
  40. unsigned m_offset { 0 };
  41. };
  42. }
  43. template<>
  44. struct AK::Formatter<Web::DOM::Position> : Formatter<StringView> {
  45. ErrorOr<void> format(FormatBuilder& builder, Web::DOM::Position const& value)
  46. {
  47. return Formatter<StringView>::format(builder, TRY(value.to_string()));
  48. }
  49. };