1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-26 05:27:46 +00:00

LibWeb: Implement stringifier for DOM Range :^)

This commit is contained in:
Andreas Kling 2022-03-21 16:29:19 +01:00
parent c8bdac8736
commit 394cd77467
3 changed files with 34 additions and 0 deletions

View file

@ -9,6 +9,7 @@
#include <LibWeb/DOM/DocumentType.h>
#include <LibWeb/DOM/Node.h>
#include <LibWeb/DOM/Range.h>
#include <LibWeb/DOM/Text.h>
#include <LibWeb/HTML/Window.h>
namespace Web::DOM {
@ -498,4 +499,33 @@ ExceptionOr<i16> Range::compare_point(Node const& node, u32 offset) const
return 0;
}
// https://dom.spec.whatwg.org/#dom-range-stringifier
String Range::to_string() const
{
// 1. Let s be the empty string.
StringBuilder builder;
// 2. If thiss start node is thiss end node and it is a Text node,
// then return the substring of that Text nodes data beginning at thiss start offset and ending at thiss end offset.
if (start_container() == end_container() && is<Text>(*start_container()))
return static_cast<Text const&>(*start_container()).data().substring(start_offset(), end_offset());
// 3. If thiss start node is a Text node, then append the substring of that nodes data from thiss start offset until the end to s.
if (is<Text>(*start_container()))
builder.append(static_cast<Text const&>(*start_container()).data().substring_view(start_offset()));
// 4. Append the concatenation of the data of all Text nodes that are contained in this, in tree order, to s.
for (Node const* node = start_container()->next_in_pre_order(); node && node != end_container(); node = node->next_in_pre_order()) {
if (is<Text>(*node))
builder.append(static_cast<Text const&>(*node).data());
}
// 5. If thiss end node is a Text node, then append the substring of that nodes data from its start until thiss end offset to s.
if (is<Text>(*end_container()))
builder.append(static_cast<Text const&>(*end_container()).data().substring_view(0, end_offset()));
// 6. Return s.
return builder.to_string();
}
}