render.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. package main
  2. import (
  3. "bytes"
  4. "crypto/sha1"
  5. "encoding/hex"
  6. "fmt"
  7. "html/template"
  8. "io/fs"
  9. "os"
  10. "path"
  11. "path/filepath"
  12. "sort"
  13. "strings"
  14. "time"
  15. )
  16. const repoURL = "https://github.com/tobychui/arozos"
  17. // siteModel holds everything the pages are drawn from.
  18. type siteModel struct {
  19. Version string
  20. API *API
  21. Guides []*Guide
  22. Refs []*RefPage
  23. Samples []*Sample
  24. Icons map[string]template.HTML
  25. Year int
  26. md *markdown
  27. syms map[string]string
  28. assetVer string
  29. tpl *template.Template
  30. }
  31. // libIcons picks an icon of the website's set for each library card.
  32. var libIcons = map[string]string{
  33. "core": "terminal", "db": "database", "user": "users", "filelib": "folder",
  34. "imagelib": "image", "http": "globe", "share": "share", "appdata": "box",
  35. "sysinfo": "gauge", "ziplib": "layers", "sqlite": "database", "llm": "sparkles",
  36. "cnn": "eye", "office": "doc", "ffmpeg": "film", "websocket": "plug",
  37. "scheduler": "clock", "sharedspace": "users", "meetroom": "video",
  38. "notification": "send", "audio": "bell", "git": "git", "email": "mail", "cluster": "server",
  39. }
  40. // builtinRefs are drawn under "Built-in functions" instead of "Libraries".
  41. var builtinRefs = map[string]bool{"core": true, "db": true, "user": true}
  42. // ---------- page models ----------
  43. type navItem struct {
  44. Title string
  45. URL string // from the docs root
  46. Key string
  47. Sub string // small text after the title
  48. Icon string
  49. }
  50. type navGroup struct {
  51. Title string
  52. Items []navItem
  53. }
  54. type tocItem struct {
  55. Level int
  56. ID string
  57. Title string
  58. Code bool
  59. }
  60. type headingView struct {
  61. Level int
  62. ID string
  63. Aliases []string
  64. HTML template.HTML
  65. }
  66. type sigView struct {
  67. Name string
  68. Args string
  69. Also []string
  70. Ret string
  71. Desc string
  72. }
  73. type fnView struct {
  74. Level int
  75. ID string
  76. Aliases []string
  77. Sigs []sigView
  78. Badges []string
  79. Body template.HTML
  80. Examples []string
  81. Missing bool // documented here but not in api.json
  82. }
  83. type itemView struct {
  84. Heading *headingView
  85. Body template.HTML
  86. Fn *fnView
  87. }
  88. type indexRow struct {
  89. Name, Ret, Desc, Anchor string
  90. }
  91. type guideView struct {
  92. Guide *Guide
  93. Intro template.HTML
  94. Items []itemView
  95. }
  96. type refView struct {
  97. Page *RefPage
  98. Intro template.HTML
  99. Index []indexRow
  100. Items []itemView
  101. Builtin bool
  102. Play string // how the playground serves it: "runs", or the tool window that answers
  103. }
  104. type libCard struct {
  105. Title, URL, Desc, Icon string
  106. Count int
  107. Builtin bool
  108. }
  109. type homeView struct {
  110. Builtins []libCard
  111. Libraries []libCard
  112. FnCount int
  113. Samples int
  114. Start []navItem
  115. }
  116. type page struct {
  117. Kind string // home, guide, ref, playground
  118. Key string
  119. Title string
  120. Desc string
  121. Root string
  122. Site *siteModel
  123. Nav []navGroup
  124. TOC []tocItem
  125. Prev *navItem
  126. Next *navItem
  127. Edit string // the source file on GitHub
  128. Home *homeView
  129. Guide *guideView
  130. Ref *refView
  131. }
  132. // ---------- rendering ----------
  133. func (s *siteModel) render(out string, rep *report) error {
  134. s.md = newMarkdown()
  135. s.Year = time.Now().Year()
  136. s.buildSymbols()
  137. if err := s.copyStatic(out); err != nil {
  138. return err
  139. }
  140. if err := s.parseTemplates(); err != nil {
  141. return err
  142. }
  143. nav := s.nav()
  144. order := flatten(nav)
  145. write := func(p *page, file string) error {
  146. p.Site = s
  147. p.Nav = nav
  148. if p.Kind == "guide" || p.Kind == "ref" {
  149. for i, it := range order {
  150. if it.Key == p.Key {
  151. if i > 0 {
  152. prev := order[i-1]
  153. p.Prev = &prev
  154. }
  155. if i < len(order)-1 {
  156. next := order[i+1]
  157. p.Next = &next
  158. }
  159. }
  160. }
  161. }
  162. var buf bytes.Buffer
  163. if err := s.tpl.ExecuteTemplate(&buf, "layout", p); err != nil {
  164. return fmt.Errorf("%s: %w", file, err)
  165. }
  166. return writeFile(filepath.Join(out, filepath.FromSlash(file)), buf.Bytes())
  167. }
  168. if err := write(s.homePage(), "index.html"); err != nil {
  169. return err
  170. }
  171. for _, g := range s.Guides {
  172. p, err := s.guidePage(g)
  173. if err != nil {
  174. return fmt.Errorf("pages/%s.md: %w", g.Slug, err)
  175. }
  176. if err := write(p, g.Slug+".html"); err != nil {
  177. return err
  178. }
  179. }
  180. for _, r := range s.Refs {
  181. p, err := s.refPage(r)
  182. if err != nil {
  183. return fmt.Errorf("reference/%s.md: %w", r.ID, err)
  184. }
  185. if err := write(p, "reference/"+r.ID+".html"); err != nil {
  186. return err
  187. }
  188. }
  189. if err := write(&page{Kind: "playground", Key: "playground", Title: "Playground", Desc: "Run AGI scripts in your browser against a virtual file system and mocked services."}, "playground.html"); err != nil {
  190. return err
  191. }
  192. if err := writeJSON(filepath.Join(out, "search.json"), s.searchIndex()); err != nil {
  193. return err
  194. }
  195. if err := writeJSON(filepath.Join(out, "playground", "catalog.json"), s.catalog()); err != nil {
  196. return err
  197. }
  198. return writeJSON(filepath.Join(out, "playground", "samples.json"), s.Samples)
  199. }
  200. // buildSymbols maps every function name and library id to the URL of its
  201. // documentation, for linking `code` in the prose.
  202. func (s *siteModel) buildSymbols() {
  203. s.syms = map[string]string{}
  204. for _, r := range s.Refs {
  205. url := "reference/" + r.ID + ".html"
  206. if r.Load != "" {
  207. s.syms[r.ID] = url
  208. }
  209. for _, f := range r.AllFunctions() {
  210. for _, n := range f.Names {
  211. if _, taken := s.syms[n]; !taken {
  212. s.syms[n] = url + "#" + f.Anchor
  213. }
  214. }
  215. }
  216. }
  217. }
  218. func (s *siteModel) nav() []navGroup {
  219. var groups []navGroup
  220. for _, g := range s.Guides {
  221. if len(groups) == 0 || groups[len(groups)-1].Title != g.Group {
  222. groups = append(groups, navGroup{Title: g.Group})
  223. }
  224. last := &groups[len(groups)-1]
  225. last.Items = append(last.Items, navItem{Title: g.Title, URL: g.Slug + ".html", Key: "guide:" + g.Slug})
  226. }
  227. builtin := navGroup{Title: "Built-in functions"}
  228. libs := navGroup{Title: "Libraries"}
  229. for _, r := range s.Refs {
  230. it := navItem{Title: r.Title, URL: "reference/" + r.ID + ".html", Key: "ref:" + r.ID, Icon: libIcons[r.ID]}
  231. if builtinRefs[r.ID] {
  232. builtin.Items = append(builtin.Items, it)
  233. } else {
  234. libs.Items = append(libs.Items, it)
  235. }
  236. }
  237. return append(groups, builtin, libs)
  238. }
  239. func flatten(groups []navGroup) []navItem {
  240. var out []navItem
  241. for _, g := range groups {
  242. out = append(out, g.Items...)
  243. }
  244. return out
  245. }
  246. func (s *siteModel) homePage() *page {
  247. h := &homeView{Samples: len(s.Samples)}
  248. for _, r := range s.Refs {
  249. n := len(r.AllFunctions())
  250. h.FnCount += n
  251. c := libCard{Title: r.Title, URL: "reference/" + r.ID + ".html", Desc: r.Desc, Icon: libIcons[r.ID], Count: n, Builtin: builtinRefs[r.ID]}
  252. if c.Icon == "" {
  253. c.Icon = "puzzle"
  254. }
  255. if c.Builtin {
  256. h.Builtins = append(h.Builtins, c)
  257. } else {
  258. h.Libraries = append(h.Libraries, c)
  259. }
  260. }
  261. for _, g := range s.Guides {
  262. if g.Group == "Getting started" {
  263. h.Start = append(h.Start, navItem{Title: g.Title, URL: g.Slug + ".html", Sub: g.Summary})
  264. }
  265. }
  266. return &page{Kind: "home", Key: "home", Title: "AGI Developer Documentation", Desc: "Reference, guides and a browser playground for AGI, the server-side JavaScript runtime of ArozOS WebApps.", Home: h}
  267. }
  268. func (s *siteModel) guidePage(g *Guide) (*page, error) {
  269. rc := &renderCtx{Root: "", Syms: s.syms}
  270. body := strings.ReplaceAll(g.Body, "{{agiVersion}}", s.Version)
  271. intro, blocks := splitBlocks(body)
  272. v := &guideView{Guide: g}
  273. var err error
  274. if v.Intro, err = s.md.render(intro, rc); err != nil {
  275. return nil, err
  276. }
  277. ids := idSet{}
  278. var toc []tocItem
  279. for _, b := range blocks {
  280. hv, err := s.heading(b, rc, ids)
  281. if err != nil {
  282. return nil, err
  283. }
  284. bodyHTML, err := s.md.render(b.Body, rc)
  285. if err != nil {
  286. return nil, err
  287. }
  288. v.Items = append(v.Items, itemView{Heading: hv, Body: bodyHTML})
  289. if b.Level <= 3 {
  290. toc = append(toc, tocItem{Level: b.Level, ID: hv.ID, Title: plainText(b.Heading)})
  291. }
  292. }
  293. return &page{
  294. Kind: "guide", Key: "guide:" + g.Slug, Title: g.Title, Desc: g.Summary, TOC: toc, Guide: v,
  295. Edit: repoURL + "/edit/master/scripts/agidocgen/pages/" + g.Slug + ".md",
  296. }, nil
  297. }
  298. func (s *siteModel) heading(b *Block, rc *renderCtx, ids idSet) (*headingView, error) {
  299. h, err := s.md.inline(b.Heading, rc)
  300. if err != nil {
  301. return nil, err
  302. }
  303. hv := &headingView{Level: b.Level, ID: ids.take(slugify(b.Heading)), HTML: h}
  304. if gh := githubSlug(b.Heading); gh != "" && gh != hv.ID {
  305. hv.Aliases = append(hv.Aliases, ids.take(gh))
  306. }
  307. if hv.Level < 2 {
  308. hv.Level = 2
  309. }
  310. return hv, nil
  311. }
  312. func (s *siteModel) refPage(r *RefPage) (*page, error) {
  313. rc := &renderCtx{Root: "../", Syms: s.syms}
  314. v := &refView{Page: r, Builtin: builtinRefs[r.ID], Play: playMode(r.ID)}
  315. var err error
  316. if v.Intro, err = s.md.render(strings.ReplaceAll(r.Intro, "{{agiVersion}}", s.Version), rc); err != nil {
  317. return nil, err
  318. }
  319. ids := idSet{}
  320. var toc []tocItem
  321. addEntry := func(f *Function, level int) {
  322. fv := &fnView{Level: level, ID: ids.take(anchorFor(f.Names())), Sigs: []sigView{entrySig(f)}}
  323. if f.Example != "" {
  324. fv.Examples = []string{f.Example}
  325. }
  326. v.Items = append(v.Items, itemView{Fn: fv})
  327. toc = append(toc, tocItem{Level: level, ID: fv.ID, Title: fv.Sigs[0].Name, Code: true})
  328. }
  329. for _, f := range r.Leading {
  330. addEntry(f, 2)
  331. }
  332. for _, b := range r.Blocks {
  333. if !b.IsFn {
  334. hv, err := s.heading(b, rc, ids)
  335. if err != nil {
  336. return nil, err
  337. }
  338. bodyHTML, err := s.md.render(b.Body, rc)
  339. if err != nil {
  340. return nil, err
  341. }
  342. v.Items = append(v.Items, itemView{Heading: hv, Body: bodyHTML})
  343. if b.Level <= 3 {
  344. toc = append(toc, tocItem{Level: b.Level, ID: hv.ID, Title: plainText(b.Heading)})
  345. }
  346. continue
  347. }
  348. fv, err := s.fnBlock(b, rc, ids)
  349. if err != nil {
  350. return nil, err
  351. }
  352. v.Items = append(v.Items, itemView{Fn: fv})
  353. toc = append(toc, tocItem{Level: fv.Level, ID: fv.ID, Title: fv.Sigs[0].Name, Code: true})
  354. for _, f := range b.After {
  355. addEntry(f, fv.Level)
  356. }
  357. }
  358. for _, it := range v.Items {
  359. if it.Fn == nil {
  360. continue
  361. }
  362. for _, sg := range it.Fn.Sigs {
  363. v.Index = append(v.Index, indexRow{Name: sg.Name, Ret: sg.Ret, Desc: sg.Desc, Anchor: it.Fn.ID})
  364. }
  365. }
  366. for i := range toc {
  367. if toc[i].Level > 3 {
  368. toc[i].Level = 3
  369. }
  370. }
  371. return &page{
  372. Kind: "ref", Key: "ref:" + r.ID, Title: r.Title, Desc: r.Desc, Root: "../", TOC: toc, Ref: v,
  373. Edit: repoURL + "/edit/master/scripts/agidocgen/reference/" + r.ID + ".md",
  374. }, nil
  375. }
  376. // fnBlock draws a function heading as a card: the api.json signature,
  377. // return type and summary, then the Markdown, then any api.json example the
  378. // Markdown does not already show.
  379. func (s *siteModel) fnBlock(b *Block, rc *renderCtx, ids idSet) (*fnView, error) {
  380. skip := map[string]bool{}
  381. for _, n := range b.Names() {
  382. skip[n] = true
  383. }
  384. for _, f := range b.Entries {
  385. for _, n := range f.Names() {
  386. skip[n] = true
  387. }
  388. }
  389. brc := &renderCtx{Root: rc.Root, Syms: rc.Syms, Skip: skip}
  390. body, err := s.md.render(strings.ReplaceAll(b.Body, "{{agiVersion}}", s.Version), brc)
  391. if err != nil {
  392. return nil, err
  393. }
  394. fv := &fnView{Level: b.Level, Body: body, Badges: b.Badges}
  395. if fv.Level < 2 {
  396. fv.Level = 2
  397. }
  398. if len(b.Entries) > 0 {
  399. // The Markdown's own examples win: the api.json one (written for the
  400. // Terminal's short help) is only added where the page shows no code.
  401. hasCode := len(codeBlocks(b.Body)) > 0
  402. for _, f := range b.Entries {
  403. sv := entrySig(f)
  404. if sv.Ret == "" {
  405. sv.Ret = b.Ret
  406. }
  407. fv.Sigs = append(fv.Sigs, sv)
  408. if f.Example != "" && !hasCode {
  409. fv.Examples = append(fv.Examples, f.Example)
  410. }
  411. }
  412. } else {
  413. fv.Missing = true
  414. desc := firstSentence(b.Body)
  415. for _, sp := range b.Sigs {
  416. name, args := splitSig(sp.Sig)
  417. fv.Sigs = append(fv.Sigs, sigView{Name: name, Args: args, Ret: b.Ret})
  418. }
  419. if len(fv.Sigs) == 1 {
  420. fv.Sigs[0].Desc = desc
  421. }
  422. }
  423. fv.ID = ids.take(anchorFor(b.Names()))
  424. if gh := githubSlug(b.Heading); gh != "" && gh != fv.ID {
  425. fv.Aliases = append(fv.Aliases, ids.take(gh))
  426. }
  427. return fv, nil
  428. }
  429. func entrySig(f *Function) sigView {
  430. sig := f.Sig
  431. if sig == "" {
  432. sig = f.Name
  433. }
  434. name, args := splitSig(sig)
  435. sv := sigView{Name: name, Args: args, Ret: f.Ret, Desc: f.Desc}
  436. for _, n := range f.Names() {
  437. if n != name {
  438. sv.Also = append(sv.Also, n)
  439. }
  440. }
  441. return sv
  442. }
  443. // splitSig separates "filelib.readFile(vpath)" into its name and arguments.
  444. func splitSig(sig string) (string, string) {
  445. sig = strings.TrimSpace(sig)
  446. if i := strings.Index(sig, "("); i > 0 {
  447. return strings.TrimSpace(sig[:i]), sig[i:]
  448. }
  449. return sig, ""
  450. }
  451. // ---------- search and playground data ----------
  452. type searchEntry struct {
  453. T string `json:"t"` // title
  454. S string `json:"s"` // where it lives
  455. U string `json:"u"` // URL from the docs root
  456. D string `json:"d,omitempty"` // summary
  457. K string `json:"k"` // page, section or fn
  458. }
  459. func (s *siteModel) searchIndex() []searchEntry {
  460. var out []searchEntry
  461. for _, g := range s.Guides {
  462. out = append(out, searchEntry{T: g.Title, S: "Guide", U: g.Slug + ".html", D: g.Summary, K: "page"})
  463. _, blocks := splitBlocks(g.Body)
  464. ids := idSet{}
  465. for _, b := range blocks {
  466. id := ids.take(slugify(b.Heading))
  467. if gh := githubSlug(b.Heading); gh != "" && gh != id {
  468. ids.take(gh)
  469. }
  470. out = append(out, searchEntry{T: plainText(b.Heading), S: g.Title, U: g.Slug + ".html#" + id, K: "section"})
  471. }
  472. }
  473. for _, r := range s.Refs {
  474. url := "reference/" + r.ID + ".html"
  475. kind := "Library"
  476. if builtinRefs[r.ID] {
  477. kind = "Built-in functions"
  478. }
  479. out = append(out, searchEntry{T: r.Title, S: kind, U: url, D: r.Desc, K: "page"})
  480. for _, f := range r.AllFunctions() {
  481. ret := ""
  482. if f.Ret != "" {
  483. ret = " → " + f.Ret
  484. }
  485. for _, n := range f.Names {
  486. out = append(out, searchEntry{T: n, S: r.Title + ret, U: url + "#" + f.Anchor, D: f.Desc, K: "fn"})
  487. }
  488. }
  489. }
  490. out = append(out, searchEntry{T: "Playground", S: "Tool", U: "playground.html", D: "Run AGI scripts in your browser.", K: "page"})
  491. return out
  492. }
  493. // catalogLib tells the playground which functions each library has, so the
  494. // libraries it cannot run for real still exist and answer with mock data.
  495. type catalogLib struct {
  496. ID string `json:"id"`
  497. Title string `json:"title"`
  498. Load string `json:"load,omitempty"`
  499. Play string `json:"play"`
  500. Fns []FnInfo `json:"fns"`
  501. }
  502. func (s *siteModel) catalog() []catalogLib {
  503. var out []catalogLib
  504. for _, r := range s.Refs {
  505. out = append(out, catalogLib{ID: r.ID, Title: r.Title, Load: r.Load, Play: playMode(r.ID), Fns: r.AllFunctions()})
  506. }
  507. return out
  508. }
  509. // playModes says how the playground serves each page: "runs" for what its
  510. // engine does for real (on the virtual drive and session), otherwise the
  511. // tool window whose answers the library returns. Libraries not listed are
  512. // generic mocks answered from the Services window. Keep in step with
  513. // playground.NativeLibs.
  514. var playModes = map[string]string{
  515. "core": "runs", "db": "runs", "user": "runs", "filelib": "runs", "imagelib": "runs",
  516. "appdata": "runs", "ziplib": "runs", "share": "runs", "websocket": "runs",
  517. "scheduler": "runs", "notification": "runs",
  518. "http": "HTTP", "llm": "LLM", "cnn": "CNN", "sqlite": "Services", "sysinfo": "Services",
  519. }
  520. func playMode(id string) string {
  521. if m, ok := playModes[id]; ok {
  522. return m
  523. }
  524. return "Services"
  525. }
  526. // ---------- static files and templates ----------
  527. // copyStatic copies static/ into the output and derives the cache-busting
  528. // version from the content of every file.
  529. func (s *siteModel) copyStatic(out string) error {
  530. h := sha1.New()
  531. err := filepath.WalkDir("static", func(p string, d fs.DirEntry, err error) error {
  532. if err != nil || d.IsDir() {
  533. return err
  534. }
  535. raw, err := os.ReadFile(p)
  536. if err != nil {
  537. return err
  538. }
  539. rel, _ := filepath.Rel("static", p)
  540. h.Write([]byte(filepath.ToSlash(rel)))
  541. h.Write(raw)
  542. return writeFile(filepath.Join(out, rel), raw)
  543. })
  544. if err != nil {
  545. return err
  546. }
  547. h.Write([]byte(s.Version))
  548. s.assetVer = hex.EncodeToString(h.Sum(nil))[:10]
  549. return nil
  550. }
  551. func (s *siteModel) parseTemplates() error {
  552. funcs := template.FuncMap{
  553. "icon": func(name string) (template.HTML, error) {
  554. ic, ok := s.Icons[name]
  555. if !ok {
  556. return "", fmt.Errorf("no icon named %q", name)
  557. }
  558. return ic, nil
  559. },
  560. "asset": func(root, p string) string { return root + p + "?v=" + s.assetVer },
  561. "ver": func() string { return s.assetVer },
  562. "lower": strings.ToLower,
  563. "base": path.Base,
  564. "heading": func(level int, id string, aliases []string, inner template.HTML) template.HTML {
  565. if level < 2 {
  566. level = 2
  567. }
  568. if level > 6 {
  569. level = 6
  570. }
  571. var b strings.Builder
  572. fmt.Fprintf(&b, `<h%d id="%s" class="hd">`, level, template.HTMLEscapeString(id))
  573. for _, a := range aliases {
  574. fmt.Fprintf(&b, `<span id="%s" class="alias"></span>`, template.HTMLEscapeString(a))
  575. }
  576. fmt.Fprintf(&b, `%s<a class="hd-link" href="#%s" aria-label="Link to this section">#</a></h%d>`, inner, template.HTMLEscapeString(id), level)
  577. return template.HTML(b.String())
  578. },
  579. }
  580. files, err := filepath.Glob(filepath.Join("templates", "*.html"))
  581. if err != nil {
  582. return err
  583. }
  584. sort.Strings(files)
  585. t, err := template.New("").Funcs(funcs).ParseFiles(files...)
  586. if err != nil {
  587. return err
  588. }
  589. s.tpl = t
  590. return nil
  591. }