1 /*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2023. All rights reserved.
3 * Description: Implementation for Css style parser.
4 * Create: 2020/03/31
5 */
6
7 #include "CssStyleParser.h"
8
getArributesMap(const std::string & key) const9 const std::unordered_map<std::string, std::string>& CssStyleParser::getArributesMap(const std::string& key) const
10 {
11 auto styleClassIter = fStyleMap.find(key);
12 if (styleClassIter != fStyleMap.end()) {
13 return styleClassIter->second;
14 } else {
15 static std::unordered_map<std::string, std::string> fEmptyMap;
16 return fEmptyMap;
17 }
18 }
19
parseCssStyle(const std::string & style)20 void CssStyleParser::parseCssStyle(const std::string& style)
21 {
22 // begin from 1 to skip first '.'for example: ".cls-1{fill:#843dd1;}"
23 auto styles = splitString(style.substr(1), "}.");
24 for (auto& style : styles) {
25 auto nameEnd = style.find_first_of('{');
26 if (nameEnd != std::string::npos) {
27 auto names = style.substr(0, nameEnd);
28 if (names.empty()) {
29 return;
30 }
31 auto splitNames = splitString(names, ",.");
32 auto attributesString = style.substr(nameEnd + 1);
33 auto attributesVector = splitString(attributesString, ";");
34 for (auto& splitName : splitNames) {
35 for (auto& attribute : attributesVector) {
36 auto arrPair = splitString(attribute, ":");
37 // 2 means stye is a kind of key: value, for example a color stype: "fill:#843dd1"
38 if (arrPair.size() == 2) {
39 auto arrMapIter = fStyleMap.find(splitName);
40 if (arrMapIter == fStyleMap.end()) {
41 std::unordered_map<std::string, std::string> arrMap;
42 arrMap.emplace(std::make_pair(arrPair[0], arrPair[1]));
43 fStyleMap.emplace(std::make_pair(splitName, arrMap));
44 } else {
45 arrMapIter->second.emplace(std::make_pair(arrPair[0], arrPair[1]));
46 }
47 }
48 }
49 }
50 }
51 }
52 }
53
splitString(const std::string & srcString,const std::string & splitString)54 std::vector<std::string> CssStyleParser::splitString(const std::string& srcString, const std::string& splitString)
55 {
56 std::string::size_type pos1;
57 std::string::size_type pos2;
58 std::vector<std::string> res;
59 pos2 = srcString.find(splitString);
60 pos1 = 0;
61 while (std::string::npos != pos2) {
62 res.push_back(srcString.substr(pos1, pos2 - pos1));
63
64 pos1 = pos2 + splitString.size();
65 pos2 = srcString.find(splitString, pos1);
66 }
67 if (pos1 != srcString.length()) {
68 res.push_back(srcString.substr(pos1));
69 }
70 return res;
71 }
72