blob: e4dc8cd67cf0feb9c50fb11d112abad55e15b904 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
|
/*
* Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
* Copyright (c) 2021, Max Wipfli <mail@maxwipfli.ch>
*
* SPDX-License-Identifier: BSD-2-Clause
*/
#include <AK/Utf8View.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/Position.h>
#include <LibWeb/DOM/Text.h>
namespace Web::DOM {
Position::Position(Node& node, unsigned offset)
: m_node(node)
, m_offset(offset)
{
}
Position::~Position()
{
}
String Position::to_string() const
{
if (!node())
return String::formatted("DOM::Position(nullptr, {})", offset());
return String::formatted("DOM::Position({} ({})), {})", node()->node_name(), node(), offset());
}
bool Position::increment_offset()
{
if (!is<DOM::Text>(*m_node))
return false;
auto& node = downcast<DOM::Text>(*m_node);
auto text = Utf8View(node.data());
for (auto iterator = text.begin(); !iterator.done(); ++iterator) {
if (text.byte_offset_of(iterator) >= m_offset) {
// NOTE: If the current offset is inside a multi-byte code point, it will be moved to the start of the next code point.
m_offset = text.byte_offset_of(++iterator);
return true;
}
}
// NOTE: Already at end of current node.
return false;
}
bool Position::decrement_offset()
{
if (m_offset == 0 || !is<DOM::Text>(*m_node))
return false;
auto& node = downcast<DOM::Text>(*m_node);
auto text = Utf8View(node.data());
size_t last_smaller_offset = 0;
for (auto iterator = text.begin(); !iterator.done(); ++iterator) {
auto byte_offset = text.byte_offset_of(iterator);
if (byte_offset >= m_offset) {
break;
}
last_smaller_offset = text.byte_offset_of(iterator);
}
// NOTE: If the current offset is inside a multi-byte code point, it will be moved to the start of that code point.
m_offset = last_smaller_offset;
return true;
}
bool Position::offset_is_at_end_of_node() const
{
if (!is<DOM::Text>(*m_node))
return false;
auto& node = downcast<DOM::Text>(*m_node);
auto text = node.data();
return m_offset == text.length();
}
}
|