Skip to content

Commit

Permalink
Add applyStyleSheet function, allowing users to apply CSS styles di…
Browse files Browse the repository at this point in the history
…rectly to the document #196
  • Loading branch information
sammycage committed Nov 14, 2024
1 parent 23578c7 commit c7889a0
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
6 changes: 6 additions & 0 deletions include/lunasvg.h
Original file line number Diff line number Diff line change
Expand Up @@ -682,6 +682,12 @@ class LUNASVG_API Document {
*/
static std::unique_ptr<Document> loadFromData(const char* data, size_t length);

/**
* @brief Applies a CSS stylesheet to the document.
* @param content A string containing the CSS rules to apply.
*/
void applyStyleSheet(const std::string& content);

/**
* @brief Returns the intrinsic width of the document in pixels.
* @return The width of the document.
Expand Down
16 changes: 11 additions & 5 deletions source/svgparser.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -683,7 +683,7 @@ inline bool readIdentifier(std::string_view& input, std::string& output)
bool Document::parse(const char* data, size_t length)
{
std::string buffer;
StyleSheet styleSheet;
std::string styleSheet;
SVGElement* currentElement = nullptr;
int ignoring = 0;
auto handleText = [&](const std::string_view& text, bool in_cdata) {
Expand All @@ -701,7 +701,7 @@ bool Document::parse(const char* data, size_t length)

if(currentElement->id() == ElementID::Style) {
removeStyleComments(buffer);
styleSheet.parseSheet(buffer);
styleSheet.append(buffer);
} else {
auto node = std::make_unique<SVGTextNode>(this);
node->setData(buffer);
Expand Down Expand Up @@ -871,6 +871,15 @@ bool Document::parse(const char* data, size_t length)

if(m_rootElement == nullptr || ignoring > 0 || !input.empty())
return false;
applyStyleSheet(styleSheet);
m_rootElement->build();
return true;
}

void Document::applyStyleSheet(const std::string& content)
{
StyleSheet styleSheet;
styleSheet.parseSheet(content);
if(!styleSheet.isEmpty()) {
styleSheet.sortRules();
m_rootElement->transverse([&styleSheet](SVGNode* node) {
Expand All @@ -888,9 +897,6 @@ bool Document::parse(const char* data, size_t length)
return true;
});
}

m_rootElement->build();
return true;
}

} // namespace lunasvg

0 comments on commit c7889a0

Please sign in to comment.