Selectors.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. /*
  2. * This source file is part of RmlUi, the HTML/CSS Interface Middleware
  3. *
  4. * For the latest information, see http://github.com/mikke89/RmlUi
  5. *
  6. * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
  7. * Copyright (c) 2019-2023 The RmlUi Team, and contributors
  8. *
  9. * Permission is hereby granted, free of charge, to any person obtaining a copy
  10. * of this software and associated documentation files (the "Software"), to deal
  11. * in the Software without restriction, including without limitation the rights
  12. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. * copies of the Software, and to permit persons to whom the Software is
  14. * furnished to do so, subject to the following conditions:
  15. *
  16. * The above copyright notice and this permission notice shall be included in
  17. * all copies or substantial portions of the Software.
  18. *
  19. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. * THE SOFTWARE.
  26. *
  27. */
  28. #include "../Common/TestsShell.h"
  29. #include <RmlUi/Core/Context.h>
  30. #include <RmlUi/Core/Core.h>
  31. #include <RmlUi/Core/Element.h>
  32. #include <RmlUi/Core/ElementDocument.h>
  33. #include <RmlUi/Core/Types.h>
  34. #include <doctest.h>
  35. using namespace Rml;
  36. static const String doc_begin = R"(
  37. <rml>
  38. <head>
  39. <title>Demo</title>
  40. <style>
  41. body
  42. {
  43. width: 400px;
  44. height: 300px;
  45. margin: auto;
  46. font-family: LatoLatin;
  47. }
  48. )";
  49. static const String doc_end = R"(
  50. </style>
  51. </head>
  52. <body>
  53. <div id="X" class="hello"/>
  54. <span id="Y" class="world"/>
  55. <div id="Z" class="hello world"/>
  56. <div id="P" class="parent">
  57. <h1 id="A"/>
  58. Some text
  59. <p id="B" unit="m"/>
  60. <p id="C"/>
  61. <p id="D"> <span id="D0"> </span><span id="D1">Text</span> </p>
  62. <h3 id="E"/>
  63. <p id="F"> <span id="F0" class="hello-world"/> </p>
  64. <p id="G" class/>
  65. <p id="H" class="world hello"/>
  66. </div>
  67. <input id="I" type="checkbox" checked/>
  68. </body>
  69. </rml>
  70. )";
  71. enum class SelectorOp { None, RemoveElementsByIds, InsertElementBefore, RemoveClasses, RemoveId, RemoveChecked, RemoveAttributeUnit, SetHover };
  72. struct QuerySelector {
  73. QuerySelector(String selector, String expected_ids, int expect_num_warnings = 0, int expect_num_query_warnings = 0) :
  74. selector(std::move(selector)), expected_ids(std::move(expected_ids)), expect_num_warnings(expect_num_warnings),
  75. expect_num_query_warnings(expect_num_query_warnings)
  76. {}
  77. QuerySelector(String selector, String expected_ids, SelectorOp operation, String operation_argument, String expected_ids_after_operation) :
  78. selector(std::move(selector)), expected_ids(std::move(expected_ids)), operation(operation), operation_argument(std::move(operation_argument)),
  79. expected_ids_after_operation(std::move(expected_ids_after_operation))
  80. {}
  81. String selector;
  82. String expected_ids;
  83. // If this rule should fail to parse or otherwise produce warnings, set these to non-zero values.
  84. int expect_num_warnings = 0, expect_num_query_warnings = 0;
  85. // Optionally also test the selector after dynamically making a structural operation on the document.
  86. SelectorOp operation = SelectorOp::None;
  87. String operation_argument;
  88. String expected_ids_after_operation;
  89. };
  90. // clang-format off
  91. static const Vector<QuerySelector> query_selectors =
  92. {
  93. { "span", "Y D0 D1 F0" },
  94. { ".hello", "X Z H" },
  95. { ".hello.world", "Z H" },
  96. { "div.hello", "X Z" },
  97. { "body .hello", "X Z H" },
  98. { "body>.hello", "X Z" },
  99. { "body > .hello", "X Z" },
  100. { ".parent *", "A B C D D0 D1 E F F0 G H" },
  101. { ".parent > *", "A B C D E F G H" },
  102. { ":checked", "I", SelectorOp::RemoveChecked, "I", "" },
  103. { "*", "X Y Z P A B C D D0 D1 E F F0 G H I" },
  104. { "*span", "Y D0 D1 F0" },
  105. { "*.hello", "X Z H" },
  106. { "*:checked", "I" },
  107. { "p[unit='m']", "B" },
  108. { "p[unit=\"m\"]", "B" },
  109. { "[class]", "X Y Z P F0 G H" },
  110. { "[class=hello]", "X" },
  111. { "[class=]", "G" },
  112. { "[class='']", "G" },
  113. { "[class=\"\"]", "G" },
  114. { "[class~=hello]", "X Z H" },
  115. { "[class~=ello]", "" },
  116. { "[class|=hello]", "X F0" },
  117. { "[class^=hello]", "X Z F0" },
  118. { "[class^=]", "X Y Z P F0 G H" },
  119. { "[class$=hello]", "X H" },
  120. { "[class*=hello]", "X Z F0 H" },
  121. { "[class*=ello]", "X Z F0 H" },
  122. { "[class~=hello].world", "Z H" },
  123. { "*[class~=hello].world", "Z H" },
  124. { ".world[class~=hello]", "Z H" },
  125. { "[class~=hello][class~=world]", "Z H" },
  126. { "[class=hello world]", "Z" },
  127. { "[class='hello world']", "Z" },
  128. { "[class=\"hello world\"]", "Z" },
  129. { "[invalid", "", 1, 4 },
  130. { "[]", "", 1, 4 },
  131. { "[x=Rule{What}]", "", 2, 0 },
  132. { "[x=Hello,world]", "", 1, 2 },
  133. // The next ones are valid in CSS but we currently don't bother handling them, just make sure we don't crash.
  134. { "[x='Rule{What}']", "", 2, 0 },
  135. { "[x='Hello,world']", "", 1, 2 },
  136. { "#X[class=hello]", "X" },
  137. { "[class=hello]#X", "X" },
  138. { "#Y[class=hello]", "" },
  139. { "div[class=hello]", "X" },
  140. { "[class=hello]div", "X" },
  141. { "span[class=hello]", "" },
  142. { ".parent :nth-child(odd)", "A C D0 E F0 G" },
  143. { ".parent > :nth-child(even)", "B D F H", SelectorOp::RemoveClasses, "parent", "" },
  144. { ":first-child", "X A D0 F0", SelectorOp::RemoveElementsByIds, "A F0", "X B D0" },
  145. { ":last-child", "D1 F0 H I", SelectorOp::RemoveElementsByIds, "D0 H", "D1 F0 G I" },
  146. { "h1:nth-child(2)", "", SelectorOp::InsertElementBefore, "A", "A" },
  147. { "p:nth-child(2)", "B", SelectorOp::InsertElementBefore, "A", "" },
  148. { "p:nth-child(2)", "B", SelectorOp::RemoveElementsByIds, "A", "C" },
  149. { "p:nth-child(3n+1)", "D G", SelectorOp::RemoveElementsByIds, "B", "H" },
  150. { "p:nth-child(3n + 1)", "D G" },
  151. { "#P > :nth-last-child(2n+1)", "B D F H" },
  152. { "#P p:nth-of-type(odd)", "B D G" },
  153. { "span:first-child", "D0 F0" },
  154. { "body span:first-child", "D0 F0" },
  155. { "body > p span:first-child", "" },
  156. { "body > div span:first-child", "D0 F0" },
  157. { ":nth-child(4) * span:first-child", "D0 F0", SelectorOp::RemoveElementsByIds, "X", "" },
  158. { "p:nth-last-of-type(3n+1)", "D H" },
  159. { ":first-of-type", "X Y A B D0 E F0 I" },
  160. { ":last-of-type", "Y P A D1 E F0 H I" },
  161. { ":only-child", "F0", SelectorOp::RemoveElementsByIds, "D0", "D1 F0" },
  162. { ":only-of-type", "Y A E F0 I" },
  163. { "span:empty", "Y D0 F0" },
  164. { ".hello.world, #P span, #I", "Z D0 D1 F0 H I", SelectorOp::RemoveClasses, "world", "D0 D1 F0 I" },
  165. { "body * span", "D0 D1 F0" },
  166. { "D1 *", "" },
  167. { "#E + #F", "F", SelectorOp::InsertElementBefore, "F", "" },
  168. { "#E+#F", "F" },
  169. { "#E +#F", "F" },
  170. { "#E+ #F", "F" },
  171. { "#F + #E", "" },
  172. { "#A + #B", "B", SelectorOp::RemoveId, "A", "" },
  173. { "* + #A", "" },
  174. { "#H + *", "" },
  175. { "#P + *", "I" },
  176. { "div.parent > #B + p", "C" },
  177. { "div.parent > #B + div", "" },
  178. { "#B ~ #F", "F" },
  179. { "#B~#F", "F" },
  180. { "#B ~#F", "F" },
  181. { "#B~ #F", "F" },
  182. { "#F ~ #B", "" },
  183. { "div.parent > #B ~ p:empty", "C G H", SelectorOp::InsertElementBefore, "H", "C G Inserted H" },
  184. { "div.parent > #B ~ * span", "D0 D1 F0" },
  185. { ":not(*)", "" },
  186. { ":not(span)", "X Z P A B C D E F G H I" },
  187. { "#D :not(#D0)", "D1" },
  188. { "body > :not(:checked)", "X Y Z P", SelectorOp::RemoveChecked, "I", "X Y Z P I" },
  189. { "div.hello:not(.world)", "X" },
  190. { ":not(div,:nth-child(2),p *)", "A C D E F G H I" },
  191. { ".hello + .world", "Y", SelectorOp::RemoveClasses, "hello", "" },
  192. { "#B ~ h3", "E", SelectorOp::RemoveId, "B", "" },
  193. { "#Z + div > :nth-child(2)", "B", SelectorOp::RemoveId, "Z", "" },
  194. { ":hover + #P #D1", "", SelectorOp::SetHover, "Z", "D1" },
  195. { ":not(:hover) + #P #D1", "D1", SelectorOp::SetHover, "Z", "" },
  196. { "#X + #Y", "Y", SelectorOp::RemoveId, "X", "" },
  197. { "p[unit=m]", "B", SelectorOp::RemoveAttributeUnit, "B", "" },
  198. { "p[unit=m] + *", "C", SelectorOp::RemoveAttributeUnit, "B", "" },
  199. { "body > * #D0", "D0" },
  200. { "#E + * ~ *", "G H" },
  201. { "#B + * ~ #G", "G" },
  202. { "body > :nth-child(4) span:first-child", "D0 F0", SelectorOp::RemoveElementsByIds, "X", "" },
  203. };
  204. struct ClosestSelector {
  205. String start_id;
  206. String selector;
  207. String expected_id;
  208. };
  209. static const Vector<ClosestSelector> closest_selectors =
  210. {
  211. { "D1", "#P", "P" },
  212. { "D1", "#P, body", "P" },
  213. { "D1", "#P, #D", "D" },
  214. { "D1", "#Z", "" },
  215. { "D1", "#D1", "" },
  216. { "D1", "#D0", "" },
  217. { "D1", "div", "P" },
  218. { "D1", "p", "D" },
  219. { "D1", ":nth-child(4)", "D" },
  220. { "D1", "div:nth-child(4)", "P" },
  221. };
  222. struct MatchesSelector {
  223. String id;
  224. String selector;
  225. bool expected_result;
  226. };
  227. static const Vector<MatchesSelector> matches_selectors =
  228. {
  229. { "X", ".world", false },
  230. { "X", ".hello", true },
  231. { "X", ".hello, .world", true },
  232. { "E", "h3", true },
  233. { "G", "p#G[class]", true },
  234. { "G", "p#G[missing]", false },
  235. { "B", "[unit='m']", true }
  236. };
  237. struct ScopeSelector : public QuerySelector {
  238. String scope_selector;
  239. ScopeSelector(const String& scope_selector, const String& selector, const String& expected_ids) :
  240. QuerySelector(selector, expected_ids), scope_selector(scope_selector)
  241. {}
  242. };
  243. static const Vector<ScopeSelector> scope_selectors =
  244. {
  245. { "", ":scope *", "X Y Z P A B C D D0 D1 E F F0 G H I" }, // should be equivalent to just "*"
  246. { "", ":scope > *", "X Y Z P I" },
  247. { "", ":scope > *:not(:checked)", "X Y Z P" },
  248. { "#P", ":scope > p", "B C D F G H" },
  249. { "#P", ":scope span", "D0 D1 F0" },
  250. };
  251. struct ContainsSelector {
  252. String element_id;
  253. String target_id;
  254. bool expected_result;
  255. };
  256. static const Vector<ContainsSelector> contains_selectors =
  257. {
  258. { "A", "A", true },
  259. { "P", "A", true },
  260. { "A", "P", false },
  261. { "P", "D0", true },
  262. { "D0", "P", false },
  263. { "X", "P", false },
  264. { "P", "X", false },
  265. };
  266. // clang-format on
  267. // Recursively iterate through 'element' and all of its descendants to find all
  268. // elements matching a particular property used to tag matching selectors.
  269. static void GetMatchingIds(String& matching_ids, Element* element)
  270. {
  271. String id = element->GetId();
  272. if (!id.empty() && element->GetProperty<int>("drag") == (int)Style::Drag::Drag)
  273. {
  274. if (!matching_ids.empty())
  275. matching_ids += ' ';
  276. matching_ids += id;
  277. }
  278. for (int i = 0; i < element->GetNumChildren(); i++)
  279. {
  280. GetMatchingIds(matching_ids, element->GetChild(i));
  281. }
  282. }
  283. // Return the list of IDs that should match the above 'selectors.expected_ids'.
  284. static String ElementListToIds(const ElementList& elements)
  285. {
  286. String result;
  287. for (Element* element : elements)
  288. {
  289. result += element->GetId() + ' ';
  290. }
  291. if (!result.empty())
  292. result.pop_back();
  293. return result;
  294. }
  295. static void RemoveElementsWithIds(ElementDocument* document, const String& remove_ids)
  296. {
  297. StringList remove_id_list;
  298. StringUtilities::ExpandString(remove_id_list, remove_ids, ' ');
  299. for (const String& id : remove_id_list)
  300. {
  301. if (Element* element = document->GetElementById(id))
  302. element->GetParentElement()->RemoveChild(element);
  303. }
  304. }
  305. static void RemoveClassesFromAllElements(ElementDocument* document, const String& remove_classes)
  306. {
  307. StringList class_list;
  308. StringUtilities::ExpandString(class_list, remove_classes, ' ');
  309. for (const String& name : class_list)
  310. {
  311. ElementList element_list;
  312. document->GetElementsByClassName(element_list, name);
  313. for (Element* element : element_list)
  314. element->SetClass(name, false);
  315. }
  316. }
  317. static void InsertElementBefore(ElementDocument* document, const String& before_id)
  318. {
  319. Element* element = document->GetElementById(before_id);
  320. ElementPtr new_element = document->CreateElement("p");
  321. new_element->SetId("Inserted");
  322. element->GetParentElement()->InsertBefore(std::move(new_element), element);
  323. }
  324. TEST_CASE("Selectors")
  325. {
  326. Context* context = TestsShell::GetContext();
  327. SUBCASE("RCSS document selectors")
  328. {
  329. for (const QuerySelector& selector : query_selectors)
  330. {
  331. TestsShell::SetNumExpectedWarnings(selector.expect_num_warnings);
  332. const String selector_css = selector.selector + " { drag: drag; } ";
  333. const String document_string = doc_begin + selector_css + doc_end;
  334. ElementDocument* document = context->LoadDocumentFromMemory(document_string);
  335. // Update the context to settle any dirty state.
  336. context->Update();
  337. String matching_ids;
  338. GetMatchingIds(matching_ids, document);
  339. CHECK_MESSAGE(matching_ids == selector.expected_ids, "Selector: " << selector.selector);
  340. // Also check validity of selectors after structural document changes.
  341. if (selector.operation != SelectorOp::None)
  342. {
  343. String operation_str;
  344. switch (selector.operation)
  345. {
  346. case SelectorOp::RemoveElementsByIds:
  347. RemoveElementsWithIds(document, selector.operation_argument);
  348. operation_str = "RemoveElementsByIds";
  349. break;
  350. case SelectorOp::InsertElementBefore:
  351. InsertElementBefore(document, selector.operation_argument);
  352. operation_str = "InsertElementBefore";
  353. break;
  354. case SelectorOp::RemoveClasses:
  355. RemoveClassesFromAllElements(document, selector.operation_argument);
  356. operation_str = "RemoveClasses";
  357. break;
  358. case SelectorOp::RemoveChecked:
  359. document->GetElementById(selector.operation_argument)->RemoveAttribute("checked");
  360. operation_str = "RemoveChecked";
  361. break;
  362. case SelectorOp::RemoveId:
  363. document->GetElementById(selector.operation_argument)->SetId("");
  364. operation_str = "RemoveId";
  365. break;
  366. case SelectorOp::RemoveAttributeUnit:
  367. document->GetElementById(selector.operation_argument)->RemoveAttribute("unit");
  368. operation_str = "RemoveAttributeUnit";
  369. break;
  370. case SelectorOp::SetHover:
  371. document->GetElementById(selector.operation_argument)->SetPseudoClass("hover", true);
  372. operation_str = "SetHover";
  373. break;
  374. case SelectorOp::None: break;
  375. }
  376. context->Update();
  377. String matching_ids_after_operation;
  378. GetMatchingIds(matching_ids_after_operation, document);
  379. CHECK_MESSAGE(matching_ids_after_operation == selector.expected_ids_after_operation, "Selector: ", selector.selector,
  380. " Operation: ", operation_str, " Argument: ", selector.operation_argument);
  381. }
  382. context->UnloadDocument(document);
  383. }
  384. }
  385. SUBCASE("QuerySelector(All)")
  386. {
  387. const String document_string = doc_begin + doc_end;
  388. ElementDocument* document = context->LoadDocumentFromMemory(document_string);
  389. REQUIRE(document);
  390. for (const QuerySelector& selector : query_selectors)
  391. {
  392. TestsShell::SetNumExpectedWarnings(selector.expect_num_query_warnings);
  393. ElementList elements;
  394. document->QuerySelectorAll(elements, selector.selector);
  395. String matching_ids = ElementListToIds(elements);
  396. Element* first_element = document->QuerySelector(selector.selector);
  397. if (first_element)
  398. {
  399. CHECK_MESSAGE(first_element == elements[0], "QuerySelector does not return the first match of QuerySelectorAll.");
  400. }
  401. else
  402. {
  403. CHECK_MESSAGE(elements.empty(), "QuerySelector found nothing, while QuerySelectorAll found " << elements.size() << " element(s).");
  404. }
  405. CHECK_MESSAGE(matching_ids == selector.expected_ids, "QuerySelector: " << selector.selector);
  406. }
  407. context->UnloadDocument(document);
  408. }
  409. SUBCASE("Closest")
  410. {
  411. const String document_string = doc_begin + doc_end;
  412. ElementDocument* document = context->LoadDocumentFromMemory(document_string);
  413. REQUIRE(document);
  414. for (const ClosestSelector& selector : closest_selectors)
  415. {
  416. Element* start = document->GetElementById(selector.start_id);
  417. REQUIRE(start);
  418. Element* match = start->Closest(selector.selector);
  419. const String match_id = match ? match->GetId() : "";
  420. CHECK_MESSAGE(match_id == selector.expected_id, "Closest() selector '" << selector.selector << "' from " << selector.start_id);
  421. }
  422. context->UnloadDocument(document);
  423. }
  424. SUBCASE("Matches")
  425. {
  426. const String document_string = doc_begin + doc_end;
  427. ElementDocument* document = context->LoadDocumentFromMemory(document_string);
  428. REQUIRE(document);
  429. for (const MatchesSelector& selector : matches_selectors)
  430. {
  431. Element* start = document->GetElementById(selector.id);
  432. REQUIRE(start);
  433. bool matches = start->Matches(selector.selector);
  434. CHECK_MESSAGE(matches == selector.expected_result, "Matches() selector '" << selector.selector << "' from " << selector.id);
  435. }
  436. context->UnloadDocument(document);
  437. }
  438. SUBCASE("Scope")
  439. {
  440. const String document_string = doc_begin + doc_end;
  441. ElementDocument* document = context->LoadDocumentFromMemory(document_string);
  442. REQUIRE(document);
  443. for (const ScopeSelector& selector : scope_selectors)
  444. {
  445. Element* start = (selector.scope_selector.empty() ? document : document->QuerySelector(selector.scope_selector));
  446. REQUIRE(start);
  447. ElementList elements;
  448. start->QuerySelectorAll(elements, selector.selector);
  449. String matching_ids = ElementListToIds(elements);
  450. Element* first_element = start->QuerySelector(selector.selector);
  451. if (first_element)
  452. {
  453. CHECK_MESSAGE(first_element == elements[0], "QuerySelector does not return the first match of QuerySelectorAll.");
  454. }
  455. else
  456. {
  457. CHECK_MESSAGE(elements.empty(), "QuerySelector found nothing, while QuerySelectorAll found " << elements.size() << " element(s).");
  458. }
  459. CHECK_MESSAGE(matching_ids == selector.expected_ids, "QuerySelector: " << selector.selector);
  460. }
  461. context->UnloadDocument(document);
  462. }
  463. SUBCASE("Contains")
  464. {
  465. const String document_string = doc_begin + doc_end;
  466. ElementDocument* document = context->LoadDocumentFromMemory(document_string);
  467. REQUIRE(document);
  468. for (const ContainsSelector& selector : contains_selectors)
  469. {
  470. Element* element = document->GetElementById(selector.element_id);
  471. Element* target = document->GetElementById(selector.target_id);
  472. REQUIRE(element);
  473. REQUIRE(target);
  474. CHECK_MESSAGE(element->Contains(target) == selector.expected_result,
  475. "'" << selector.element_id << "' contains '" << selector.target_id << "'");
  476. }
  477. context->UnloadDocument(document);
  478. }
  479. TestsShell::ShutdownShell();
  480. }