Serenity Operating System
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
8#include <AK/Utf8View.h>
9#include <LibUnicode/Segmentation.h>
10#include <LibWeb/DOM/Node.h>
11#include <LibWeb/DOM/Position.h>
12#include <LibWeb/DOM/Text.h>
13
14namespace Web::DOM {
15
16Position::Position(Node& node, unsigned offset)
17 : m_node(JS::make_handle(node))
18 , m_offset(offset)
19{
20}
21
22ErrorOr<String> Position::to_string() const
23{
24 if (!node())
25 return String::formatted("DOM::Position(nullptr, {})", offset());
26 return String::formatted("DOM::Position({} ({})), {})", node()->node_name(), node(), offset());
27}
28
29bool Position::increment_offset()
30{
31 if (!is<DOM::Text>(*m_node))
32 return false;
33
34 auto& node = verify_cast<DOM::Text>(*m_node);
35 auto text = Utf8View(node.data());
36
37 if (auto offset = Unicode::next_grapheme_segmentation_boundary(text, m_offset); offset.has_value()) {
38 m_offset = *offset;
39 return true;
40 }
41
42 // NOTE: Already at end of current node.
43 return false;
44}
45
46bool Position::decrement_offset()
47{
48 if (!is<DOM::Text>(*m_node))
49 return false;
50
51 auto& node = verify_cast<DOM::Text>(*m_node);
52 auto text = Utf8View(node.data());
53
54 if (auto offset = Unicode::previous_grapheme_segmentation_boundary(text, m_offset); offset.has_value()) {
55 m_offset = *offset;
56 return true;
57 }
58
59 // NOTE: Already at beginning of current node.
60 return false;
61}
62
63bool Position::offset_is_at_end_of_node() const
64{
65 if (!is<DOM::Text>(*m_node))
66 return false;
67
68 auto& node = verify_cast<DOM::Text>(*m_node);
69 auto text = node.data();
70 return m_offset == text.length();
71}
72
73}