MarkupNode.vala 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  1. using Xml;
  2. using Html;
  3. using Invercargill;
  4. using Invercargill.DataStructures;
  5. namespace Astralis {
  6. /// <summary>
  7. /// Represents an HTML element node in the DOM with convenient manipulation methods
  8. /// </summary>
  9. public class MarkupNode : GLib.Object {
  10. private Xml.Node* xml_node;
  11. private MarkupDocument document;
  12. internal MarkupNode(MarkupDocument doc, Xml.Node* node) {
  13. this.document = doc;
  14. this.xml_node = node;
  15. }
  16. /// <summary>
  17. /// The tag name of the element (e.g., "div", "span", "p")
  18. /// </summary>
  19. public string tag_name {
  20. owned get { return xml_node->name; }
  21. }
  22. /// <summary>
  23. /// The text content of this element and its children
  24. /// </summary>
  25. public string text_content {
  26. owned get { return xml_node->get_content() ?? ""; }
  27. set { xml_node->set_content(value); }
  28. }
  29. /// <summary>
  30. /// Gets an attribute value by name
  31. /// </summary>
  32. public string? get_attribute(string name) {
  33. return xml_node->get_prop(name);
  34. }
  35. /// <summary>
  36. /// Sets an attribute value
  37. /// </summary>
  38. public void set_attribute(string name, string value) {
  39. xml_node->set_prop(name, value);
  40. }
  41. /// <summary>
  42. /// Removes an attribute by name
  43. /// </summary>
  44. public void remove_attribute(string name) {
  45. xml_node->unset_prop(name);
  46. }
  47. /// <summary>
  48. /// Gets the id attribute of this element
  49. /// </summary>
  50. public string? id {
  51. owned get { return get_attribute("id"); }
  52. set {
  53. if (value != null) {
  54. set_attribute("id", value);
  55. } else {
  56. remove_attribute("id");
  57. }
  58. }
  59. }
  60. /// <summary>
  61. /// Gets the class attribute as a string
  62. /// </summary>
  63. public string? class_string {
  64. owned get { return get_attribute("class"); }
  65. set {
  66. if (value != null) {
  67. set_attribute("class", value);
  68. } else {
  69. remove_attribute("class");
  70. }
  71. }
  72. }
  73. /// <summary>
  74. /// Gets a list of CSS classes applied to this element
  75. /// </summary>
  76. public string[] classes {
  77. owned get {
  78. var class_attr = get_attribute("class");
  79. if (class_attr == null || class_attr.strip() == "") {
  80. return new string[0];
  81. }
  82. return class_attr.split_set(" \t\n\r");
  83. }
  84. }
  85. /// <summary>
  86. /// Checks if this element has a specific CSS class
  87. /// </summary>
  88. public bool has_class(string class_name) {
  89. foreach (unowned var cls in classes) {
  90. if (cls == class_name) {
  91. return true;
  92. }
  93. }
  94. return false;
  95. }
  96. /// <summary>
  97. /// Adds a CSS class to this element
  98. /// </summary>
  99. public void add_class(string class_name) {
  100. if (has_class(class_name)) {
  101. return;
  102. }
  103. var current_classes = classes;
  104. var new_classes = new string[current_classes.length + 1];
  105. for (int i = 0; i < current_classes.length; i++) {
  106. new_classes[i] = current_classes[i];
  107. }
  108. new_classes[current_classes.length] = class_name;
  109. set_attribute("class", string.joinv(" ", new_classes));
  110. }
  111. /// <summary>
  112. /// Removes a CSS class from this element
  113. /// </summary>
  114. public void remove_class(string class_name) {
  115. var current_classes = classes;
  116. var new_list = new StringBuilder();
  117. bool first = true;
  118. bool found = false;
  119. foreach (unowned var cls in current_classes) {
  120. if (cls == class_name) {
  121. found = true;
  122. continue;
  123. }
  124. if (!first) {
  125. new_list.append(" ");
  126. }
  127. new_list.append(cls);
  128. first = false;
  129. }
  130. if (found) {
  131. if (new_list.len > 0) {
  132. set_attribute("class", new_list.str);
  133. } else {
  134. remove_attribute("class");
  135. }
  136. }
  137. }
  138. /// <summary>
  139. /// Toggles a CSS class on this element
  140. /// </summary>
  141. public void toggle_class(string class_name) {
  142. if (has_class(class_name)) {
  143. remove_class(class_name);
  144. } else {
  145. add_class(class_name);
  146. }
  147. }
  148. /// <summary>
  149. /// Replaces all classes with a new set of classes
  150. /// </summary>
  151. public void set_classes(string[] new_classes) {
  152. set_attribute("class", string.joinv(" ", new_classes));
  153. }
  154. /// <summary>
  155. /// Gets the parent element, or null if this is the root
  156. /// </summary>
  157. public MarkupNode? parent {
  158. owned get {
  159. var parent_node = xml_node->parent;
  160. if (parent_node == null || parent_node->type == ElementType.DOCUMENT_NODE) {
  161. return null;
  162. }
  163. return new MarkupNode(document, parent_node);
  164. }
  165. }
  166. /// <summary>
  167. /// Gets the first child element of this node
  168. /// </summary>
  169. public MarkupNode? first_element_child {
  170. owned get {
  171. var child = xml_node->first_element_child();
  172. return child != null ? new MarkupNode(document, child) : null;
  173. }
  174. }
  175. /// <summary>
  176. /// Gets the last child element of this node
  177. /// </summary>
  178. public MarkupNode? last_element_child {
  179. owned get {
  180. var child = xml_node->last_element_child();
  181. return child != null ? new MarkupNode(document, child) : null;
  182. }
  183. }
  184. /// <summary>
  185. /// Gets the next sibling element
  186. /// </summary>
  187. public MarkupNode? next_element_sibling {
  188. owned get {
  189. var sibling = xml_node->next_element_sibling();
  190. return sibling != null ? new MarkupNode(document, sibling) : null;
  191. }
  192. }
  193. /// <summary>
  194. /// Gets the previous sibling element
  195. /// </summary>
  196. public MarkupNode? previous_element_sibling {
  197. owned get {
  198. var sibling = xml_node->previous_element_sibling();
  199. return sibling != null ? new MarkupNode(document, sibling) : null;
  200. }
  201. }
  202. /// <summary>
  203. /// Gets all child elements of this node
  204. /// </summary>
  205. public MarkupNodeList children {
  206. owned get {
  207. var list = new MarkupNodeList(document);
  208. for (var child = xml_node->children; child != null; child = child->next) {
  209. if (child->type == ElementType.ELEMENT_NODE) {
  210. list.add_node(child);
  211. }
  212. }
  213. return list;
  214. }
  215. }
  216. /// <summary>
  217. /// Appends a new child element with the given tag name
  218. /// </summary>
  219. public MarkupNode append_child_element(string tag_name) {
  220. var new_node = xml_node->new_child(null, tag_name);
  221. return new MarkupNode(document, new_node);
  222. }
  223. /// <summary>
  224. /// Appends a text node to this element
  225. /// </summary>
  226. public void append_text(string text) {
  227. xml_node->add_content(text);
  228. }
  229. /// <summary>
  230. /// Creates and appends a child element with text content
  231. /// </summary>
  232. public MarkupNode append_child_with_text(string tag_name, string text) {
  233. var new_node = xml_node->new_text_child(null, tag_name, text);
  234. return new MarkupNode(document, new_node);
  235. }
  236. /// <summary>
  237. /// Removes this element from the DOM
  238. /// </summary>
  239. public void remove() {
  240. xml_node->unlink();
  241. delete xml_node;
  242. }
  243. /// <summary>
  244. /// Removes all children from this element
  245. /// </summary>
  246. public void clear_children() {
  247. while (xml_node->children != null) {
  248. var child = xml_node->children;
  249. child->unlink();
  250. delete child;
  251. }
  252. }
  253. /// <summary>
  254. /// Replaces this element with new content
  255. /// </summary>
  256. public void replace_with_html(string html) {
  257. // Parse the HTML fragment using HTML parser
  258. int options = (int)(Html.ParserOption.RECOVER |
  259. Html.ParserOption.NOERROR |
  260. Html.ParserOption.NOWARNING |
  261. Html.ParserOption.NOBLANKS |
  262. Html.ParserOption.NONET);
  263. string wrapped = "<div>" + html + "</div>";
  264. char[] buffer = wrapped.to_utf8();
  265. var temp_doc = Html.Doc.read_memory(buffer, buffer.length, "", null, options);
  266. if (temp_doc == null) {
  267. return;
  268. }
  269. var temp_root = temp_doc->get_root_element();
  270. if (temp_root == null) {
  271. delete temp_doc;
  272. return;
  273. }
  274. // Import and insert children before this node
  275. var parent = xml_node->parent;
  276. if (parent != null) {
  277. for (var child = temp_root->children; child != null; child = child->next) {
  278. var imported = doc.import_node(child, true);
  279. parent->add_prev_sibling(imported);
  280. parent = imported; // Move insertion point
  281. }
  282. }
  283. // Remove this node
  284. remove();
  285. delete temp_doc;
  286. }
  287. /// <summary>
  288. /// Sets the inner HTML of this element
  289. /// </summary>
  290. public string inner_html {
  291. owned set {
  292. clear_children();
  293. if (value == null || value == "") {
  294. return;
  295. }
  296. // Parse the HTML fragment using HTML parser
  297. int options = (int)(Html.ParserOption.RECOVER |
  298. Html.ParserOption.NOERROR |
  299. Html.ParserOption.NOWARNING |
  300. Html.ParserOption.NOBLANKS |
  301. Html.ParserOption.NONET);
  302. string wrapped = "<div>" + value + "</div>";
  303. char[] buffer = wrapped.to_utf8();
  304. var temp_doc = Html.Doc.read_memory(buffer, buffer.length, "", null, options);
  305. if (temp_doc == null) {
  306. return;
  307. }
  308. var temp_root = temp_doc->get_root_element();
  309. if (temp_root == null) {
  310. delete temp_doc;
  311. return;
  312. }
  313. // Import children
  314. for (var child = temp_root->children; child != null; child = child->next) {
  315. var imported = doc.import_node(child, true);
  316. xml_node->add_child(imported);
  317. }
  318. delete temp_doc;
  319. }
  320. owned get {
  321. // Use Html.Doc to serialize the children properly
  322. var temp_doc = new Html.Doc();
  323. Xml.Node* wrapper = temp_doc.new_node(null, "div");
  324. temp_doc.set_root_element(wrapper);
  325. // Copy children to the wrapper
  326. for (var child = xml_node->children; child != null; child = child->next) {
  327. var copied = child->copy(1);
  328. wrapper->add_child(copied);
  329. }
  330. // Serialize using HTML serializer
  331. string buffer;
  332. int len;
  333. temp_doc.dump_memory(out buffer, out len);
  334. // Extract just the inner content (between <div> and </div>)
  335. // The HTML serializer outputs proper HTML without XML declaration
  336. string result = buffer ?? "";
  337. // Strip the wrapper div tags
  338. if (result.has_prefix("<div>")) {
  339. result = result.substring(5);
  340. }
  341. if (result.has_suffix("</div>")) {
  342. result = result.substring(0, result.length - 6);
  343. }
  344. return result;
  345. }
  346. }
  347. /// <summary>
  348. /// Gets the outer HTML of this element (including the element itself)
  349. /// </summary>
  350. public string outer_html {
  351. owned get {
  352. // Create a temporary HTML document to serialize this node
  353. var temp_doc = new Html.Doc();
  354. temp_doc.set_root_element(xml_node->copy(1));
  355. string buffer;
  356. int len;
  357. temp_doc.dump_memory(out buffer, out len);
  358. return buffer ?? "";
  359. }
  360. }
  361. /// <summary>
  362. /// Creates an HttpResult from this node's outer HTML.
  363. /// Useful for returning HTML fragments to HTMX requests.
  364. /// </summary>
  365. /// <param name="status">HTTP status code (defaults to OK)</param>
  366. /// <returns>An HttpResult containing the node's HTML with Content-Type text/html</returns>
  367. public HttpResult to_result(StatusCode status = StatusCode.OK) {
  368. return new HttpStringResult(outer_html, status)
  369. .set_header("Content-Type", "text/html; charset=UTF-8");
  370. }
  371. internal MarkupDocument doc {
  372. get { return document; }
  373. }
  374. internal Xml.Node* native {
  375. get { return xml_node; }
  376. }
  377. }
  378. /// <summary>
  379. /// A list of HTML nodes supporting iteration and manipulation
  380. /// </summary>
  381. public class MarkupNodeList : Invercargill.Enumerable<MarkupNode> {
  382. private MarkupDocument document;
  383. private List<Xml.Node*> nodes;
  384. internal MarkupNodeList(MarkupDocument doc) {
  385. this.document = doc;
  386. this.nodes = new List<Xml.Node*>();
  387. }
  388. internal void add_node(Xml.Node* node) {
  389. nodes.append(node);
  390. }
  391. /// <summary>
  392. /// Number of nodes in the list
  393. /// </summary>
  394. public int length {
  395. get { return (int)nodes.length(); }
  396. }
  397. /// <summary>
  398. /// Gets a node at the specified index
  399. /// </summary>
  400. public new MarkupNode? get(int index) {
  401. unowned List<Xml.Node*> item = nodes.nth((uint)index);
  402. if (item == null) {
  403. return null;
  404. }
  405. return new MarkupNode(document, item.data);
  406. }
  407. /// <summary>
  408. /// Gets the first node, or null if empty
  409. /// </summary>
  410. public new MarkupNode? first {
  411. owned get {
  412. if (nodes.is_empty()) {
  413. return null;
  414. }
  415. unowned List<Xml.Node*> item = nodes.first();
  416. return item != null ? new MarkupNode(document, item.data) : null;
  417. }
  418. }
  419. /// <summary>
  420. /// Gets the last node, or null if empty
  421. /// </summary>
  422. public new MarkupNode? last {
  423. owned get {
  424. if (nodes.is_empty()) {
  425. return null;
  426. }
  427. unowned List<Xml.Node*> item = nodes.last();
  428. return item != null ? new MarkupNode(document, item.data) : null;
  429. }
  430. }
  431. /// <summary>
  432. /// Sets a property on all nodes in the list
  433. /// </summary>
  434. public void set_attribute_all(string name, string value) {
  435. foreach (var node in nodes) {
  436. node->set_prop(name, value);
  437. }
  438. }
  439. /// <summary>
  440. /// Adds a class to all nodes in the list
  441. /// </summary>
  442. public void add_class_all(string class_name) {
  443. foreach (var node in nodes) {
  444. var wrapper = new MarkupNode(document, node);
  445. wrapper.add_class(class_name);
  446. }
  447. }
  448. /// <summary>
  449. /// Removes a class from all nodes in the list
  450. /// </summary>
  451. public void remove_class_all(string class_name) {
  452. foreach (var node in nodes) {
  453. var wrapper = new MarkupNode(document, node);
  454. wrapper.remove_class(class_name);
  455. }
  456. }
  457. /// <summary>
  458. /// Sets text content on all nodes in the list
  459. /// </summary>
  460. public void set_text_all(string text) {
  461. foreach (var node in nodes) {
  462. node->set_content(text);
  463. }
  464. }
  465. /// <summary>
  466. /// Removes all nodes in the list from the DOM
  467. /// </summary>
  468. public void remove_all() {
  469. foreach (var node in nodes) {
  470. node->unlink();
  471. delete node;
  472. }
  473. nodes = new List<Xml.Node*>();
  474. }
  475. /// <summary>
  476. /// Gets information about this enumerable
  477. /// </summary>
  478. public override Invercargill.EnumerableInfo get_info() {
  479. return new Invercargill.EnumerableInfo.infer_ultimate(this, Invercargill.EnumerableCategory.IN_MEMORY);
  480. }
  481. /// <summary>
  482. /// Gets a tracker for iterating over the nodes
  483. /// </summary>
  484. public override Invercargill.Tracker<MarkupNode> get_tracker() {
  485. return new NodeTracker(document, nodes);
  486. }
  487. /// <summary>
  488. /// Peeks at the count without full enumeration
  489. /// </summary>
  490. public override uint? peek_count() {
  491. return (uint)nodes.length();
  492. }
  493. /// <summary>
  494. /// Tracker for iterating over MarkupNodeList
  495. /// </summary>
  496. private class NodeTracker : Invercargill.Tracker<MarkupNode> {
  497. private MarkupDocument document;
  498. private unowned List<Xml.Node*> nodes;
  499. private unowned List<Xml.Node*>? current;
  500. internal NodeTracker(MarkupDocument doc, List<Xml.Node*> nodes) {
  501. this.document = doc;
  502. this.nodes = nodes;
  503. this.current = null;
  504. }
  505. public override MarkupNode get_next() {
  506. if (current == null) {
  507. current = nodes.first();
  508. } else {
  509. current = current.next;
  510. }
  511. // has_next() should be called before get_next()
  512. // Returning null here would violate the non-nullable contract
  513. assert(current != null);
  514. return new MarkupNode(document, current.data);
  515. }
  516. public override bool has_next() {
  517. if (current == null) {
  518. return !nodes.is_empty();
  519. }
  520. return current.next != null;
  521. }
  522. }
  523. }
  524. }