1 /*
2 * Copyright (c) Huawei Technologies Co., Ltd. 2020-2020. 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 '.'
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 if (arrPair.size() == 2) {
38 auto arrMapIter = fStyleMap.find(splitName);
39 if (arrMapIter == fStyleMap.end()) {
40 std::unordered_map<std::string, std::string> arrMap;
41 arrMap.emplace(std::make_pair(arrPair[0], arrPair[1]));
42 fStyleMap.emplace(std::make_pair(splitName, arrMap));
43 } else {
44 arrMapIter->second.emplace(std::make_pair(arrPair[0], arrPair[1]));
45 }
46 }
47 }
48 }
49 }
50 }
51 }
52
splitString(const std::string & srcString,const std::string & splitString)53 std::vector<std::string> CssStyleParser::splitString(const std::string& srcString, const std::string& splitString)
54 {
55 std::string::size_type pos1;
56 std::string::size_type pos2;
57 std::vector<std::string> res;
58 pos2 = srcString.find(splitString);
59 pos1 = 0;
60 while (std::string::npos != pos2) {
61 res.push_back(srcString.substr(pos1, pos2 - pos1));
62
63 pos1 = pos2 + splitString.size();
64 pos2 = srcString.find(splitString, pos1);
65 }
66 if (pos1 != srcString.length()) {
67 res.push_back(srcString.substr(pos1));
68 }
69 return res;
70 }