Position.h 1.6 KB

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