oficina / mapa Public

Clone
git clone https://amadan.net/oficina/mapa

Plain git — no account needed to clone.

Download

Download this file

1package mapa
2
3import (
4 "context"
5 "encoding/json"
6 "html/template"
7 "net/http"
8 "strings"
9
10 "amadan.net/oficina/mapa/internal/mapa/locale"
11 "amadan.net/oficina/mapa/internal/mapa/markup"
12)
13
14// What the editor is given (level-up §6.8). Every editable page carries
15// a JSON island, <script type="application/json" id="mapa-editor">,
16// holding the source the editor mounts over, the page's current
17// revision, the person's draft if they have one, and each link's chip
18// state under the viewer's scope. Chips typed after mount ask
19// POST /links/resolve. Both read through the scoped accessor
20// (around.go) and write nothing.
21
22// maxResolve is how many link targets one /links/resolve may ask for.
23const maxResolve = 32
24
25// island is the editor's data, as JSON. Revisions and versions are
26// int63s, past what a JavaScript number holds, so they are text.
27type island struct {
28 Source string `json:"source"`
29 Base string `json:"base"`
30 Draft *islandDraft `json:"draft"`
31 Links map[string]LinkState `json:"links"`
32 // Drafts is where the editor autosaves: the page's or the day's
33 // …/draft, or /scratch for a page that does not exist yet, whose
34 // first autosave is its first commit (First).
35 Drafts string `json:"drafts"`
36 First bool `json:"first,omitempty"`
37 // Page is the page's public id, for Resolve's inline choice; empty
38 // for a page or day not written yet.
39 Page string `json:"page,omitempty"`
40 // Dates is the reader's locale's date patterns, which the editor
41 // labels chips typed after mount and draws its picker with
42 // (editor/dates.mjs, build note 85).
43 Dates locale.Client `json:"dates"`
44 // Images is each image's state in the source, on this page for
45 // this viewer (images §4.5): what the editor draws it as.
46 Images map[string]imageState `json:"images"`
47}
48
49// imageState is an image as the editor draws it: available with its
50// size, or not (images §2.3). Never a node attribute.
51type imageState struct {
52 Available bool `json:"available"`
53 Width int `json:"width"`
54 Height int `json:"height"`
55}
56
57// ImageStates is each id's state on page for scope.
58func (index *Index) ImageStates(ctx context.Context, scope Scope,
59 page int64, ids []string) map[string]imageState {
60 lookup := index.imageLookup(ctx)
61 lookup.fetch(ids)
62 out := make(map[string]imageState, len(ids))
63 for _, id := range ids {
64 if !markup.IsImageID(id) {
65 continue
66 }
67 answer := lookup.answer(scope, page, id)
68 out[id] = imageState{Available: answer.Available,
69 Width: answer.Width, Height: answer.Height}
70 }
71 return out
72}
73
74type islandDraft struct {
75 Version string `json:"version"`
76 Base string `json:"base"`
77}
78
79// linkKey is how a link is named in the island and in /links/resolve:
80// its target as typed, with "#^id" when it names a block.
81func linkKey(target, anchor string) string {
82 if anchor == "" {
83 return target
84 }
85 return target + "#^" + anchor
86}
87
88// splitKey reads a link key back, by the parser's own rule for what
89// sits between [[ and ]] (markup's wikiSpan): "|" ends the target, "#^"
90// starts the anchor, and the target is trimmed.
91func splitKey(key string) (string, string, bool) {
92 target, _, _ := strings.Cut(key, "|")
93 target, anchor, _ := strings.Cut(target, "#")
94 target = strings.TrimSpace(target)
95 if !strings.HasPrefix(anchor, "^") {
96 anchor = ""
97 } else {
98 anchor = strings.TrimSpace(anchor[1:])
99 }
100 return target, anchor, target != ""
101}
102
103// LinkStates is each key's chip state for scope.
104func (index *Index) LinkStates(ctx context.Context, scope Scope,
105 keys []string) (map[string]LinkState, error) {
106 if err := index.Sync(ctx); err != nil {
107 return nil, err
108 }
109 index.mutex.RLock()
110 defer index.mutex.RUnlock()
111 view := index.in(scope)
112 out := make(map[string]LinkState, len(keys))
113 for _, key := range keys {
114 if target, anchor, ok := splitKey(key); ok {
115 out[key] = view.linkState(target, anchor)
116 }
117 }
118 return out, nil
119}
120
121// islandFor is the island for a page the viewer may edit: source is the
122// text the page shows (the draft's, when there is one), its current
123// revision (0 for a page or day not written yet), drafts where it
124// autosaves.
125func (app *app) islandFor(ctx context.Context, viewer Viewer,
126 page PageView, draft *DraftView, drafts string) (template.JS, error) {
127 source := page.Body
128 var keys []string
129 for _, link := range markup.Links(source) {
130 keys = append(keys, linkKey(link.Target, link.Anchor))
131 }
132 links, err := app.index.LinkStates(ctx, ScopeOf(viewer), keys)
133 if err != nil {
134 return "", err
135 }
136 data := island{Source: source, Base: idText(page.Revision),
137 Links: links, Drafts: drafts, First: drafts == "/scratch",
138 Dates: viewer.Locale.Client(),
139 Images: app.index.ImageStates(ctx, ScopeOf(viewer), page.ID,
140 sortedKeys(markup.ImageIDs(source)))}
141 if page.ID != 0 {
142 data.Page = page.Public
143 }
144 if draft != nil {
145 data.Draft = &islandDraft{Version: idText(draft.Version),
146 Base: idText(draft.BaseRevision)}
147 }
148 // encoding/json escapes <, >, & and U+2028/9, so no body can end
149 // the script element early or open a comment in it.
150 encoded, err := json.Marshal(data)
151 return template.JS(encoded), err
152}
153
154// resolveLinks is POST /links/resolve: up to maxResolve link keys in
155// the body, as "target" fields, answered as {key: {kind, href, title}}.
156// A POST so the targets travel in the body, not a URL that logs keep;
157// it writes nothing, like /preview.
158func (app *app) resolveLinks(writer http.ResponseWriter,
159 request *http.Request) {
160 viewer, err := app.viewer(request)
161 if err == nil {
162 err = request.ParseForm()
163 }
164 if err != nil {
165 app.fail(writer, request, err)
166 return
167 }
168 keys, images := request.PostForm["target"], request.PostForm["image"]
169 if len(keys) > maxResolve || len(images) > maxResolve {
170 refuseJSON(writer, http.StatusUnprocessableEntity, "too many")
171 return
172 }
173 states, err := app.index.LinkStates(request.Context(), ScopeOf(viewer),
174 keys)
175 if err != nil {
176 app.fail(writer, request, err)
177 return
178 }
179 if len(images) == 0 {
180 answer(writer, states)
181 return
182 }
183 // Image ids too (images §2.2): scoped as rendering is, on the page
184 // the editor is on, when the viewer may open it.
185 answer(writer, map[string]any{"links": states,
186 "images": app.index.ImageStates(request.Context(), ScopeOf(viewer),
187 app.previewPage(request, viewer), images)})
188}
189
190// editorState is what an editable page shows of the person's draft,
191// and its island.
192type editorState struct {
193 Draft *DraftView
194 // Saved is ?saved=1: the committed text, the draft still offered.
195 Saved bool
196 Island template.JS
197}
198
199// editorFor is a page's editor state for the viewer. A person with a
200// draft is shown the draft's text as the page body, so the editor
201// mounts over the markup it will edit (level-up §6.8); ?saved=1 shows
202// the committed text instead, and carries no island, since it is not
203// the text the draft continues.
204func (app *app) editorFor(request *http.Request, viewer Viewer,
205 page *PageView, key DraftKey) (editorState, error) {
206 ctx := request.Context()
207 state := editorState{Saved: request.URL.Query().Get("saved") == "1"}
208 draft, found, err := app.store.OwnDraft(ctx, viewer, key)
209 if err != nil || (found && state.Saved) {
210 state.Draft = pointerIf(found, draft)
211 return state, err
212 }
213 if found {
214 state.Draft = &draft
215 page.Body = draft.Body
216 page.HTML, err = app.index.Preview(ctx, ScopeOf(viewer), page.ID,
217 draft.Body)
218 if err != nil {
219 return state, err
220 }
221 }
222 state.Island, err = app.islandFor(ctx, viewer, *page, state.Draft,
223 draftsOf(*page))
224 return state, err
225}
226
227// draftsOf is where the editor autosaves a page: a daily note by its
228// day, so a day written meanwhile in another tab is still found.
229func draftsOf(page PageView) string {
230 if page.Kind == KindDaily {
231 return "/d/" + page.Date + "/draft"
232 }
233 return "/p/" + page.Public + "/draft"
234}
235
236func pointerIf(found bool, draft DraftView) *DraftView {
237 if !found {
238 return nil
239 }
240 return &draft
241}
242
243// dayEditor is editorFor for a day: its note's, or an unwritten day's.
244// A day re-shown after a refused POST carries no island: its editor is
245// the textarea's, holding that tab's text.
246func (app *app) dayEditor(request *http.Request, viewer Viewer,
247 data *dayData) error {
248 if request.Method != http.MethodGet {
249 return nil
250 }
251 key := DraftKey{Date: data.Page.Date}
252 if data.Written {
253 key = DraftKey{PageID: data.Page.ID}
254 }
255 state, err := app.editorFor(request, viewer, &data.Page, key)
256 data.Saved, data.Island = state.Saved, state.Island
257 return err
258}
259