Allow editing of individual sections
This commit is contained in:
39
main.go
39
main.go
@@ -10,6 +10,7 @@ import (
|
||||
"os"
|
||||
"path"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"strings"
|
||||
)
|
||||
|
||||
@@ -123,6 +124,16 @@ func (h *handler) serveDir(w http.ResponseWriter, r *http.Request, urlPath, fsPa
|
||||
indexPath := filepath.Join(fsPath, "index.md")
|
||||
rawMD, _ := os.ReadFile(indexPath)
|
||||
|
||||
// Determine section index (-1 = whole page).
|
||||
sectionIndex := -1
|
||||
if editMode {
|
||||
if s := r.URL.Query().Get("section"); s != "" {
|
||||
if n, err := strconv.Atoi(s); err == nil && n >= 0 {
|
||||
sectionIndex = n
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
var rendered template.HTML
|
||||
if len(rawMD) > 0 && !editMode {
|
||||
rendered = renderMarkdown(rawMD)
|
||||
@@ -152,13 +163,22 @@ func (h *handler) serveDir(w http.ResponseWriter, r *http.Request, urlPath, fsPa
|
||||
specialContent = special.Content
|
||||
}
|
||||
|
||||
rawContent := string(rawMD)
|
||||
if editMode && sectionIndex >= 0 {
|
||||
sections := splitSections(rawMD)
|
||||
if sectionIndex < len(sections) {
|
||||
rawContent = string(sections[sectionIndex])
|
||||
}
|
||||
}
|
||||
|
||||
data := pageData{
|
||||
Title: title,
|
||||
Crumbs: buildCrumbs(urlPath),
|
||||
CanEdit: true,
|
||||
EditMode: editMode,
|
||||
SectionIndex: sectionIndex,
|
||||
PostURL: urlPath,
|
||||
RawContent: string(rawMD),
|
||||
RawContent: rawContent,
|
||||
Content: rendered,
|
||||
Entries: entries,
|
||||
SpecialContent: specialContent,
|
||||
@@ -177,6 +197,23 @@ func (h *handler) handlePost(w http.ResponseWriter, r *http.Request, urlPath, fs
|
||||
}
|
||||
content := r.FormValue("content")
|
||||
indexPath := filepath.Join(fsPath, "index.md")
|
||||
|
||||
// If a section index was submitted, splice the edited section back into
|
||||
// the full file rather than replacing the whole document.
|
||||
if s := r.FormValue("section"); s != "" {
|
||||
sectionIndex, err := strconv.Atoi(s)
|
||||
if err != nil || sectionIndex < 0 {
|
||||
http.Error(w, "bad section", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
rawMD, _ := os.ReadFile(indexPath)
|
||||
sections := splitSections(rawMD)
|
||||
if sectionIndex < len(sections) {
|
||||
sections[sectionIndex] = []byte(content)
|
||||
}
|
||||
content = string(joinSections(sections))
|
||||
}
|
||||
|
||||
if strings.TrimSpace(content) == "" {
|
||||
if err := os.Remove(indexPath); err != nil && !os.IsNotExist(err) {
|
||||
http.Error(w, "delete failed: "+err.Error(), http.StatusInternalServerError)
|
||||
|
||||
Reference in New Issue
Block a user