Nim: DOMの要素をsortするスクリプト例
nimでDOMを扱うスクリプトを簡単に作ってみました。
割りとさらっと作れるので助かります。
- listは
名前(数)
という中身があるのが前提 - class名はは適当についている前提 (nikolaの出力です)
code::
proc sort_by_tags_controls(fns: openarray[proc(ev: Event)]): Element = result = document.createElement("div") for n, i in ["articles", "alphabetical", "descend/ascend"]: let elm = document.createElement("div") elm.innerHTML = i elm.setAttribute("class", "tags-sort-button") elm.addEventListener("click", fns[n]) result.appendChild(elm) result.setAttribute("class", "tags-sort-buttons") proc sort_by_tags_extract(): seq[Element] = result = @[] for i in query_all_from_root(".postlist li"): result.add(i) proc sort_by_tags_cmp1(a, b: Element): int = let at = a.innerText let bt = b.innerText return system.cmp(at, bt) proc sort_by_tags_cmp2(a, b: Element): int = proc number(s: string): int = let s1 = s.split("(") if len(s1) < 2: return 0 let s2 = s1[1].split(")") if len(s2) < 2: return 0 return parseInt(s2[0]) let an = number($a.innerText) let bn = number($b.innerText) return system.cmp(an, bn) proc sort_by_tags(): void = var (f_term, f_ascd) = (true, false) proc sort_core(): void = var items = sort_by_tags_extract() items.sort(if f_term: sort_by_tags_cmp1 else: sort_by_tags_cmp2, order = if f_ascd: SortOrder.Ascending else: SortOrder.Descending) let par = query_from_root(".postlist") let par2 = par.cloneNode(false) let root = par.parentNode root.removeChild(par) for i in items: par2.appendChild(i) root.appendChild(par2) proc sort_term(ev: Event): void = f_term = not f_term sort_core() proc sort_order(ev: Event): void = f_ascd = not f_ascd sort_core() let par = query_from_root(".postlist") if isNil(par): return let ctrls = sort_by_tags_controls([sort_term, sort_term, sort_order]) par.parentNode.insertBefore(ctrls, par)
markup::
<ul class="postlist"> <li><a class="reference listtitle" href="3dprint/">3Dprint(3)</a></li> <li><a class="reference listtitle" href="account/">account(1)</a></li> <li><a class="reference listtitle" href="android/">android(15)</a></li> <li><a class="reference listtitle" href="arcade/">arcade(16)</a></li> <li><a class="reference listtitle" href="armbian/">armbian(3)</a></li> <li><a class="reference listtitle" href="az/">AZ(3)</a></li> <li><a class="reference listtitle" href="bb10/">BB10(1)</a></li> </ul>
コメント
Comments powered by Disqus