From c7889a00156bd50ab8daebb38f17b63725395c91 Mon Sep 17 00:00:00 2001 From: Samuel Ugochukwu Date: Thu, 14 Nov 2024 12:52:01 +0100 Subject: [PATCH] Add `applyStyleSheet` function, allowing users to apply CSS styles directly to the document #196 --- include/lunasvg.h | 6 ++++++ source/svgparser.cpp | 16 +++++++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/include/lunasvg.h b/include/lunasvg.h index 9447f3c..c3f7c8a 100644 --- a/include/lunasvg.h +++ b/include/lunasvg.h @@ -682,6 +682,12 @@ class LUNASVG_API Document { */ static std::unique_ptr 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. diff --git a/source/svgparser.cpp b/source/svgparser.cpp index 704d684..fb73e35 100644 --- a/source/svgparser.cpp +++ b/source/svgparser.cpp @@ -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) { @@ -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(this); node->setData(buffer); @@ -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) { @@ -888,9 +897,6 @@ bool Document::parse(const char* data, size_t length) return true; }); } - - m_rootElement->build(); - return true; } } // namespace lunasvg