| 1 | package docs |
| 2 | |
| 3 | // The two export routes, and the view data the formatting bar and the |
| 4 | // download links need. |
| 5 | // |
| 6 | // Both routes are GETs of a document the signed-in person already |
| 7 | // owns, resolved through the same getDocumentForUpdates every other |
| 8 | // document route uses — so a document belonging to someone else 404s |
| 9 | // identically to one that does not exist (spec §4.2), and there is no |
| 10 | // separate ownership check here that could 403 by mistake. |
| 11 | |
| 12 | import ( |
| 13 | "fmt" |
| 14 | "net/http" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "unicode" |
| 18 | |
| 19 | "amadan.net/rastrillo/rastrillo" |
| 20 | |
| 21 | "github.com/carlosframework/docs/internal/export" |
| 22 | "github.com/carlosframework/docs/internal/fonts" |
| 23 | ) |
| 24 | |
| 25 | // toolbarOption is one <option> in a toolbar select. |
| 26 | type toolbarOption struct { |
| 27 | Value string |
| 28 | Label string |
| 29 | } |
| 30 | |
| 31 | // toolbarView is the formatting bar's copy, all of it resolved from |
| 32 | // the catalog at render time. fixtures/toolbar.mjs reads the values |
| 33 | // (data-docs-command, and each option's value) and never the labels — |
| 34 | // the bundle carries no copy of its own, the same rule the save-status |
| 35 | // indicator follows. |
| 36 | type toolbarView struct { |
| 37 | Label string |
| 38 | Undo string |
| 39 | Redo string |
| 40 | // History names the undo/redo pair; the Group* are the four |
| 41 | // sections' visible labels in the inspector (spec I2), and Inspector |
| 42 | // names the panel itself. |
| 43 | History string |
| 44 | GroupStyle string |
| 45 | GroupText string |
| 46 | GroupAlign string |
| 47 | GroupLists string |
| 48 | Inspector string |
| 49 | Bold string |
| 50 | Italic string |
| 51 | Code string |
| 52 | BulletList string |
| 53 | OrderedList string |
| 54 | Quote string |
| 55 | AlignLeft string |
| 56 | AlignCenter string |
| 57 | AlignRight string |
| 58 | |
| 59 | BlockLabel string |
| 60 | Blocks []toolbarOption |
| 61 | FontLabel string |
| 62 | Fonts []fontOption |
| 63 | SizeLabel string |
| 64 | Sizes []toolbarOption |
| 65 | |
| 66 | // The three strings ui/select.js reads off data attributes when it |
| 67 | // turns a <select> into a filterable combobox. See newToolbarView |
| 68 | // for why they come from the framework's catalog rather than this |
| 69 | // app's. |
| 70 | SelectFilter string |
| 71 | SelectResults string |
| 72 | SelectResultOne string |
| 73 | |
| 74 | // The phone's Format sheet and quick format bar (design/phone-web, |
| 75 | // P2): the sheet's title and its close button; the size stepper's two |
| 76 | // steps; the sheet's last group (indent, outdent, clear formatting, |
| 77 | // which the strip never had); and the quick bar's hide-keyboard |
| 78 | // button. Format, Indent, Outdent and Clear are the menu's own words. |
| 79 | Format string |
| 80 | Close string |
| 81 | SizeDown string |
| 82 | SizeUp string |
| 83 | GroupMore string |
| 84 | Indent string |
| 85 | Outdent string |
| 86 | Clear string |
| 87 | HideKeyboard string |
| 88 | } |
| 89 | |
| 90 | // newToolbarView builds it for one request's locale. |
| 91 | // |
| 92 | // The option values are the vocabulary shared with |
| 93 | // fixtures/toolbar.mjs ("paragraph", "heading-2", "sans", "lg") and, |
| 94 | // through it, with core/src/fragment.rs's mark names. They are |
| 95 | // literals here rather than derived from anything, because they are a |
| 96 | // contract with two other files and a derivation would hide that. |
| 97 | func newToolbarView(r *http.Request) toolbarView { |
| 98 | return toolbarView{ |
| 99 | Label: rastrillo.T(r, "docs.editor.toolbar.label"), |
| 100 | Undo: rastrillo.T(r, "docs.editor.toolbar.undo"), |
| 101 | Redo: rastrillo.T(r, "docs.editor.toolbar.redo"), |
| 102 | History: rastrillo.T(r, "docs.editor.toolbar.history"), |
| 103 | GroupStyle: rastrillo.T(r, "docs.editor.toolbar.group.style"), |
| 104 | GroupText: rastrillo.T(r, "docs.editor.toolbar.group.text"), |
| 105 | GroupAlign: rastrillo.T(r, "docs.editor.toolbar.group.align"), |
| 106 | GroupLists: rastrillo.T(r, "docs.editor.toolbar.group.lists"), |
| 107 | Inspector: rastrillo.T(r, "docs.editor.inspector.label"), |
| 108 | Bold: rastrillo.T(r, "docs.editor.toolbar.bold"), |
| 109 | Italic: rastrillo.T(r, "docs.editor.toolbar.italic"), |
| 110 | Code: rastrillo.T(r, "docs.editor.toolbar.code"), |
| 111 | BulletList: rastrillo.T(r, "docs.editor.toolbar.bulletlist"), |
| 112 | OrderedList: rastrillo.T(r, "docs.editor.toolbar.orderedlist"), |
| 113 | Quote: rastrillo.T(r, "docs.editor.toolbar.quote"), |
| 114 | // The command names these three buttons carry ("align_left" |
| 115 | // and so on) are a contract with fixtures/toolbar.mjs, and |
| 116 | // through it with core/src/fragment.rs's ALIGNMENTS table — |
| 117 | // the suffix after "align_" is the attribute value that ends |
| 118 | // up in the CRDT. |
| 119 | AlignLeft: rastrillo.T(r, "docs.editor.toolbar.align.left"), |
| 120 | AlignCenter: rastrillo.T(r, "docs.editor.toolbar.align.center"), |
| 121 | AlignRight: rastrillo.T(r, "docs.editor.toolbar.align.right"), |
| 122 | |
| 123 | BlockLabel: rastrillo.T(r, "docs.editor.toolbar.block"), |
| 124 | Blocks: []toolbarOption{ |
| 125 | {"paragraph", rastrillo.T(r, "docs.editor.toolbar.block.paragraph")}, |
| 126 | {"heading-1", rastrillo.T(r, "docs.editor.toolbar.block.heading1")}, |
| 127 | {"heading-2", rastrillo.T(r, "docs.editor.toolbar.block.heading2")}, |
| 128 | {"heading-3", rastrillo.T(r, "docs.editor.toolbar.block.heading3")}, |
| 129 | }, |
| 130 | FontLabel: rastrillo.T(r, "docs.editor.toolbar.font"), |
| 131 | Fonts: fontOptions(), |
| 132 | SizeLabel: rastrillo.T(r, "docs.editor.toolbar.size"), |
| 133 | Sizes: sizeOptions(), |
| 134 | |
| 135 | Format: rastrillo.T(r, "docs.editor.inspector.toggle"), |
| 136 | Close: rastrillo.T(r, "docs.editor.inspector.close"), |
| 137 | SizeDown: rastrillo.T(r, "docs.editor.toolbar.size.down"), |
| 138 | SizeUp: rastrillo.T(r, "docs.editor.toolbar.size.up"), |
| 139 | GroupMore: rastrillo.T(r, "docs.editor.toolbar.group.more"), |
| 140 | Indent: rastrillo.T(r, "docs.editor.menu.format.indent"), |
| 141 | Outdent: rastrillo.T(r, "docs.editor.menu.format.outdent"), |
| 142 | Clear: rastrillo.T(r, "docs.editor.menu.format.clear"), |
| 143 | HideKeyboard: rastrillo.T(r, "docs.editor.quickbar.hide"), |
| 144 | |
| 145 | // The searchable-select enhancement's own strings. |
| 146 | // |
| 147 | // These are the FRAMEWORK's catalog keys, not this app's — the |
| 148 | // only place in this file that reaches into rastrillo's own |
| 149 | // namespace, and deliberately so. ui/select.js builds its |
| 150 | // combobox in the browser, where the catalog is out of reach, so |
| 151 | // the strings ride out on data attributes; |
| 152 | // ui/partials/field-select.html emits exactly these three keys |
| 153 | // for exactly this reason, and our hand-written selects have to |
| 154 | // do the same rather than invent app-side copy for a framework |
| 155 | // control. Getting them from rastrillo.T means they follow the |
| 156 | // reader's locale like everything else, in twelve base locales |
| 157 | // we do not have to translate ourselves. |
| 158 | SelectFilter: rastrillo.T(r, "rastrillo.ui.select_filter"), |
| 159 | SelectResults: rastrillo.T(r, "rastrillo.ui.select_results"), |
| 160 | SelectResultOne: rastrillo.T(r, "rastrillo.ui.select_result_one"), |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | // historyView is docs-history's data (views/partials/editor_bar.html): |
| 165 | // the undo/redo pair, in the bar's lead slot (Lead) or in the strip. |
| 166 | type historyView struct { |
| 167 | Label, Undo, Redo string |
| 168 | Lead bool |
| 169 | } |
| 170 | |
| 171 | func (t toolbarView) history(lead bool) historyView { |
| 172 | return historyView{Label: t.History, Undo: t.Undo, Redo: t.Redo, Lead: lead} |
| 173 | } |
| 174 | |
| 175 | // StripHistory is the strip's pair, for show.html. |
| 176 | func (t toolbarView) StripHistory() historyView { return t.history(false) } |
| 177 | |
| 178 | // sizeOptions is the point ladder the size control offers. |
| 179 | // |
| 180 | // THE LABELS ARE NOT CATALOG KEYS, and that is deliberate rather than |
| 181 | // an oversight of AGENTS.md's "every user-visible string is a catalog |
| 182 | // key". A point size is a quantity, not authored copy — the same |
| 183 | // category as a document's title, which views/show.html also prints |
| 184 | // as-is rather than resolving. "12" is not English, there is nothing to |
| 185 | // translate, and eleven catalog entries mapping "12" to "12" in every |
| 186 | // locale would be eleven more things to keep in step for no reader's |
| 187 | // benefit. |
| 188 | // |
| 189 | // The four named steps this replaced — Small, Normal, Large, Extra |
| 190 | // large — genuinely were copy, and their keys are still in the catalog |
| 191 | // because documents predating the ladder still carry those marks. They |
| 192 | // are simply not offered here any more. |
| 193 | // |
| 194 | // DEFAULT FIRST, which is why this is written out rather than sorted. A |
| 195 | // <select> shows its first option until something sets a value, and |
| 196 | // with no JavaScript nothing ever does — export.go's own history has |
| 197 | // this exact bug, with Small listed first over body text that was |
| 198 | // Normal. fixtures/sizes.mjs's SIZES carries the same order and its |
| 199 | // module-load guard refuses any other, so the two cannot drift. |
| 200 | func sizeOptions() []toolbarOption { |
| 201 | // The same ladder as fixtures/sizes.mjs's SIZES, default first. |
| 202 | // internal/docs's TestSizeLadderMatchesTheBundle holds them equal — |
| 203 | // Go and Node cannot import each other, so a test is the only thing |
| 204 | // that can. |
| 205 | points := []int{12, 8, 9, 10, 11, 14, 18, 24, 36, 48, 72} |
| 206 | out := make([]toolbarOption, 0, len(points)) |
| 207 | for _, pt := range points { |
| 208 | v := strconv.Itoa(pt) |
| 209 | out = append(out, toolbarOption{v, v}) |
| 210 | } |
| 211 | return out |
| 212 | } |
| 213 | |
| 214 | // fontOption is one entry of the font control, drawn in its own face |
| 215 | // (Paul, 2026-10-24): Class is the preview class ui/select.js puts on the |
| 216 | // row and on the closed box (data-rst-class, rastrillo v0.28.0). The |
| 217 | // name is the family's own, untranslated; it is a proper noun, and the |
| 218 | // preview subset holds exactly its glyphs. A row is the name alone: a |
| 219 | // Word font's metric twin does not say so (Paul, 2026-10-26); Help → |
| 220 | // Fonts does. DOCX export and paste name the Word face through the |
| 221 | // manifest's docx.name. |
| 222 | type fontOption struct { |
| 223 | Value string |
| 224 | Name string |
| 225 | Class string |
| 226 | } |
| 227 | |
| 228 | // fontOptions is internal/fonts' manifest, in its order: Carlito and |
| 229 | // Caladea first, Carlito being the default and so what the control shows |
| 230 | // over unmarked text, and what a <select> with no script shows first. |
| 231 | func fontOptions() []fontOption { |
| 232 | out := make([]fontOption, 0, len(fonts.Families)) |
| 233 | for _, f := range fonts.Families { |
| 234 | out = append(out, fontOption{Value: f.Key, Name: f.Name, Class: f.PreviewClass()}) |
| 235 | } |
| 236 | return out |
| 237 | } |
| 238 | |
| 239 | // exportMarkdown serves GET /d/{sqid}/export.md. |
| 240 | func (h *handlers) exportMarkdown(w http.ResponseWriter, r *http.Request) { |
| 241 | doc, structure, ok := h.documentForExport(w, r) |
| 242 | if !ok { |
| 243 | return |
| 244 | } |
| 245 | body := export.Markdown(structure) |
| 246 | |
| 247 | // text/markdown is the registered type (RFC 7763). charset is |
| 248 | // stated because the export is UTF-8 and a reader that guesses |
| 249 | // latin-1 turns every em dash into mojibake. |
| 250 | w.Header().Set("Content-Type", "text/markdown; charset=utf-8") |
| 251 | setDownloadName(w, doc, ".md") |
| 252 | if err := writeGuardedBody(w, r, 0, []byte(body)); err != nil { |
| 253 | h.logger.Error("docs: write markdown export", "sqid", doc.Sqid, "err", err) |
| 254 | } |
| 255 | } |
| 256 | |
| 257 | // exportPDF serves GET /d/{sqid}/export.pdf. |
| 258 | func (h *handlers) exportPDF(w http.ResponseWriter, r *http.Request) { |
| 259 | doc, structure, ok := h.documentForExport(w, r) |
| 260 | if !ok { |
| 261 | return |
| 262 | } |
| 263 | |
| 264 | body, report, err := export.PDF(structure) |
| 265 | if err != nil { |
| 266 | h.logger.Error("docs: render pdf export", "sqid", doc.Sqid, "err", err) |
| 267 | h.fail(w, r, h.internalFailureStatus(), failStatus) |
| 268 | return |
| 269 | } |
| 270 | if !report.Empty() { |
| 271 | // §11.2's degrade-loudly rule, as loudly as this route can |
| 272 | // currently manage: the PDF is still served — a document with |
| 273 | // one unsettable character is far more useful than an error — |
| 274 | // but the substitution is on the record rather than only in |
| 275 | // the file. Surfacing it to the person who asked needs a |
| 276 | // screen to surface it on, which is the import/export report |
| 277 | // §11.2 describes and this branch does not build. |
| 278 | // |
| 279 | // The COUNT and the Unicode blocks, never the characters |
| 280 | // themselves. Report.String() renders the actual runes, and |
| 281 | // this log line reaches the platform's own log store |
| 282 | // (`carlos logs`) — spec §2.1's leak list, item 5, is |
| 283 | // categorical that a handler must never interpolate document |
| 284 | // content into a log or an error. For a short document in an |
| 285 | // unshipped script the deduplicated set of its characters |
| 286 | // approximates the document, so this would have leaked most of |
| 287 | // one in plaintext, out of a system whose whole premise is |
| 288 | // that documents are sealed at rest — and it would have done |
| 289 | // it to exactly the people the missing fonts already |
| 290 | // disadvantage. Blocks are enough to act on: they say which |
| 291 | // faces to add. |
| 292 | h.logger.Warn("docs: pdf export substituted characters", |
| 293 | "sqid", doc.Sqid, |
| 294 | "count", len(report.MissingRunes), |
| 295 | "blocks", report.Blocks()) |
| 296 | } |
| 297 | |
| 298 | w.Header().Set("Content-Type", "application/pdf") |
| 299 | setDownloadName(w, doc, ".pdf") |
| 300 | if err := writeGuardedBody(w, r, 0, body); err != nil { |
| 301 | h.logger.Error("docs: write pdf export", "sqid", doc.Sqid, "err", err) |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | // documentForExport resolves the document and reads its structure out |
| 306 | // of the CRDT core. ok is false once a response has already been |
| 307 | // written. |
| 308 | func (h *handlers) documentForExport(w http.ResponseWriter, r *http.Request) (*Document, export.Document, bool) { |
| 309 | doc, ok := h.getDocumentForUpdates(w, r) |
| 310 | if !ok { |
| 311 | return nil, export.Document{}, false |
| 312 | } |
| 313 | |
| 314 | structureJSON, err := h.store.JSON(r.Context(), doc) |
| 315 | if err != nil { |
| 316 | h.logger.Error("docs: document structure", "sqid", doc.Sqid, "err", err) |
| 317 | h.fail(w, r, h.internalFailureStatus(), failStatus) |
| 318 | return nil, export.Document{}, false |
| 319 | } |
| 320 | |
| 321 | structure, err := export.Parse(doc.Title, structureJSON) |
| 322 | if err != nil { |
| 323 | h.logger.Error("docs: parse document structure", "sqid", doc.Sqid, "err", err) |
| 324 | h.fail(w, r, h.internalFailureStatus(), failStatus) |
| 325 | return nil, export.Document{}, false |
| 326 | } |
| 327 | return doc, structure, true |
| 328 | } |
| 329 | |
| 330 | // setDownloadName writes the Content-Disposition header. |
| 331 | // |
| 332 | // The filename comes from the document's title, which is arbitrary |
| 333 | // text somebody typed — including, potentially, quotes, semicolons, |
| 334 | // newlines and path separators, every one of which means something in |
| 335 | // this header or in a filesystem. exportFilename below reduces it to a |
| 336 | // conservative set rather than escaping it, because a filename is not |
| 337 | // the place to be clever, and falls back to the sqid when nothing |
| 338 | // usable survives. |
| 339 | func setDownloadName(w http.ResponseWriter, doc *Document, ext string) { |
| 340 | w.Header().Set("Content-Disposition", |
| 341 | fmt.Sprintf("attachment; filename=%q", exportFilename(doc, ext))) |
| 342 | } |
| 343 | |
| 344 | // exportFilename builds a safe download name. |
| 345 | // |
| 346 | // Deliberately ASCII-only, and deliberately not RFC 5987's filename* |
| 347 | // form: a person exporting a document called "Café notes" gets |
| 348 | // "Caf-notes.pdf", which is a slightly worse name and no risk at all, |
| 349 | // where the alternative is two encodings of the same header that |
| 350 | // browsers have historically disagreed about. The document's real |
| 351 | // title is inside the file either way — the PDF carries it as |
| 352 | // metadata and the Markdown as its first heading. |
| 353 | func exportFilename(doc *Document, ext string) string { |
| 354 | var b strings.Builder |
| 355 | lastDash := true // suppress a leading dash |
| 356 | for _, r := range doc.Title { |
| 357 | switch { |
| 358 | case r < unicode.MaxASCII && (unicode.IsLetter(r) || unicode.IsDigit(r)): |
| 359 | b.WriteRune(r) |
| 360 | lastDash = false |
| 361 | case !lastDash: |
| 362 | // Every other character — spaces, punctuation, anything |
| 363 | // non-ASCII — collapses to a single dash. |
| 364 | b.WriteByte('-') |
| 365 | lastDash = true |
| 366 | } |
| 367 | if b.Len() >= 60 { |
| 368 | break |
| 369 | } |
| 370 | } |
| 371 | name := strings.Trim(b.String(), "-") |
| 372 | if name == "" { |
| 373 | // A title of nothing but punctuation, or a document called |
| 374 | // "日報". The sqid is always a usable filename by construction |
| 375 | // (store.go's sqidAlphabet is lowercase letters and digits). |
| 376 | name = doc.Sqid |
| 377 | } |
| 378 | return name + ext |
| 379 | } |
| 380 | |