From fa6a4c650facb814c892cf5b15f3c2c533394bf9 Mon Sep 17 00:00:00 2001
From: Anya Tokugawa
Date: Tue, 19 May 2026 21:30:42 +0900
Subject: [PATCH] init
---
.gitignore | 3 +
Dockerfile | 16 +
README.md | 1 +
cmd/pageswiki/main.go | 65 ++
deploy/nginx.conf | 9 +
docker-compose.yml | 18 +
go.mod | 24 +
go.sum | 51 ++
internal/address/model.go | 23 +
internal/api/error.go | 23 +
internal/db/bootstrap.go | 79 ++
internal/db/db.go | 60 ++
internal/db/migrate.go | 91 ++
internal/object/model.go | 7 +
internal/render/html.go | 10 +
internal/render/markdown.go | 15 +
internal/revision/model.go | 8 +
internal/server/api_handlers.go | 109 +++
internal/server/api_recursive_preview.go | 76 ++
internal/server/api_recursive_rename.go | 190 ++++
internal/server/breadcrumbs.go | 40 +
internal/server/explorer.go | 67 ++
internal/server/handlers.go | 75 ++
internal/server/handlers_new.go | 41 +
internal/server/health.go | 18 +
internal/server/link_manager.go | 22 +
internal/server/macro_expand.go | 68 ++
internal/server/middleware.go | 37 +
internal/server/middleware/logging.go | 31 +
internal/server/middleware/normalize.go | 53 ++
internal/server/middleware/recovery.go | 38 +
internal/server/middleware/request_id.go | 43 +
internal/server/object_resolver.go | 103 +++
internal/server/path_api.go | 37 +
internal/server/path_mutation_api.go | 96 ++
internal/server/raw_view.go | 48 +
internal/server/register_restore_route.go | 3 +
internal/server/render.go | 38 +
internal/server/render_api.go | 28 +
internal/server/revision_api.go | 64 ++
internal/server/revision_browser.go | 43 +
internal/server/revision_restore.go | 56 ++
internal/server/revision_routes.go | 215 +++++
internal/server/routes.go | 14 +
internal/server/routes/api.go | 78 ++
internal/server/routes/ui.go | 116 +++
internal/server/routes_explorer.go | 3 +
internal/server/semantic.go | 48 +
internal/server/semantic_handlers.go | 186 ++++
internal/server/server.go | 169 ++++
internal/server/server_revision_routes.txt | 16 +
internal/server/tag_api.go | 37 +
internal/server/template_funcs.go | 54 ++
internal/server/tree_handler.go | 74 ++
internal/service/page_service.go | 43 +
internal/store/create_object.go | 51 ++
internal/store/list_children.go | 88 ++
internal/store/list_semantic_objects.go | 51 ++
internal/store/objects.go | 46 +
internal/store/path_mutation.go | 32 +
internal/store/paths.go | 146 +++
internal/store/revision_store.go | 140 +++
internal/store/revisions.go | 54 ++
internal/store/store.go | 16 +
internal/store/tags.go | 53 ++
internal/store/tree.go | 152 ++++
static/css/dialog.css | 24 +
static/css/explorer.css | 10 +
static/css/main.css | 53 ++
static/css/modes.css | 7 +
static/css/revisions.css | 55 ++
static/js/app.js | 163 ++++
static/js/editor.js | 315 +++++++
static/js/navigation.js | 50 ++
static/js/path-actions.js | 105 +++
static/js/revisions.js | 44 +
static/js/search.js | 1 +
templates/layouts/base.gohtml | 60 ++
templates/layouts/base.gohtml.append.txt | 3 +
templates/layouts/body_class.gohtml | 3 +
templates/layouts/scripts.gohtml | 8 +
templates/pages/editor.gohtml | 148 ++++
templates/pages/editor_body_class.gohtml | 3 +
templates/pages/explorer.gohtml | 41 +
templates/pages/home.gohtml | 200 +++++
templates/pages/links.gohtml | 89 ++
templates/pages/page.gohtml | 90 ++
templates/pages/revision_diff.gohtml | 49 ++
templates/pages/revision_view.gohtml | 106 +++
templates/pages/revisions.gohtml | 108 +++
templates/pages/tree.gohtml | 978 +++++++++++++++++++++
templates/partials/breadcrumbs.gohtml | 18 +
templates/partials/search_dialog.gohtml | 15 +
93 files changed, 6555 insertions(+)
create mode 100644 .gitignore
create mode 100644 Dockerfile
create mode 100644 README.md
create mode 100644 cmd/pageswiki/main.go
create mode 100644 deploy/nginx.conf
create mode 100644 docker-compose.yml
create mode 100644 go.mod
create mode 100644 go.sum
create mode 100644 internal/address/model.go
create mode 100644 internal/api/error.go
create mode 100644 internal/db/bootstrap.go
create mode 100644 internal/db/db.go
create mode 100644 internal/db/migrate.go
create mode 100644 internal/object/model.go
create mode 100644 internal/render/html.go
create mode 100644 internal/render/markdown.go
create mode 100644 internal/revision/model.go
create mode 100644 internal/server/api_handlers.go
create mode 100644 internal/server/api_recursive_preview.go
create mode 100644 internal/server/api_recursive_rename.go
create mode 100644 internal/server/breadcrumbs.go
create mode 100644 internal/server/explorer.go
create mode 100644 internal/server/handlers.go
create mode 100644 internal/server/handlers_new.go
create mode 100644 internal/server/health.go
create mode 100644 internal/server/link_manager.go
create mode 100644 internal/server/macro_expand.go
create mode 100644 internal/server/middleware.go
create mode 100644 internal/server/middleware/logging.go
create mode 100644 internal/server/middleware/normalize.go
create mode 100644 internal/server/middleware/recovery.go
create mode 100644 internal/server/middleware/request_id.go
create mode 100644 internal/server/object_resolver.go
create mode 100644 internal/server/path_api.go
create mode 100644 internal/server/path_mutation_api.go
create mode 100644 internal/server/raw_view.go
create mode 100644 internal/server/register_restore_route.go
create mode 100644 internal/server/render.go
create mode 100644 internal/server/render_api.go
create mode 100644 internal/server/revision_api.go
create mode 100644 internal/server/revision_browser.go
create mode 100644 internal/server/revision_restore.go
create mode 100644 internal/server/revision_routes.go
create mode 100644 internal/server/routes.go
create mode 100644 internal/server/routes/api.go
create mode 100644 internal/server/routes/ui.go
create mode 100644 internal/server/routes_explorer.go
create mode 100644 internal/server/semantic.go
create mode 100644 internal/server/semantic_handlers.go
create mode 100644 internal/server/server.go
create mode 100644 internal/server/server_revision_routes.txt
create mode 100644 internal/server/tag_api.go
create mode 100644 internal/server/template_funcs.go
create mode 100644 internal/server/tree_handler.go
create mode 100644 internal/service/page_service.go
create mode 100644 internal/store/create_object.go
create mode 100644 internal/store/list_children.go
create mode 100644 internal/store/list_semantic_objects.go
create mode 100644 internal/store/objects.go
create mode 100644 internal/store/path_mutation.go
create mode 100644 internal/store/paths.go
create mode 100644 internal/store/revision_store.go
create mode 100644 internal/store/revisions.go
create mode 100644 internal/store/store.go
create mode 100644 internal/store/tags.go
create mode 100644 internal/store/tree.go
create mode 100644 static/css/dialog.css
create mode 100644 static/css/explorer.css
create mode 100644 static/css/main.css
create mode 100644 static/css/modes.css
create mode 100644 static/css/revisions.css
create mode 100644 static/js/app.js
create mode 100644 static/js/editor.js
create mode 100644 static/js/navigation.js
create mode 100644 static/js/path-actions.js
create mode 100644 static/js/revisions.js
create mode 100644 static/js/search.js
create mode 100644 templates/layouts/base.gohtml
create mode 100644 templates/layouts/base.gohtml.append.txt
create mode 100644 templates/layouts/body_class.gohtml
create mode 100644 templates/layouts/scripts.gohtml
create mode 100644 templates/pages/editor.gohtml
create mode 100644 templates/pages/editor_body_class.gohtml
create mode 100644 templates/pages/explorer.gohtml
create mode 100644 templates/pages/home.gohtml
create mode 100644 templates/pages/links.gohtml
create mode 100644 templates/pages/page.gohtml
create mode 100644 templates/pages/revision_diff.gohtml
create mode 100644 templates/pages/revision_view.gohtml
create mode 100644 templates/pages/revisions.gohtml
create mode 100644 templates/pages/tree.gohtml
create mode 100644 templates/partials/breadcrumbs.gohtml
create mode 100644 templates/partials/search_dialog.gohtml
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..8336a44
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,3 @@
+data/
+.tmp/
+*.sh
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..20d0991
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,16 @@
+FROM golang:1.22-alpine
+
+WORKDIR /src
+
+RUN apk add --no-cache git
+
+COPY go.mod go.sum ./
+RUN go mod download
+
+COPY . .
+
+RUN go build -o /pageswiki ./cmd/pageswiki
+
+EXPOSE 8081
+
+CMD ["/pageswiki"]
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..ee42029
--- /dev/null
+++ b/README.md
@@ -0,0 +1 @@
+pageswiki
diff --git a/cmd/pageswiki/main.go b/cmd/pageswiki/main.go
new file mode 100644
index 0000000..ff2cc8b
--- /dev/null
+++ b/cmd/pageswiki/main.go
@@ -0,0 +1,65 @@
+package main
+
+import (
+ "log"
+ "os"
+ "pageswiki/internal/db"
+ "pageswiki/internal/server"
+ "pageswiki/internal/store"
+ "path/filepath"
+)
+
+func main() {
+
+ dataDir :=
+ os.Getenv(
+ "PAGESWIKI_DATA_DIR",
+ )
+
+ if dataDir == "" {
+ dataDir = "./data"
+ }
+
+ err := os.MkdirAll(
+ dataDir,
+ 0755,
+ )
+
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ dbPath :=
+ filepath.Join(
+ dataDir,
+ "pages.db",
+ )
+
+ log.Printf(
+ "pages.db = %s",
+ dbPath,
+ )
+
+ database, err :=
+ db.Open(dbPath)
+
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ err = db.Migrate(database)
+
+ if err != nil {
+ log.Fatal(err)
+ }
+
+ st := store.New(database)
+
+ srv := server.New(st)
+
+ err = srv.Run(":81")
+
+ if err != nil {
+ log.Fatal(err)
+ }
+}
diff --git a/deploy/nginx.conf b/deploy/nginx.conf
new file mode 100644
index 0000000..50f533e
--- /dev/null
+++ b/deploy/nginx.conf
@@ -0,0 +1,9 @@
+server {
+ listen 80;
+
+ location / {
+ proxy_pass http://app:81;
+ proxy_set_header Host $host;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ }
+}
diff --git a/docker-compose.yml b/docker-compose.yml
new file mode 100644
index 0000000..9fdb133
--- /dev/null
+++ b/docker-compose.yml
@@ -0,0 +1,18 @@
+services:
+ nginx:
+ image: nginx:1.27-alpine
+ restart: unless-stopped
+ ports:
+ - "8080:80"
+ volumes:
+ - ./deploy/nginx.conf:/etc/nginx/conf.d/default.conf:ro
+ depends_on:
+ - app
+
+ app:
+ build: .
+ volumes:
+ - ./data:/data
+ environment:
+ PAGESWIKI_DATA_DIR: /data
+ restart: unless-stopped
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..73273df
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,24 @@
+module pageswiki
+
+go 1.22
+
+require (
+ github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df
+ github.com/google/uuid v1.6.0
+ modernc.org/sqlite v1.32.0
+)
+
+require (
+ github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/hashicorp/golang-lru/v2 v2.0.7 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/ncruces/go-strftime v0.1.9 // indirect
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ golang.org/x/sys v0.22.0 // indirect
+ modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 // indirect
+ modernc.org/libc v1.55.3 // indirect
+ modernc.org/mathutil v1.6.0 // indirect
+ modernc.org/memory v1.8.0 // indirect
+ modernc.org/strutil v1.2.0 // indirect
+ modernc.org/token v1.1.0 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..9f90df7
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,51 @@
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df h1:Mwihr/o+v4L5h56rwHLOE20+hh7Okhwno5BHz3zDuao=
+github.com/gomarkdown/markdown v0.0.0-20260417124207-7d523f7318df/go.mod h1:JDGcbDT52eL4fju3sZ4TeHGsQwhG9nbDV21aMyhwPoA=
+github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd h1:gbpYu9NMq8jhDVbvlGkMFWCjLFlqqEZjEmObmhUy6Vo=
+github.com/google/pprof v0.0.0-20240409012703-83162a5b38cd/go.mod h1:kf6iHlnVGwgKolg33glAes7Yg/8iWP8ukqeldJSO7jw=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/ncruces/go-strftime v0.1.9 h1:bY0MQC28UADQmHmaF5dgpLmImcShSi2kHU9XLdhx/f4=
+github.com/ncruces/go-strftime v0.1.9/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+golang.org/x/mod v0.16.0 h1:QX4fJ0Rr5cPQCF7O9lh9Se4pmwfwskqZfq5moyldzic=
+golang.org/x/mod v0.16.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.22.0 h1:RI27ohtqKCnwULzJLqkv897zojh5/DwS/ENaMzUOaWI=
+golang.org/x/sys v0.22.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
+golang.org/x/tools v0.19.0 h1:tfGCXNR1OsFG+sVdLAitlpjAvD/I6dHDKnYrpEZUHkw=
+golang.org/x/tools v0.19.0/go.mod h1:qoJWxmGSIBmAeriMx19ogtrEPrGtDbPK634QFIcLAhc=
+modernc.org/cc/v4 v4.21.4 h1:3Be/Rdo1fpr8GrQ7IVw9OHtplU4gWbb+wNgeoBMmGLQ=
+modernc.org/cc/v4 v4.21.4/go.mod h1:HM7VJTZbUCR3rV8EYBi9wxnJ0ZBRiGE5OeGXNA0IsLQ=
+modernc.org/ccgo/v4 v4.19.2 h1:lwQZgvboKD0jBwdaeVCTouxhxAyN6iawF3STraAal8Y=
+modernc.org/ccgo/v4 v4.19.2/go.mod h1:ysS3mxiMV38XGRTTcgo0DQTeTmAO4oCmJl1nX9VFI3s=
+modernc.org/fileutil v1.3.0 h1:gQ5SIzK3H9kdfai/5x41oQiKValumqNTDXMvKo62HvE=
+modernc.org/fileutil v1.3.0/go.mod h1:XatxS8fZi3pS8/hKG2GH/ArUogfxjpEKs3Ku3aK4JyQ=
+modernc.org/gc/v2 v2.4.1 h1:9cNzOqPyMJBvrUipmynX0ZohMhcxPtMccYgGOJdOiBw=
+modernc.org/gc/v2 v2.4.1/go.mod h1:wzN5dK1AzVGoH6XOzc3YZ+ey/jPgYHLuVckd62P0GYU=
+modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6 h1:5D53IMaUuA5InSeMu9eJtlQXS2NxAhyWQvkKEgXZhHI=
+modernc.org/gc/v3 v3.0.0-20240107210532-573471604cb6/go.mod h1:Qz0X07sNOR1jWYCrJMEnbW/X55x206Q7Vt4mz6/wHp4=
+modernc.org/libc v1.55.3 h1:AzcW1mhlPNrRtjS5sS+eW2ISCgSOLLNyFzRh/V3Qj/U=
+modernc.org/libc v1.55.3/go.mod h1:qFXepLhz+JjFThQ4kzwzOjA/y/artDeg+pcYnY+Q83w=
+modernc.org/mathutil v1.6.0 h1:fRe9+AmYlaej+64JsEEhoWuAYBkOtQiMEU7n/XgfYi4=
+modernc.org/mathutil v1.6.0/go.mod h1:Ui5Q9q1TR2gFm0AQRqQUaBWFLAhQpCwNcuhBOSedWPo=
+modernc.org/memory v1.8.0 h1:IqGTL6eFMaDZZhEWwcREgeMXYwmW83LYW8cROZYkg+E=
+modernc.org/memory v1.8.0/go.mod h1:XPZ936zp5OMKGWPqbD3JShgd/ZoQ7899TUuQqxY+peU=
+modernc.org/opt v0.1.3 h1:3XOZf2yznlhC+ibLltsDGzABUGVx8J6pnFMS3E4dcq4=
+modernc.org/opt v0.1.3/go.mod h1:WdSiB5evDcignE70guQKxYUl14mgWtbClRi5wmkkTX0=
+modernc.org/sortutil v1.2.0 h1:jQiD3PfS2REGJNzNCMMaLSp/wdMNieTbKX920Cqdgqc=
+modernc.org/sortutil v1.2.0/go.mod h1:TKU2s7kJMf1AE84OoiGppNHJwvB753OYfNl2WRb++Ss=
+modernc.org/sqlite v1.32.0 h1:6BM4uGza7bWypsw4fdLRsLxut6bHe4c58VeqjRgST8s=
+modernc.org/sqlite v1.32.0/go.mod h1:UqoylwmTb9F+IqXERT8bW9zzOWN8qwAIcLdzeBZs4hA=
+modernc.org/strutil v1.2.0 h1:agBi9dp1I+eOnxXeiZawM8F4LawKv4NzGWSaLfyeNZA=
+modernc.org/strutil v1.2.0/go.mod h1:/mdcBmfOibveCTBxUl5B5l6W+TTH1FXPLHZE6bTosX0=
+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
diff --git a/internal/address/model.go b/internal/address/model.go
new file mode 100644
index 0000000..8dee52d
--- /dev/null
+++ b/internal/address/model.go
@@ -0,0 +1,23 @@
+// URI Address Space in pageswiki system
+package address
+
+type Scheme string
+
+const (
+ // Path is described 'path:/path/to/file'
+ SchemePath Scheme = "path"
+ // UUID is described 'uuid:123e4567-e89b-42d3-a456-426614174000'
+ SchemeUUID Scheme = "uuid"
+ // Revision described 'rev:1'
+ SchemeRevision Scheme = "rev"
+ // Revision is described 'sha256:9a271f2a916b0b6ee6cecb2426f0b3206ef074578be55d9bc94f6f3fe3ab86aa'
+ SchemeSHA256 Scheme = "sha256"
+ // Asset is described 'asset:style.css'
+ SchemeAsset Scheme = "asset"
+)
+
+// URI Address Space has scheme and value
+type Address struct {
+ Scheme Scheme
+ Value string
+}
diff --git a/internal/api/error.go b/internal/api/error.go
new file mode 100644
index 0000000..8298ef6
--- /dev/null
+++ b/internal/api/error.go
@@ -0,0 +1,23 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+)
+
+func WriteError(
+ w http.ResponseWriter,
+ code int,
+ errCode string,
+ msg string,
+) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(code)
+
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "error": map[string]any{
+ "code": errCode,
+ "message": msg,
+ },
+ })
+}
diff --git a/internal/db/bootstrap.go b/internal/db/bootstrap.go
new file mode 100644
index 0000000..de97b2e
--- /dev/null
+++ b/internal/db/bootstrap.go
@@ -0,0 +1,79 @@
+package db
+
+import (
+ "database/sql"
+
+ "github.com/google/uuid"
+)
+
+func Bootstrap(
+ database *sql.DB,
+) error {
+
+ var count int
+
+ err := database.QueryRow(`
+ SELECT count(*)
+ FROM objects
+ `).Scan(&count)
+
+ if err != nil {
+ return err
+ }
+
+ if count > 0 {
+ return nil
+ }
+
+ rootUUID :=
+ uuid.NewString()
+
+ _, err = database.Exec(`
+ INSERT INTO objects ( uuid, created_at ) VALUES ( ?, strftime('%s','now') )`,
+ rootUUID,
+ )
+
+ if err != nil {
+ return err
+ }
+
+ _, err = database.Exec(`
+ INSERT INTO paths (
+ path,
+ object_uuid,
+ created_at
+ )
+ VALUES (
+ '/',
+ ?,
+ strftime('%s','now')
+ )
+ `,
+ rootUUID,
+ )
+
+ if err != nil {
+ return err
+ }
+
+ _, err = database.Exec(`
+ INSERT INTO revisions (
+ uuid,
+ object_uuid,
+ body,
+ message,
+ created_at
+ )
+ VALUES (
+ 'bootstrap-root',
+ ?,
+ 'Pages Wiki Bootstrap complete.
',
+ 'bootstrap',
+ strftime('%s','now')
+ )
+ `,
+ rootUUID,
+ )
+
+ return err
+}
diff --git a/internal/db/db.go b/internal/db/db.go
new file mode 100644
index 0000000..65137b4
--- /dev/null
+++ b/internal/db/db.go
@@ -0,0 +1,60 @@
+package db
+
+import (
+ "database/sql"
+
+ _ "modernc.org/sqlite"
+)
+
+func Open(path string) (*sql.DB, error) {
+ return sql.Open("sqlite", path)
+}
+
+func Init(db *sql.DB) error {
+
+ stmts := []string{
+ // objects: has UUID, kind, title
+ `
+ CREATE TABLE IF NOT EXISTS objects (
+ uuid TEXT PRIMARY KEY,
+ kind TEXT NOT NULL,
+ title TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+ )
+ `,
+ // revisions: has UUID, object uuid, body, message, created_at
+ `
+ CREATE TABLE IF NOT EXISTS revisions (
+ uuid TEXT PRIMARY KEY,
+ object_uuid TEXT NOT NULL,
+ body TEXT NOT NULL,
+ message TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+ )
+ `,
+ // paths: path -> object_uuid, created_at
+ `
+ CREATE TABLE IF NOT EXISTS paths (
+ path TEXT PRIMARY KEY,
+ object_uuid TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+ )
+ `,
+ // tags: object_uuid --> tag
+ `
+ CREATE TABLE IF NOT EXISTS tags (
+ object_uuid TEXT NOT NULL,
+ tag TEXT NOT NULL
+ )
+ `,
+ }
+
+ for _, stmt := range stmts {
+ _, err := db.Exec(stmt)
+ if err != nil {
+ return err
+ }
+ }
+
+ return nil
+}
diff --git a/internal/db/migrate.go b/internal/db/migrate.go
new file mode 100644
index 0000000..a2d0975
--- /dev/null
+++ b/internal/db/migrate.go
@@ -0,0 +1,91 @@
+package db
+
+import "database/sql"
+
+func Migrate(
+ db *sql.DB,
+) error {
+
+ stmts := []string{
+
+ `
+ CREATE TABLE IF NOT EXISTS objects (
+ uuid TEXT PRIMARY KEY,
+ kind TEXT,
+ created_at INTEGER DEFAULT (
+ strftime('%s','now')
+ )
+ )
+ `,
+
+ `
+ CREATE TABLE IF NOT EXISTS revisions (
+ uuid TEXT PRIMARY KEY,
+ object_uuid TEXT,
+ body TEXT,
+ message TEXT,
+ created_at INTEGER DEFAULT (
+ strftime('%s','now')
+ )
+ )
+ `,
+
+ `
+ CREATE TABLE IF NOT EXISTS paths (
+ path TEXT PRIMARY KEY,
+ object_uuid TEXT,
+ created_at INTEGER DEFAULT (
+ strftime('%s','now')
+ )
+ )
+ `,
+
+ `
+ CREATE TABLE IF NOT EXISTS tags (
+ object_uuid TEXT,
+ tag TEXT,
+ created_at INTEGER DEFAULT (
+ strftime('%s','now')
+ )
+ )
+ `,
+ }
+
+ for _, stmt := range stmts {
+
+ _, err := db.Exec(stmt)
+
+ if err != nil {
+ return err
+ }
+ }
+
+ alterStmts := []string{
+
+ `
+ ALTER TABLE paths
+ ADD COLUMN created_at INTEGER
+ `,
+
+ `
+ ALTER TABLE objects
+ ADD COLUMN created_at INTEGER
+ `,
+
+ `
+ ALTER TABLE revisions
+ ADD COLUMN created_at INTEGER
+ `,
+
+ `
+ ALTER TABLE tags
+ ADD COLUMN created_at INTEGER
+ `,
+ }
+
+ for _, stmt := range alterStmts {
+ _, _ = db.Exec(stmt)
+ }
+
+ return nil
+}
diff --git a/internal/object/model.go b/internal/object/model.go
new file mode 100644
index 0000000..3dabb87
--- /dev/null
+++ b/internal/object/model.go
@@ -0,0 +1,7 @@
+package object
+
+type Object struct {
+ UUID string
+ Kind string
+ Title string
+}
diff --git a/internal/render/html.go b/internal/render/html.go
new file mode 100644
index 0000000..d07cb82
--- /dev/null
+++ b/internal/render/html.go
@@ -0,0 +1,10 @@
+package render
+
+import "html/template"
+
+func SafeHTML(
+ input string,
+) template.HTML {
+
+ return template.HTML(input)
+}
diff --git a/internal/render/markdown.go b/internal/render/markdown.go
new file mode 100644
index 0000000..5307073
--- /dev/null
+++ b/internal/render/markdown.go
@@ -0,0 +1,15 @@
+package render
+
+import (
+ "github.com/gomarkdown/markdown"
+)
+
+func Markdown(input string) string {
+ out := markdown.ToHTML(
+ []byte(input),
+ nil,
+ nil,
+ )
+
+ return string(out)
+}
diff --git a/internal/revision/model.go b/internal/revision/model.go
new file mode 100644
index 0000000..4824a5f
--- /dev/null
+++ b/internal/revision/model.go
@@ -0,0 +1,8 @@
+package revision
+
+type Revision struct {
+ UUID string
+ ObjectUUID string
+ Message string
+ CreatedAt int64
+}
diff --git a/internal/server/api_handlers.go b/internal/server/api_handlers.go
new file mode 100644
index 0000000..191d51e
--- /dev/null
+++ b/internal/server/api_handlers.go
@@ -0,0 +1,109 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+
+ "pageswiki/internal/api"
+)
+
+func (s *Server) handleCreateObjectAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ var req struct {
+ Kind string `json:"kind"`
+ Title string `json:"title"`
+ Body string `json:"body"`
+ }
+
+ err := json.NewDecoder(r.Body).Decode(&req)
+ if err != nil {
+ api.WriteError(
+ w,
+ 400,
+ "bad_json",
+ err.Error(),
+ )
+ return
+ }
+
+ id, err := s.store.CreateObject(req.Kind)
+
+ if err != nil {
+ api.WriteError(
+ w,
+ 500,
+ "create_failed",
+ err.Error(),
+ )
+ return
+ }
+
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "uuid": id,
+ })
+}
+
+func (s *Server) handleListObjectsAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ objs, err := s.store.ListObjects()
+ if err != nil {
+ api.WriteError(
+ w,
+ 500,
+ "list_failed",
+ err.Error(),
+ )
+ return
+ }
+
+ _ = json.NewEncoder(w).Encode(objs)
+}
+
+func (s *Server) handleSaveRevisionAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ var req struct {
+ ObjectUUID string `json:"object_uuid"`
+ Body string `json:"body"`
+ Message string `json:"message"`
+ }
+
+ err := json.NewDecoder(r.Body).Decode(&req)
+ if err != nil {
+ api.WriteError(
+ w,
+ 400,
+ "bad_json",
+ err.Error(),
+ )
+ return
+ }
+
+ _, err = s.store.SaveRevision(
+ req.ObjectUUID,
+ req.Body,
+ req.Message,
+ )
+
+ if err != nil {
+ api.WriteError(
+ w,
+ 500,
+ "save_failed",
+ err.Error(),
+ )
+ return
+ }
+
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "status": "ok",
+ })
+}
diff --git a/internal/server/api_recursive_preview.go b/internal/server/api_recursive_preview.go
new file mode 100644
index 0000000..dd11333
--- /dev/null
+++ b/internal/server/api_recursive_preview.go
@@ -0,0 +1,76 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+)
+
+type renamePreviewResponse struct {
+ Targets []string `json:"targets"`
+}
+
+func (s *Server) handleRenamePreview(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ oldPath :=
+ r.URL.Query().Get(
+ "old_path",
+ )
+
+ rows, err :=
+ s.store.DB.Query(`
+ SELECT path
+ FROM paths
+ WHERE path = ?
+ OR path LIKE ?
+ ORDER BY LENGTH(path) ASC
+ `,
+ oldPath,
+ oldPath+"/%",
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ defer rows.Close()
+
+ var targets []string
+
+ for rows.Next() {
+
+ var p string
+
+ err := rows.Scan(&p)
+
+ if err != nil {
+ continue
+ }
+
+ targets =
+ append(
+ targets,
+ p,
+ )
+ }
+
+ w.Header().Set(
+ "Content-Type",
+ "application/json",
+ )
+
+ json.NewEncoder(w).Encode(
+ renamePreviewResponse{
+ Targets: targets,
+ },
+ )
+}
diff --git a/internal/server/api_recursive_rename.go b/internal/server/api_recursive_rename.go
new file mode 100644
index 0000000..6253d0c
--- /dev/null
+++ b/internal/server/api_recursive_rename.go
@@ -0,0 +1,190 @@
+package server
+
+import (
+ "database/sql"
+ "encoding/json"
+ "net/http"
+)
+
+type renamePathRequest struct {
+ OldPath string `json:"old_path"`
+ NewPath string `json:"new_path"`
+ Recursive bool `json:"recursive"`
+}
+
+type renamePreview struct {
+ Count int `json:"count"`
+}
+
+func (s *Server) handleRenamePath(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ var req renamePathRequest
+
+ err := json.NewDecoder(
+ r.Body,
+ ).Decode(&req)
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 400,
+ )
+
+ return
+ }
+
+ if req.OldPath == "" ||
+ req.NewPath == "" {
+
+ http.Error(
+ w,
+ "invalid path",
+ 400,
+ )
+
+ return
+ }
+
+ if req.Recursive {
+
+ var count int
+
+ err :=
+ s.store.DB.QueryRow(`
+ SELECT COUNT(*)
+ FROM paths
+ WHERE path = ?
+ OR path LIKE ?
+ `,
+ req.OldPath,
+ req.OldPath+"/%",
+ ).Scan(&count)
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ if r.URL.Query().Get("preview") == "1" {
+
+ w.Header().Set(
+ "Content-Type",
+ "application/json",
+ )
+
+ json.NewEncoder(w).Encode(
+ renamePreview{
+ Count: count,
+ },
+ )
+
+ return
+ }
+
+ tx, err :=
+ s.store.DB.BeginTx(
+ r.Context(),
+ &sql.TxOptions{},
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ _, err = tx.Exec(`
+ UPDATE paths
+ SET path =
+ CASE
+ WHEN path = ?
+ THEN ?
+ ELSE REPLACE(
+ path,
+ ? || '/',
+ ? || '/'
+ )
+ END
+ WHERE path = ?
+ OR path LIKE ?
+ `,
+ req.OldPath,
+ req.NewPath,
+
+ req.OldPath,
+ req.NewPath,
+
+ req.OldPath,
+ req.OldPath+"/%",
+ )
+
+ if err != nil {
+
+ tx.Rollback()
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ err = tx.Commit()
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ w.WriteHeader(200)
+
+ return
+ }
+
+ _, err =
+ s.store.DB.Exec(`
+ UPDATE paths
+ SET path = ?
+ WHERE path = ?
+ `,
+ req.NewPath,
+ req.OldPath,
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ w.WriteHeader(200)
+}
diff --git a/internal/server/breadcrumbs.go b/internal/server/breadcrumbs.go
new file mode 100644
index 0000000..514fcd8
--- /dev/null
+++ b/internal/server/breadcrumbs.go
@@ -0,0 +1,40 @@
+package server
+
+import "strings"
+
+type Breadcrumb struct {
+ Name string
+ Path string
+}
+
+func buildBreadcrumbs(
+ path string,
+) []Breadcrumb {
+
+ path = cleanSemanticPath(path)
+
+ if path == "/" {
+ return nil
+ }
+
+ parts :=
+ strings.Split(
+ strings.Trim(path, "/"),
+ "/",
+ )
+
+ var out []Breadcrumb
+ current := ""
+
+ for _, p := range parts {
+
+ current += "/" + p
+
+ out = append(out, Breadcrumb{
+ Name: p,
+ Path: current,
+ })
+ }
+
+ return out
+}
diff --git a/internal/server/explorer.go b/internal/server/explorer.go
new file mode 100644
index 0000000..2bff353
--- /dev/null
+++ b/internal/server/explorer.go
@@ -0,0 +1,67 @@
+package server
+
+import (
+ "net/http"
+)
+
+type ExplorerNode struct {
+ Path string
+ Children []ExplorerNode
+}
+
+func (s *Server) buildExplorerTree(
+ path string,
+ depth int,
+) []ExplorerNode {
+
+ if depth > 4 {
+ return nil
+ }
+
+ children, err :=
+ s.store.ListChildren(path)
+
+ if err != nil {
+ return nil
+ }
+
+ var out []ExplorerNode
+
+ for _, child := range children {
+
+ node := ExplorerNode{
+ Path: child,
+ }
+
+ node.Children =
+ s.buildExplorerTree(
+ child,
+ depth+1,
+ )
+
+ out = append(out, node)
+ }
+
+ return out
+}
+
+func (s *Server) handleExplorer(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ tree :=
+ s.buildExplorerTree(
+ "/",
+ 0,
+ )
+
+ s.render(
+ w,
+ "explorer.gohtml",
+ map[string]any{
+ "Title": "Explorer",
+ "Tree": tree,
+ },
+ )
+}
diff --git a/internal/server/handlers.go b/internal/server/handlers.go
new file mode 100644
index 0000000..4cc2628
--- /dev/null
+++ b/internal/server/handlers.go
@@ -0,0 +1,75 @@
+package server
+
+import (
+ "net/http"
+ "strings"
+)
+
+type HomeObject struct {
+ UUID string
+ Path string
+ Kind string
+}
+
+func (s *Server) handleHome(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ objects, err :=
+ s.store.ListObjects()
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ var semanticObjects []HomeObject
+
+ for _, o := range objects {
+
+ path := o.UUID
+
+ if path == "" {
+ continue
+ }
+
+ if strings.HasPrefix(
+ path,
+ "/system/",
+ ) {
+ continue
+ }
+
+ if strings.HasPrefix(
+ path,
+ "/o/",
+ ) {
+ continue
+ }
+
+ semanticObjects = append(
+ semanticObjects,
+ HomeObject{
+ UUID: o.UUID,
+ Path: path,
+ Kind: o.Kind,
+ },
+ )
+ }
+
+ s.render(
+ w,
+ "home.gohtml",
+ map[string]any{
+ "Title": "Pages Wiki",
+ "Objects": semanticObjects,
+ },
+ )
+}
diff --git a/internal/server/handlers_new.go b/internal/server/handlers_new.go
new file mode 100644
index 0000000..8cfe2c5
--- /dev/null
+++ b/internal/server/handlers_new.go
@@ -0,0 +1,41 @@
+package server
+
+import (
+ "fmt"
+ "net/http"
+ "time"
+)
+
+func (s *Server) handleNewPage(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ draftPath := fmt.Sprintf(
+ "/draft/%d",
+ time.Now().UnixNano(),
+ )
+
+ _, err :=
+ s.store.CreateObject(
+ draftPath,
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ http.Redirect(
+ w,
+ r,
+ "/e"+draftPath,
+ http.StatusFound,
+ )
+}
diff --git a/internal/server/health.go b/internal/server/health.go
new file mode 100644
index 0000000..30b7820
--- /dev/null
+++ b/internal/server/health.go
@@ -0,0 +1,18 @@
+package server
+
+import "net/http"
+
+func (s *Server) handleHealth(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ w.Header().Set(
+ "Content-Type",
+ "text/plain",
+ )
+
+ _, _ = w.Write(
+ []byte("ok"),
+ )
+}
diff --git a/internal/server/link_manager.go b/internal/server/link_manager.go
new file mode 100644
index 0000000..f98b6b6
--- /dev/null
+++ b/internal/server/link_manager.go
@@ -0,0 +1,22 @@
+package server
+
+import (
+ "net/http"
+)
+
+func (s *Server) handleLinkManager(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ objects, _ := s.store.ListObjects()
+
+ s.render(
+ w,
+ "links.gohtml",
+ map[string]any{
+ "Title": "Link Manager",
+ "Objects": objects,
+ },
+ )
+}
diff --git a/internal/server/macro_expand.go b/internal/server/macro_expand.go
new file mode 100644
index 0000000..5d6d67a
--- /dev/null
+++ b/internal/server/macro_expand.go
@@ -0,0 +1,68 @@
+package server
+
+import (
+ "fmt"
+ "strings"
+)
+
+func (s *Server) expandMacros(
+ body string,
+ currentPath string,
+) string {
+
+ if strings.Contains(
+ body,
+ "{{children}}",
+ ) {
+
+ children, err :=
+ s.store.ListChildPaths(
+ currentPath,
+ )
+
+ if err == nil {
+
+ var b strings.Builder
+
+ b.WriteString(
+ ``,
+ )
+
+ b.WriteString("")
+
+ for _, child := range children {
+
+ name :=
+ strings.TrimPrefix(
+ child,
+ currentPath,
+ )
+
+ name =
+ strings.TrimPrefix(
+ name,
+ "/",
+ )
+
+ b.WriteString(
+ fmt.Sprintf(
+ `%s `,
+ child,
+ name,
+ ),
+ )
+ }
+
+ b.WriteString(" ")
+ b.WriteString(" ")
+
+ body = strings.ReplaceAll(
+ body,
+ "{{children}}",
+ b.String(),
+ )
+ }
+ }
+
+ return body
+}
diff --git a/internal/server/middleware.go b/internal/server/middleware.go
new file mode 100644
index 0000000..e3c1202
--- /dev/null
+++ b/internal/server/middleware.go
@@ -0,0 +1,37 @@
+package server
+
+import (
+ "net/http"
+ "strings"
+)
+
+func (s *Server) normalizeSlashes(next http.Handler) http.Handler {
+ return http.HandlerFunc(func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+ if r.URL.Path != "/" &&
+ strings.HasSuffix(r.URL.Path, "/") {
+
+ target := strings.TrimSuffix(
+ r.URL.Path,
+ "/",
+ )
+
+ if r.URL.RawQuery != "" {
+ target += "?" + r.URL.RawQuery
+ }
+
+ http.Redirect(
+ w,
+ r,
+ target,
+ http.StatusMovedPermanently,
+ )
+
+ return
+ }
+
+ next.ServeHTTP(w, r)
+ })
+}
diff --git a/internal/server/middleware/logging.go b/internal/server/middleware/logging.go
new file mode 100644
index 0000000..5ab1328
--- /dev/null
+++ b/internal/server/middleware/logging.go
@@ -0,0 +1,31 @@
+package middleware
+
+import (
+ "log"
+ "net/http"
+ "time"
+)
+
+func Logging(
+ next http.Handler,
+) http.Handler {
+
+ return http.HandlerFunc(
+ func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+
+ start := time.Now()
+
+ next.ServeHTTP(w, r)
+
+ log.Printf(
+ "%s %s %s",
+ r.Method,
+ r.URL.Path,
+ time.Since(start),
+ )
+ },
+ )
+}
diff --git a/internal/server/middleware/normalize.go b/internal/server/middleware/normalize.go
new file mode 100644
index 0000000..85949a0
--- /dev/null
+++ b/internal/server/middleware/normalize.go
@@ -0,0 +1,53 @@
+package middleware
+
+import (
+ "net/http"
+ "strings"
+)
+
+func NormalizePath(
+ next http.Handler,
+) http.Handler {
+
+ return http.HandlerFunc(
+ func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+
+ p := r.URL.Path
+
+ if p != "/" {
+
+ for strings.HasSuffix(
+ p,
+ "/",
+ ) {
+
+ p = strings.TrimSuffix(
+ p,
+ "/",
+ )
+ }
+
+ if p == "" {
+ p = "/"
+ }
+
+ if p != r.URL.Path {
+
+ http.Redirect(
+ w,
+ r,
+ p,
+ http.StatusMovedPermanently,
+ )
+
+ return
+ }
+ }
+
+ next.ServeHTTP(w, r)
+ },
+ )
+}
diff --git a/internal/server/middleware/recovery.go b/internal/server/middleware/recovery.go
new file mode 100644
index 0000000..8e4199b
--- /dev/null
+++ b/internal/server/middleware/recovery.go
@@ -0,0 +1,38 @@
+package middleware
+
+import (
+ "log"
+ "net/http"
+)
+
+func Recovery(
+ next http.Handler,
+) http.Handler {
+
+ return http.HandlerFunc(
+ func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+
+ defer func() {
+
+ if err := recover(); err != nil {
+
+ log.Printf(
+ "panic recovered: %v",
+ err,
+ )
+
+ http.Error(
+ w,
+ "internal server error",
+ 500,
+ )
+ }
+ }()
+
+ next.ServeHTTP(w, r)
+ },
+ )
+}
diff --git a/internal/server/middleware/request_id.go b/internal/server/middleware/request_id.go
new file mode 100644
index 0000000..ca836cc
--- /dev/null
+++ b/internal/server/middleware/request_id.go
@@ -0,0 +1,43 @@
+package middleware
+
+import (
+ "context"
+ "net/http"
+
+ "github.com/google/uuid"
+)
+
+type contextKey string
+
+const RequestIDKey contextKey = "request_id"
+
+func RequestID(
+ next http.Handler,
+) http.Handler {
+
+ return http.HandlerFunc(
+ func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+
+ id := uuid.NewString()
+
+ ctx := context.WithValue(
+ r.Context(),
+ RequestIDKey,
+ id,
+ )
+
+ w.Header().Set(
+ "X-Request-ID",
+ id,
+ )
+
+ next.ServeHTTP(
+ w,
+ r.WithContext(ctx),
+ )
+ },
+ )
+}
diff --git a/internal/server/object_resolver.go b/internal/server/object_resolver.go
new file mode 100644
index 0000000..335dee1
--- /dev/null
+++ b/internal/server/object_resolver.go
@@ -0,0 +1,103 @@
+package server
+
+import (
+ "net/http"
+ "os"
+ "path/filepath"
+ "strings"
+)
+
+func (s *Server) handleObjectRoute(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ addr :=
+ strings.TrimPrefix(
+ r.URL.Path,
+ "/o/",
+ )
+
+ switch {
+
+ case strings.HasPrefix(
+ addr,
+ "path:",
+ ):
+
+ s.resolvePathAddress(
+ w,
+ r,
+ strings.TrimPrefix(
+ addr,
+ "path:",
+ ),
+ )
+
+ return
+
+ default:
+
+ http.NotFound(w, r)
+ return
+ }
+}
+
+func (s *Server) resolvePathAddress(
+ w http.ResponseWriter,
+ r *http.Request,
+ path string,
+) {
+
+ switch {
+
+ case strings.HasPrefix(
+ path,
+ "/system/static/",
+ ):
+
+ s.resolveStaticObject(
+ w,
+ r,
+ path,
+ )
+
+ return
+
+ default:
+
+ http.NotFound(w, r)
+ return
+ }
+}
+
+func (s *Server) resolveStaticObject(
+ w http.ResponseWriter,
+ r *http.Request,
+ path string,
+) {
+
+ rel :=
+ strings.TrimPrefix(
+ path,
+ "/system/static/",
+ )
+
+ localPath :=
+ filepath.Join(
+ "static",
+ rel,
+ )
+
+ if _, err := os.Stat(localPath); err != nil {
+
+ http.NotFound(w, r)
+ return
+ }
+
+ http.ServeFile(
+ w,
+ r,
+ localPath,
+ )
+}
diff --git a/internal/server/path_api.go b/internal/server/path_api.go
new file mode 100644
index 0000000..e4131c3
--- /dev/null
+++ b/internal/server/path_api.go
@@ -0,0 +1,37 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+)
+
+func (s *Server) handleBindPathAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ var req struct {
+ ObjectUUID string `json:"object_uuid"`
+ Path string `json:"path"`
+ }
+
+ err := json.NewDecoder(r.Body).Decode(&req)
+ if err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ err = s.store.BindPath(
+ req.Path,
+ req.ObjectUUID,
+ )
+
+ if err != nil {
+ http.Error(w, err.Error(), 500)
+ return
+ }
+
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "status": "ok",
+ })
+}
diff --git a/internal/server/path_mutation_api.go b/internal/server/path_mutation_api.go
new file mode 100644
index 0000000..e30837b
--- /dev/null
+++ b/internal/server/path_mutation_api.go
@@ -0,0 +1,96 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+)
+
+func (s *Server) handleRenamePathAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ var req struct {
+ OldPath string `json:"old_path"`
+ NewPath string `json:"new_path"`
+ }
+
+ err := json.NewDecoder(
+ r.Body,
+ ).Decode(&req)
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 400,
+ )
+
+ return
+ }
+
+ err = s.store.RenamePath(
+ req.OldPath,
+ req.NewPath,
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ w.WriteHeader(
+ http.StatusNoContent,
+ )
+}
+
+func (s *Server) handleRemovePathAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ var req struct {
+ Path string `json:"path"`
+ }
+
+ err := json.NewDecoder(
+ r.Body,
+ ).Decode(&req)
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 400,
+ )
+
+ return
+ }
+
+ err = s.store.RemovePath(
+ req.Path,
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ w.WriteHeader(
+ http.StatusNoContent,
+ )
+}
diff --git a/internal/server/raw_view.go b/internal/server/raw_view.go
new file mode 100644
index 0000000..87917dd
--- /dev/null
+++ b/internal/server/raw_view.go
@@ -0,0 +1,48 @@
+package server
+
+import (
+ "net/http"
+ "strings"
+)
+
+func (s *Server) handleRawView(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ path := strings.TrimPrefix(
+ r.URL.Path,
+ "/raw",
+ )
+
+ objectUUID, err :=
+ s.store.ResolvePath(path)
+
+ if err != nil {
+ http.NotFound(w, r)
+ return
+ }
+
+ rev, err :=
+ s.store.GetLatestRevision(
+ objectUUID,
+ )
+
+ if err != nil {
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+ return
+ }
+
+ w.Header().Set(
+ "Content-Type",
+ "text/plain",
+ )
+
+ _, _ = w.Write(
+ []byte(rev.Body),
+ )
+}
diff --git a/internal/server/register_restore_route.go b/internal/server/register_restore_route.go
new file mode 100644
index 0000000..f5a4cee
--- /dev/null
+++ b/internal/server/register_restore_route.go
@@ -0,0 +1,3 @@
+package server
+
+func init() {}
diff --git a/internal/server/render.go b/internal/server/render.go
new file mode 100644
index 0000000..30c5095
--- /dev/null
+++ b/internal/server/render.go
@@ -0,0 +1,38 @@
+package server
+
+import (
+ "html/template"
+ "net/http"
+)
+
+func (s *Server) render(
+ w http.ResponseWriter,
+ name string,
+ data any,
+) {
+
+ s.templates.Funcs(
+ template.FuncMap{
+ "sub": func(a, b int) int {
+ return a - b
+ },
+ },
+ )
+
+ err := s.templates.ExecuteTemplate(
+ w,
+ name,
+ data,
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+}
diff --git a/internal/server/render_api.go b/internal/server/render_api.go
new file mode 100644
index 0000000..66adf91
--- /dev/null
+++ b/internal/server/render_api.go
@@ -0,0 +1,28 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+
+ "pageswiki/internal/render"
+)
+
+func (s *Server) handleMarkdownRenderAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ var req struct {
+ Markdown string `json:"markdown"`
+ }
+
+ err := json.NewDecoder(r.Body).Decode(&req)
+ if err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "html": render.Markdown(req.Markdown),
+ })
+}
diff --git a/internal/server/revision_api.go b/internal/server/revision_api.go
new file mode 100644
index 0000000..af8ec06
--- /dev/null
+++ b/internal/server/revision_api.go
@@ -0,0 +1,64 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+)
+
+func (s *Server) handleRevisionListAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ uuid := r.URL.Query().Get(
+ "uuid",
+ )
+
+ rows, err := s.store.DB.Query(`
+ SELECT
+ uuid,
+ message,
+ created_at
+ FROM revisions
+ WHERE object_uuid = ?
+ ORDER BY created_at DESC
+ `, uuid)
+
+ if err != nil {
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+ return
+ }
+
+ defer rows.Close()
+
+ var out []map[string]any
+
+ for rows.Next() {
+
+ var revisionUUID string
+ var message string
+ var createdAt int64
+
+ err := rows.Scan(
+ &revisionUUID,
+ &message,
+ &createdAt,
+ )
+
+ if err != nil {
+ continue
+ }
+
+ out = append(out, map[string]any{
+ "uuid": revisionUUID,
+ "message": message,
+ "created_at": createdAt,
+ })
+ }
+
+ _ = json.NewEncoder(w).Encode(out)
+}
diff --git a/internal/server/revision_browser.go b/internal/server/revision_browser.go
new file mode 100644
index 0000000..20a6aa7
--- /dev/null
+++ b/internal/server/revision_browser.go
@@ -0,0 +1,43 @@
+package server
+
+import (
+ "net/http"
+ "strings"
+)
+
+func (s *Server) handleRevisionBrowser(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ objectUUID := strings.TrimPrefix(
+ r.URL.Path,
+ "/r/history/",
+ )
+
+ revisions, err :=
+ s.store.ListRevisions(
+ objectUUID,
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ s.render(
+ w,
+ "revisions.gohtml",
+ map[string]any{
+ "Title": "Revision History",
+ "ObjectUUID": objectUUID,
+ "Revisions": revisions,
+ },
+ )
+}
diff --git a/internal/server/revision_restore.go b/internal/server/revision_restore.go
new file mode 100644
index 0000000..363de7e
--- /dev/null
+++ b/internal/server/revision_restore.go
@@ -0,0 +1,56 @@
+package server
+
+import (
+ "net/http"
+)
+
+func (s *Server) handleRestoreRevisionAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ revisionUUID :=
+ r.URL.Query().Get("revision")
+
+ row := s.store.DB.QueryRow(`
+ SELECT
+ object_uuid,
+ body
+ FROM revisions
+ WHERE uuid = ?
+ `, revisionUUID)
+
+ var objectUUID string
+ var body string
+
+ err := row.Scan(
+ &objectUUID,
+ &body,
+ )
+
+ if err != nil {
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+ return
+ }
+
+ _, err = s.store.SaveRevision(
+ objectUUID,
+ body,
+ "restore revision",
+ )
+
+ if err != nil {
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+ return
+ }
+
+ _, _ = w.Write([]byte("ok"))
+}
diff --git a/internal/server/revision_routes.go b/internal/server/revision_routes.go
new file mode 100644
index 0000000..835358d
--- /dev/null
+++ b/internal/server/revision_routes.go
@@ -0,0 +1,215 @@
+package server
+
+import (
+ "fmt"
+ "html"
+ "html/template"
+ "net/http"
+ "strings"
+)
+
+func (s *Server) handleRevisionView(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ hash := strings.TrimPrefix(
+ r.URL.Path,
+ "/r/view/",
+ )
+
+ revision, err :=
+ s.store.GetRevision(hash)
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ s.render(
+ w,
+ "revision_view.gohtml",
+ map[string]any{
+ "Title": "Revision View",
+ "Revision": revision,
+ "RenderedHTML": template.HTML(
+ revision.Body,
+ ),
+ },
+ )
+}
+
+func renderColoredDiff(
+ before string,
+ after string,
+) string {
+
+ beforeLines := strings.Split(
+ before,
+ "\n",
+ )
+
+ afterLines := strings.Split(
+ after,
+ "\n",
+ )
+
+ max := len(beforeLines)
+
+ if len(afterLines) > max {
+ max = len(afterLines)
+ }
+
+ var out []string
+
+ out = append(
+ out,
+ ``,
+ )
+
+ for i := 0; i < max; i++ {
+
+ lineNo := i + 1
+
+ var b string
+ var a string
+
+ if i < len(beforeLines) {
+ b = beforeLines[i]
+ }
+
+ if i < len(afterLines) {
+ a = afterLines[i]
+ }
+
+ switch {
+
+ case b == a:
+
+ out = append(
+ out,
+ fmt.Sprintf(
+ `%4d %s
`,
+ lineNo,
+ html.EscapeString(a),
+ ),
+ )
+
+ default:
+
+ if b != "" {
+
+ out = append(
+ out,
+ fmt.Sprintf(
+ `%4d - %s
`,
+ lineNo,
+ html.EscapeString(b),
+ ),
+ )
+ }
+
+ if a != "" {
+
+ out = append(
+ out,
+ fmt.Sprintf(
+ `%4d + %s
`,
+ lineNo,
+ html.EscapeString(a),
+ ),
+ )
+ }
+ }
+ }
+
+ out = append(
+ out,
+ " ",
+ )
+
+ return strings.Join(
+ out,
+ "\n",
+ )
+}
+
+func (s *Server) handleRevisionDiff(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ path := strings.TrimPrefix(
+ r.URL.Path,
+ "/r/diff/",
+ )
+
+ parts := strings.SplitN(
+ path,
+ "/",
+ 2,
+ )
+
+ if len(parts) != 2 {
+
+ http.Error(
+ w,
+ "bad diff path",
+ 400,
+ )
+
+ return
+ }
+
+ beforeRev, err :=
+ s.store.GetRevision(parts[0])
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ afterRev, err :=
+ s.store.GetRevision(parts[1])
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ diffHTML := renderColoredDiff(
+ beforeRev.Body,
+ afterRev.Body,
+ )
+
+ s.render(
+ w,
+ "revision_diff.gohtml",
+ map[string]any{
+ "Title": "Revision Diff",
+ "Before": beforeRev,
+ "After": afterRev,
+ "DiffHTML": template.HTML(
+ diffHTML,
+ ),
+ },
+ )
+}
diff --git a/internal/server/routes.go b/internal/server/routes.go
new file mode 100644
index 0000000..ce9d7ee
--- /dev/null
+++ b/internal/server/routes.go
@@ -0,0 +1,14 @@
+package server
+
+func init() {
+
+ /*
+ ADD THIS ROUTE
+ BEFORE semantic catch-all:
+
+ s.mux.HandleFunc(
+ "/r/",
+ s.handleRevisionBrowser,
+ )
+ */
+}
diff --git a/internal/server/routes/api.go b/internal/server/routes/api.go
new file mode 100644
index 0000000..ee391f8
--- /dev/null
+++ b/internal/server/routes/api.go
@@ -0,0 +1,78 @@
+package routes
+
+import "net/http"
+
+type APIHandlers struct {
+ CreateObject http.HandlerFunc
+ ListObjects http.HandlerFunc
+ SaveRevision http.HandlerFunc
+ ListRevisions http.HandlerFunc
+ RestoreRevision http.HandlerFunc
+ RenderMarkdown http.HandlerFunc
+ AddTag http.HandlerFunc
+ BindPath http.HandlerFunc
+ RenamePath http.HandlerFunc
+ RenamePreview http.HandlerFunc
+ RemovePath http.HandlerFunc
+}
+
+func RegisterAPIRoutes(
+ mux *http.ServeMux,
+ h APIHandlers,
+) {
+
+ mux.HandleFunc(
+ "/_/api/v1/object/create",
+ h.CreateObject,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/object/list",
+ h.ListObjects,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/revisions/save",
+ h.SaveRevision,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/revisions/list",
+ h.ListRevisions,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/revisions/restore",
+ h.RestoreRevision,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/render/markdown",
+ h.RenderMarkdown,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/tag/add",
+ h.AddTag,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/path/bind",
+ h.BindPath,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/path/rename",
+ h.RenamePath,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/path/rename-preview",
+ h.RenamePreview,
+ )
+
+ mux.HandleFunc(
+ "/_/api/v1/path/remove",
+ h.RemovePath,
+ )
+}
diff --git a/internal/server/routes/ui.go b/internal/server/routes/ui.go
new file mode 100644
index 0000000..35fbf37
--- /dev/null
+++ b/internal/server/routes/ui.go
@@ -0,0 +1,116 @@
+package routes
+
+import "net/http"
+
+type UIHandlers struct {
+ Home http.HandlerFunc
+ NewPage http.HandlerFunc
+ SemanticEditor http.HandlerFunc
+ SemanticPage http.HandlerFunc
+ RawView http.HandlerFunc
+ LinkManager http.HandlerFunc
+ Health http.HandlerFunc
+ Tree http.HandlerFunc
+}
+
+func RegisterUIRoutes(
+ mux *http.ServeMux,
+ h UIHandlers,
+) {
+
+ mux.HandleFunc(
+ "/healthz",
+ h.Health,
+ )
+
+ mux.HandleFunc(
+ "/tree",
+ h.Tree,
+ )
+
+ mux.HandleFunc(
+ "/new",
+ h.NewPage,
+ )
+
+ mux.HandleFunc(
+ "/e",
+ h.SemanticEditor,
+ )
+
+ mux.HandleFunc(
+ "/e/",
+ h.SemanticEditor,
+ )
+
+ mux.HandleFunc(
+ "/raw",
+ h.RawView,
+ )
+
+ mux.HandleFunc(
+ "/raw/",
+ h.RawView,
+ )
+
+ mux.HandleFunc(
+ "/l",
+ h.LinkManager,
+ )
+
+ mux.HandleFunc(
+ "/",
+ func(
+ w http.ResponseWriter,
+ r *http.Request,
+ ) {
+
+ if r.URL.Path == "/" {
+
+ h.Home(
+ w,
+ r,
+ )
+
+ return
+ }
+
+ switch r.URL.Path {
+
+ case "/tree":
+
+ h.Tree(
+ w,
+ r,
+ )
+
+ return
+
+ case "/new":
+
+ h.NewPage(
+ w,
+ r,
+ )
+
+ return
+ }
+
+ if r.URL.Path == "/e" ||
+ r.URL.Path == "/raw" {
+
+ http.NotFound(
+ w,
+ r,
+ )
+
+ return
+ }
+
+ h.SemanticPage(
+ w,
+ r,
+ )
+ },
+ )
+}
diff --git a/internal/server/routes_explorer.go b/internal/server/routes_explorer.go
new file mode 100644
index 0000000..f5a4cee
--- /dev/null
+++ b/internal/server/routes_explorer.go
@@ -0,0 +1,3 @@
+package server
+
+func init() {}
diff --git a/internal/server/semantic.go b/internal/server/semantic.go
new file mode 100644
index 0000000..fd177ff
--- /dev/null
+++ b/internal/server/semantic.go
@@ -0,0 +1,48 @@
+package server
+
+import (
+ "strings"
+)
+
+func cleanSemanticPath(
+ path string,
+) string {
+
+ if path == "" {
+ return "/"
+ }
+
+ if !strings.HasPrefix(path, "/") {
+ path = "/" + path
+ }
+
+ if len(path) > 1 &&
+ strings.HasSuffix(path, "/") {
+
+ path = strings.TrimSuffix(
+ path,
+ "/",
+ )
+ }
+
+ return path
+}
+
+func parentPath(
+ path string,
+) string {
+
+ path = cleanSemanticPath(path)
+
+ if path == "/" {
+ return "/"
+ }
+
+ idx := strings.LastIndex(path, "/")
+
+ if idx <= 0 {
+ return "/"
+ }
+
+ return path[:idx]
+}
diff --git a/internal/server/semantic_handlers.go b/internal/server/semantic_handlers.go
new file mode 100644
index 0000000..4879df6
--- /dev/null
+++ b/internal/server/semantic_handlers.go
@@ -0,0 +1,186 @@
+package server
+
+import (
+ "html/template"
+ "net/http"
+ "strings"
+)
+
+func (s *Server) handleSemanticRoute(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ path := r.URL.Path
+
+ objectUUID, err :=
+ s.store.ResolvePath(path)
+
+ if err != nil {
+
+ http.NotFound(w, r)
+
+ return
+ }
+
+ latest, err :=
+ s.store.GetLatestRevision(
+ objectUUID,
+ )
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ rendered :=
+ s.expandMacros(
+ latest.Body,
+ path,
+ )
+
+ s.render(
+ w,
+ "page.gohtml",
+ map[string]any{
+ "Title": path,
+ "Path": path,
+ "ObjectUUID": objectUUID,
+ "RenderedHTML": template.HTML(
+ rendered,
+ ),
+ },
+ )
+}
+
+func (s *Server) handleSemanticEditor(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ path := strings.TrimPrefix(
+ r.URL.Path,
+ "/e",
+ )
+
+ if path == "" {
+ path = "/"
+ }
+
+ objectUUID, err :=
+ s.store.ResolvePath(path)
+
+ if err != nil {
+
+ objectUUID, err =
+ s.store.CreateObject(path)
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+ }
+
+ latest, err :=
+ s.store.GetLatestRevision(
+ objectUUID,
+ )
+
+ body := ""
+
+ if err == nil {
+ body = latest.Body
+ }
+
+ editType :=
+ r.URL.Query().Get(
+ "edittype",
+ )
+
+ if editType == "" {
+ editType = "html"
+ }
+
+ if editType == "markdown" {
+
+ body =
+ htmlToMarkdown(
+ body,
+ )
+ }
+
+ s.render(
+ w,
+ "editor.gohtml",
+ map[string]any{
+ "Title": path,
+ "Path": path,
+ "ObjectUUID": objectUUID,
+ "Body": body,
+ "RenderedHTML": template.HTML(
+ s.expandMacros(
+ body,
+ path,
+ ),
+ ),
+ "EditType": editType,
+ },
+ )
+}
+
+func htmlToMarkdown(
+ in string,
+) string {
+
+ out := in
+
+ out = strings.ReplaceAll(
+ out,
+ "",
+ "# ",
+ )
+
+ out = strings.ReplaceAll(
+ out,
+ " ",
+ "",
+ )
+
+ out = strings.ReplaceAll(
+ out,
+ "",
+ "",
+ )
+
+ out = strings.ReplaceAll(
+ out,
+ " ",
+ "",
+ )
+
+ out = strings.ReplaceAll(
+ out,
+ "",
+ "- ",
+ )
+
+ out = strings.ReplaceAll(
+ out,
+ " ",
+ "",
+ )
+
+ return out
+}
diff --git a/internal/server/server.go b/internal/server/server.go
new file mode 100644
index 0000000..809b993
--- /dev/null
+++ b/internal/server/server.go
@@ -0,0 +1,169 @@
+package server
+
+import (
+ "html/template"
+ "log"
+ "net/http"
+
+ mw "pageswiki/internal/server/middleware"
+ routespkg "pageswiki/internal/server/routes"
+
+ "pageswiki/internal/store"
+)
+
+type Server struct {
+ mux *http.ServeMux
+ templates *template.Template
+ store *store.Store
+}
+
+func New(
+ st *store.Store,
+) *Server {
+
+ s := &Server{
+ mux: http.NewServeMux(),
+ store: st,
+ }
+
+ s.mustLoadTemplates()
+
+ s.registerStaticRoutes()
+
+ s.mux.HandleFunc(
+ "/o/",
+ s.handleObjectRoute,
+ )
+
+ s.mux.HandleFunc(
+ "/r/history/",
+ s.handleRevisionBrowser,
+ )
+
+ s.mux.HandleFunc(
+ "/r/view/",
+ s.handleRevisionView,
+ )
+
+ s.mux.HandleFunc(
+ "/r/diff/",
+ s.handleRevisionDiff,
+ )
+
+ s.registerRoutes()
+
+ return s
+}
+
+func (s *Server) registerStaticRoutes() {
+
+ staticFS := http.FileServer(
+ http.Dir("./static"),
+ )
+
+ s.mux.Handle(
+ "/static/",
+ http.StripPrefix(
+ "/static/",
+ staticFS,
+ ),
+ )
+}
+
+func (s *Server) mustLoadTemplates() {
+
+ funcs := template.FuncMap{
+
+ "parentPath": parentPath,
+
+ "sub": func(a, b int) int {
+ return a - b
+ },
+
+ "add": func(a, b int) int {
+ return a + b
+ },
+
+ "until": func(n int) []int {
+
+ out := make([]int, n)
+
+ for i := 0; i < n; i++ {
+ out[i] = i
+ }
+
+ return out
+ },
+ }
+
+ tmpl := template.New("").Funcs(funcs)
+
+ parsed, err := tmpl.ParseGlob(
+ "templates/**/*.gohtml",
+ )
+
+ if err != nil {
+ panic(err)
+ }
+
+ s.templates = parsed
+}
+
+func (s *Server) registerRoutes() {
+
+ routespkg.RegisterUIRoutes(
+ s.mux,
+ routespkg.UIHandlers{
+ Home: s.handleHome,
+ NewPage: s.handleNewPage,
+ SemanticEditor: s.handleSemanticEditor,
+ SemanticPage: s.handleSemanticRoute,
+ RawView: s.handleRawView,
+ LinkManager: s.handleLinkManager,
+ Health: s.handleHealth,
+ Tree: s.handleTree,
+ },
+ )
+
+ routespkg.RegisterAPIRoutes(
+ s.mux,
+ routespkg.APIHandlers{
+ CreateObject: s.handleCreateObjectAPI,
+ ListObjects: s.handleListObjectsAPI,
+ SaveRevision: s.handleSaveRevisionAPI,
+ ListRevisions: s.handleRevisionListAPI,
+ RestoreRevision: s.handleRestoreRevisionAPI,
+ RenderMarkdown: s.handleMarkdownRenderAPI,
+ AddTag: s.handleTagAddAPI,
+ BindPath: s.handleBindPathAPI,
+ RenamePath: s.handleRenamePath,
+ RenamePreview: s.handleRenamePreview,
+ RemovePath: s.handleRemovePathAPI,
+ },
+ )
+}
+
+func (s *Server) handler() http.Handler {
+
+ var h http.Handler = s.mux
+
+ h = mw.NormalizePath(h)
+ h = mw.RequestID(h)
+ h = mw.Logging(h)
+ h = mw.Recovery(h)
+
+ return h
+}
+
+func (s *Server) Run(addr string) error {
+
+ log.Printf(
+ "listen %s",
+ addr,
+ )
+
+ return http.ListenAndServe(
+ addr,
+ s.handler(),
+ )
+}
diff --git a/internal/server/server_revision_routes.txt b/internal/server/server_revision_routes.txt
new file mode 100644
index 0000000..5c77567
--- /dev/null
+++ b/internal/server/server_revision_routes.txt
@@ -0,0 +1,16 @@
+REGISTER BEFORE semantic catch-all:
+
+s.mux.HandleFunc(
+ "/r/history/",
+ s.handleRevisionBrowser,
+)
+
+s.mux.HandleFunc(
+ "/r/view/",
+ s.handleRevisionView,
+)
+
+s.mux.HandleFunc(
+ "/r/diff/",
+ s.handleRevisionDiff,
+)
diff --git a/internal/server/tag_api.go b/internal/server/tag_api.go
new file mode 100644
index 0000000..89839f3
--- /dev/null
+++ b/internal/server/tag_api.go
@@ -0,0 +1,37 @@
+package server
+
+import (
+ "encoding/json"
+ "net/http"
+)
+
+func (s *Server) handleTagAddAPI(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ var req struct {
+ ObjectUUID string `json:"object_uuid"`
+ Tag string `json:"tag"`
+ }
+
+ err := json.NewDecoder(r.Body).Decode(&req)
+ if err != nil {
+ http.Error(w, err.Error(), 400)
+ return
+ }
+
+ err = s.store.AddTag(
+ req.ObjectUUID,
+ req.Tag,
+ )
+
+ if err != nil {
+ http.Error(w, err.Error(), 500)
+ return
+ }
+
+ _ = json.NewEncoder(w).Encode(map[string]any{
+ "status": "ok",
+ })
+}
diff --git a/internal/server/template_funcs.go b/internal/server/template_funcs.go
new file mode 100644
index 0000000..229b065
--- /dev/null
+++ b/internal/server/template_funcs.go
@@ -0,0 +1,54 @@
+package server
+
+import (
+ "html/template"
+ "strings"
+ "time"
+)
+
+func templateFuncMap() template.FuncMap {
+
+ return template.FuncMap{
+
+ "safeHTML": func(
+ s string,
+ ) template.HTML {
+
+ return template.HTML(s)
+ },
+
+ "formatTime": func(
+ ts int64,
+ ) string {
+
+ return time.Unix(
+ ts,
+ 0,
+ ).Format(time.RFC3339)
+ },
+
+ "parentPath": func(
+ p string,
+ ) string {
+
+ parts :=
+ strings.Split(
+ strings.Trim(p, "/"),
+ "/",
+ )
+
+ if len(parts) <= 1 {
+ return "/"
+ }
+
+ parts =
+ parts[:len(parts)-1]
+
+ return "/" +
+ strings.Join(
+ parts,
+ "/",
+ )
+ },
+ }
+}
diff --git a/internal/server/tree_handler.go b/internal/server/tree_handler.go
new file mode 100644
index 0000000..5ada158
--- /dev/null
+++ b/internal/server/tree_handler.go
@@ -0,0 +1,74 @@
+package server
+
+import (
+ "net/http"
+ "strings"
+
+ "pageswiki/internal/store"
+)
+
+type TreeViewNode struct {
+ Name string
+ Path string
+ Depth int
+ IsDir bool
+ IsDraft bool
+ ChildCount int
+}
+
+func (s *Server) handleTree(
+ w http.ResponseWriter,
+ r *http.Request,
+) {
+
+ tree, err :=
+ s.store.BuildPathTree()
+
+ if err != nil {
+
+ http.Error(
+ w,
+ err.Error(),
+ 500,
+ )
+
+ return
+ }
+
+ var flattened []store.FlatTreeNode
+
+ store.FlattenTree(
+ tree,
+ 0,
+ &flattened,
+ )
+
+ var nodes []TreeViewNode
+
+ for _, n := range flattened {
+
+ nodes = append(
+ nodes,
+ TreeViewNode{
+ Name: n.Name,
+ Path: n.FullPath,
+ Depth: n.Depth,
+ IsDir: n.IsDir,
+ ChildCount: n.ChildCount,
+
+ IsDraft: strings.HasPrefix(
+ n.FullPath,
+ "/draft/",
+ ),
+ },
+ )
+ }
+
+ s.render(
+ w,
+ "tree.gohtml",
+ map[string]any{
+ "Nodes": nodes,
+ },
+ )
+}
diff --git a/internal/service/page_service.go b/internal/service/page_service.go
new file mode 100644
index 0000000..725edd2
--- /dev/null
+++ b/internal/service/page_service.go
@@ -0,0 +1,43 @@
+package service
+
+import (
+ "html/template"
+
+ "pageswiki/internal/render"
+ "pageswiki/internal/store"
+)
+
+type Breadcrumb struct {
+ Name string
+ Path string
+}
+
+type PageView struct {
+ Path string
+ Body string
+ HTML template.HTML
+ Tags []string
+ Breadcrumbs []Breadcrumb
+}
+
+type PageService struct {
+ Store *store.Store
+}
+
+func NewPageService(
+ st *store.Store,
+) *PageService {
+
+ return &PageService{
+ Store: st,
+ }
+}
+
+func (s *PageService) RenderHTML(
+ markdown string,
+) template.HTML {
+
+ return render.SafeHTML(
+ render.Markdown(markdown),
+ )
+}
diff --git a/internal/store/create_object.go b/internal/store/create_object.go
new file mode 100644
index 0000000..7fceba0
--- /dev/null
+++ b/internal/store/create_object.go
@@ -0,0 +1,51 @@
+package store
+
+import (
+ "github.com/google/uuid"
+)
+
+func (s *Store) CreateObject(
+ path string,
+) (string, error) {
+
+ objectUUID :=
+ uuid.NewString()
+
+ _, err := s.DB.Exec(`
+ INSERT INTO objects (
+ uuid,
+ created_at
+ )
+ VALUES (
+ ?,
+ strftime('%s','now')
+ )
+ `,
+ objectUUID,
+ )
+
+ if err != nil {
+ return "", err
+ }
+
+ _, err = s.DB.Exec(`
+ INSERT INTO paths (
+ path,
+ object_uuid,
+ created_at
+ )
+ VALUES (
+ ?, ?,
+ strftime('%s','now')
+ )
+ `,
+ path,
+ objectUUID,
+ )
+
+ if err != nil {
+ return "", err
+ }
+
+ return objectUUID, nil
+}
diff --git a/internal/store/list_children.go b/internal/store/list_children.go
new file mode 100644
index 0000000..9c3ab50
--- /dev/null
+++ b/internal/store/list_children.go
@@ -0,0 +1,88 @@
+package store
+
+import "strings"
+
+func (s *Store) ListChildPaths(
+ parent string,
+) ([]string, error) {
+
+ if parent == "/" {
+ parent = ""
+ }
+
+ rows, err := s.DB.Query(`
+ SELECT path
+ FROM paths
+ ORDER BY path ASC
+ `)
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer rows.Close()
+
+ var out []string
+
+ for rows.Next() {
+
+ var path string
+
+ err := rows.Scan(
+ &path,
+ )
+
+ if err != nil {
+ return nil, err
+ }
+
+ if parent != "" {
+
+ if !strings.HasPrefix(
+ path,
+ parent+"/",
+ ) {
+ continue
+ }
+
+ } else {
+
+ if !strings.HasPrefix(
+ path,
+ "/",
+ ) {
+ continue
+ }
+ }
+
+ trimmed :=
+ strings.TrimPrefix(
+ path,
+ parent,
+ )
+
+ trimmed =
+ strings.TrimPrefix(
+ trimmed,
+ "/",
+ )
+
+ if trimmed == "" {
+ continue
+ }
+
+ if strings.Contains(
+ trimmed,
+ "/",
+ ) {
+ continue
+ }
+
+ out = append(
+ out,
+ path,
+ )
+ }
+
+ return out, nil
+}
diff --git a/internal/store/list_semantic_objects.go b/internal/store/list_semantic_objects.go
new file mode 100644
index 0000000..dba41b6
--- /dev/null
+++ b/internal/store/list_semantic_objects.go
@@ -0,0 +1,51 @@
+package store
+
+import "strings"
+
+type SemanticObject struct {
+ UUID string
+ Path string
+ Kind string
+}
+
+func (s *Store) ListSemanticObjects() (
+ []SemanticObject,
+ error,
+) {
+
+ objects, err := s.ListObjects()
+
+ if err != nil {
+ return nil, err
+ }
+
+ var out []SemanticObject
+
+ for _, o := range objects {
+
+ if strings.HasPrefix(
+ o.UUID,
+ "/system/",
+ ) {
+ continue
+ }
+
+ if strings.HasPrefix(
+ o.UUID,
+ "/o/",
+ ) {
+ continue
+ }
+
+ out = append(
+ out,
+ SemanticObject{
+ UUID: o.UUID,
+ Path: o.UUID,
+ Kind: o.Kind,
+ },
+ )
+ }
+
+ return out, nil
+}
diff --git a/internal/store/objects.go b/internal/store/objects.go
new file mode 100644
index 0000000..1d0bfcf
--- /dev/null
+++ b/internal/store/objects.go
@@ -0,0 +1,46 @@
+package store
+
+type Object struct {
+ UUID string
+ Kind string
+ CreatedAt int64
+}
+
+func (s *Store) ListObjects() ([]Object, error) {
+
+ rows, err := s.DB.Query(`
+ SELECT
+ uuid,
+ COALESCE(kind, '') AS kind,
+ created_at
+ FROM objects
+ ORDER BY created_at DESC
+ `)
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer rows.Close()
+
+ var out []Object
+
+ for rows.Next() {
+
+ var o Object
+
+ err := rows.Scan(
+ &o.UUID,
+ &o.Kind,
+ &o.CreatedAt,
+ )
+
+ if err != nil {
+ return nil, err
+ }
+
+ out = append(out, o)
+ }
+
+ return out, nil
+}
diff --git a/internal/store/path_mutation.go b/internal/store/path_mutation.go
new file mode 100644
index 0000000..73ad563
--- /dev/null
+++ b/internal/store/path_mutation.go
@@ -0,0 +1,32 @@
+package store
+
+func (s *Store) RenamePath(
+ oldPath string,
+ newPath string,
+) error {
+
+ _, err := s.DB.Exec(`
+ UPDATE paths
+ SET path = ?
+ WHERE path = ?
+ `,
+ newPath,
+ oldPath,
+ )
+
+ return err
+}
+
+func (s *Store) RemovePath(
+ path string,
+) error {
+
+ _, err := s.DB.Exec(`
+ DELETE FROM paths
+ WHERE path = ?
+ `,
+ path,
+ )
+
+ return err
+}
diff --git a/internal/store/paths.go b/internal/store/paths.go
new file mode 100644
index 0000000..dc5ddfb
--- /dev/null
+++ b/internal/store/paths.go
@@ -0,0 +1,146 @@
+package store
+
+import (
+ "database/sql"
+ "time"
+)
+
+func (s *Store) BindPath(
+ path string,
+ objectUUID string,
+) error {
+
+ _, err := s.DB.Exec(`
+ INSERT OR REPLACE INTO paths (
+ path,
+ object_uuid,
+ created_at
+ ) VALUES (?, ?, ?)
+ `,
+ path,
+ objectUUID,
+ time.Now().Unix(),
+ )
+
+ return err
+}
+
+func (s *Store) ResolvePath(
+ path string,
+) (string, error) {
+
+ row := s.DB.QueryRow(`
+ SELECT object_uuid
+ FROM paths
+ WHERE path = ?
+ `, path)
+
+ var objectUUID string
+
+ err := row.Scan(&objectUUID)
+ if err != nil {
+ return "", err
+ }
+
+ return objectUUID, nil
+}
+
+func (s *Store) ListChildren(
+ prefix string,
+) ([]string, error) {
+
+ rows, err := s.DB.Query(`
+ SELECT path
+ FROM paths
+ WHERE path LIKE ?
+ ORDER BY path
+ `,
+ prefix+"/%",
+ )
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer rows.Close()
+
+ var out []string
+
+ for rows.Next() {
+
+ var p string
+
+ err := rows.Scan(&p)
+ if err != nil {
+ return nil, err
+ }
+
+ out = append(out, p)
+ }
+
+ return out, nil
+}
+
+func (s *Store) PathExists(
+ path string,
+) bool {
+
+ row := s.DB.QueryRow(`
+ SELECT COUNT(*)
+ FROM paths
+ WHERE path = ?
+ `, path)
+
+ var count int
+
+ _ = row.Scan(&count)
+
+ return count > 0
+}
+
+func (s *Store) CreatePageAtPath(
+ path string,
+) (string, error) {
+
+ objectUUID, err := s.CreateObject("flow")
+
+ if err != nil {
+ return "", err
+ }
+
+ err = s.BindPath(
+ path,
+ objectUUID,
+ )
+
+ if err != nil {
+ return "", err
+ }
+
+ return objectUUID, nil
+}
+
+func (s *Store) GetPathByUUID(
+ uuid string,
+) (string, error) {
+
+ row := s.DB.QueryRow(`
+ SELECT path
+ FROM paths
+ WHERE object_uuid = ?
+ LIMIT 1
+ `, uuid)
+
+ var path string
+
+ err := row.Scan(&path)
+ if err != nil {
+ return "", err
+ }
+
+ return path, nil
+}
+
+func IsNotFound(err error) bool {
+ return err == sql.ErrNoRows
+}
diff --git a/internal/store/revision_store.go b/internal/store/revision_store.go
new file mode 100644
index 0000000..7597299
--- /dev/null
+++ b/internal/store/revision_store.go
@@ -0,0 +1,140 @@
+package store
+
+import (
+ "crypto/sha256"
+ "database/sql"
+ "encoding/hex"
+)
+
+type Revision struct {
+ Hash string
+ ObjectUUID string
+ Body string
+ Message string
+ CreatedAt int64
+}
+
+func revisionHash(
+ body string,
+) string {
+
+ sum := sha256.Sum256(
+ []byte(body),
+ )
+
+ return hex.EncodeToString(
+ sum[:],
+ )
+}
+
+func (s *Store) SaveRevision(
+ objectUUID string,
+ body string,
+ message string,
+) (string, error) {
+
+ hash := revisionHash(body)
+
+ _, err := s.DB.Exec(`
+ INSERT OR IGNORE INTO revisions (
+ uuid,
+ object_uuid,
+ body,
+ message,
+ created_at
+ )
+ VALUES (
+ ?, ?, ?, ?,
+ strftime('%s','now')
+ )
+ `,
+ hash,
+ objectUUID,
+ body,
+ message,
+ )
+
+ if err != nil {
+ return "", err
+ }
+
+ return hash, nil
+}
+
+func (s *Store) GetRevision(
+ hash string,
+) (*Revision, error) {
+
+ row := s.DB.QueryRow(`
+ SELECT
+ uuid,
+ object_uuid,
+ body,
+ message,
+ created_at
+ FROM revisions
+ WHERE uuid = ?
+ `,
+ hash,
+ )
+
+ var r Revision
+
+ err := row.Scan(
+ &r.Hash,
+ &r.ObjectUUID,
+ &r.Body,
+ &r.Message,
+ &r.CreatedAt,
+ )
+
+ if err != nil {
+ return nil, err
+ }
+
+ return &r, nil
+}
+
+func (s *Store) GetLatestRevision(
+ objectUUID string,
+) (*Revision, error) {
+
+ row := s.DB.QueryRow(`
+ SELECT
+ uuid,
+ object_uuid,
+ body,
+ message,
+ created_at
+ FROM revisions
+ WHERE object_uuid = ?
+ ORDER BY created_at DESC
+ LIMIT 1
+ `,
+ objectUUID,
+ )
+
+ var r Revision
+
+ err := row.Scan(
+ &r.Hash,
+ &r.ObjectUUID,
+ &r.Body,
+ &r.Message,
+ &r.CreatedAt,
+ )
+
+ if err != nil {
+
+ if err == sql.ErrNoRows {
+
+ return &Revision{
+ ObjectUUID: objectUUID,
+ }, nil
+ }
+
+ return nil, err
+ }
+
+ return &r, nil
+}
diff --git a/internal/store/revisions.go b/internal/store/revisions.go
new file mode 100644
index 0000000..17d8971
--- /dev/null
+++ b/internal/store/revisions.go
@@ -0,0 +1,54 @@
+package store
+
+type RevisionListItem struct {
+ Hash string
+ ObjectUUID string
+ Message string
+ CreatedAt int64
+}
+
+func (s *Store) ListRevisions(
+ objectUUID string,
+) ([]RevisionListItem, error) {
+
+ rows, err := s.DB.Query(`
+ SELECT
+ uuid,
+ object_uuid,
+ message,
+ created_at
+ FROM revisions
+ WHERE object_uuid = ?
+ ORDER BY created_at DESC
+ `,
+ objectUUID,
+ )
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer rows.Close()
+
+ var out []RevisionListItem
+
+ for rows.Next() {
+
+ var r RevisionListItem
+
+ err = rows.Scan(
+ &r.Hash,
+ &r.ObjectUUID,
+ &r.Message,
+ &r.CreatedAt,
+ )
+
+ if err != nil {
+ return nil, err
+ }
+
+ out = append(out, r)
+ }
+
+ return out, nil
+}
diff --git a/internal/store/store.go b/internal/store/store.go
new file mode 100644
index 0000000..46ab585
--- /dev/null
+++ b/internal/store/store.go
@@ -0,0 +1,16 @@
+package store
+
+import "database/sql"
+
+type Store struct {
+ DB *sql.DB
+}
+
+func New(
+ db *sql.DB,
+) *Store {
+
+ return &Store{
+ DB: db,
+ }
+}
diff --git a/internal/store/tags.go b/internal/store/tags.go
new file mode 100644
index 0000000..9050135
--- /dev/null
+++ b/internal/store/tags.go
@@ -0,0 +1,53 @@
+package store
+
+func (s *Store) AddTag(
+ objectUUID string,
+ tag string,
+) error {
+
+ _, err := s.DB.Exec(`
+ INSERT INTO tags (
+ object_uuid,
+ tag
+ ) VALUES (?, ?)
+ `,
+ objectUUID,
+ tag,
+ )
+
+ return err
+}
+
+func (s *Store) ListTags(
+ objectUUID string,
+) ([]string, error) {
+
+ rows, err := s.DB.Query(`
+ SELECT tag
+ FROM tags
+ WHERE object_uuid = ?
+ ORDER BY tag
+ `, objectUUID)
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer rows.Close()
+
+ var out []string
+
+ for rows.Next() {
+
+ var tag string
+
+ err := rows.Scan(&tag)
+ if err != nil {
+ return nil, err
+ }
+
+ out = append(out, tag)
+ }
+
+ return out, nil
+}
diff --git a/internal/store/tree.go b/internal/store/tree.go
new file mode 100644
index 0000000..c641be6
--- /dev/null
+++ b/internal/store/tree.go
@@ -0,0 +1,152 @@
+package store
+
+import (
+ "sort"
+ "strings"
+)
+
+type TreeNode struct {
+ Name string
+ FullPath string
+ Children map[string]*TreeNode
+ IsDir bool
+ ChildCount int
+}
+
+type FlatTreeNode struct {
+ Name string
+ FullPath string
+ Depth int
+ IsDir bool
+ ChildCount int
+}
+
+func (s *Store) BuildPathTree() (*TreeNode, error) {
+
+ rows, err := s.DB.Query(`
+ SELECT path
+ FROM paths
+ WHERE path LIKE '/%'
+ ORDER BY path ASC
+ `)
+
+ if err != nil {
+ return nil, err
+ }
+
+ defer rows.Close()
+
+ root := &TreeNode{
+ Name: "/",
+ FullPath: "/",
+ Children: map[string]*TreeNode{},
+ IsDir: true,
+ }
+
+ for rows.Next() {
+
+ var path string
+
+ err := rows.Scan(
+ &path,
+ )
+
+ if err != nil {
+ return nil, err
+ }
+
+ parts :=
+ strings.Split(
+ strings.TrimPrefix(
+ path,
+ "/",
+ ),
+ "/",
+ )
+
+ current := root
+ var pathBuilder strings.Builder
+
+ for i, part := range parts {
+
+ pathBuilder.WriteString("/")
+ pathBuilder.WriteString(part)
+ currentPath := pathBuilder.String()
+
+ child, ok :=
+ current.Children[part]
+
+ if !ok {
+
+ child = &TreeNode{
+ Name: part,
+ FullPath: currentPath,
+ Children: map[string]*TreeNode{},
+ }
+
+ current.Children[part] =
+ child
+ }
+
+ if i != len(parts)-1 {
+ child.IsDir = true
+ }
+
+ current = child
+ }
+ }
+
+ var walk func(*TreeNode)
+
+ walk = func(n *TreeNode) {
+
+ n.ChildCount =
+ len(n.Children)
+
+ for _, c := range n.Children {
+ walk(c)
+ }
+ }
+
+ walk(root)
+
+ return root, nil
+}
+
+func FlattenTree(
+ node *TreeNode,
+ depth int,
+ out *[]FlatTreeNode,
+) {
+
+ if node.FullPath != "/" {
+
+ *out = append(
+ *out,
+ FlatTreeNode{
+ Name: node.Name,
+ FullPath: node.FullPath,
+ Depth: depth,
+ IsDir: node.IsDir,
+ ChildCount: node.ChildCount,
+ },
+ )
+ }
+
+ keys := make([]string, 0)
+
+ for k := range node.Children {
+ keys = append(keys, k)
+ }
+
+ sort.Strings(keys)
+
+ for _, k := range keys {
+
+ FlattenTree(
+ node.Children[k],
+ depth+1,
+ out,
+ )
+ }
+}
diff --git a/static/css/dialog.css b/static/css/dialog.css
new file mode 100644
index 0000000..9db1546
--- /dev/null
+++ b/static/css/dialog.css
@@ -0,0 +1,24 @@
+.dialog {
+ width: min(800px, 90vw);
+ border: 1px solid #333;
+ background: #1b1b1b;
+ color: #eee;
+}
+
+.dialog-body {
+ padding: 1rem;
+}
+
+.search-input {
+ width: 100%;
+ padding: 0.75rem;
+ background: #111;
+ color: #eee;
+ border: 1px solid #333;
+}
+
+.search-results {
+ margin-top: 1rem;
+ list-style: none;
+ padding: 0;
+}
diff --git a/static/css/explorer.css b/static/css/explorer.css
new file mode 100644
index 0000000..95832cc
--- /dev/null
+++ b/static/css/explorer.css
@@ -0,0 +1,10 @@
+.tree {
+ list-style: none;
+ margin-left: 1rem;
+ padding-left: 1rem;
+ border-left: 1px solid #333;
+}
+
+.tree li {
+ margin: 0.4rem 0;
+}
diff --git a/static/css/main.css b/static/css/main.css
new file mode 100644
index 0000000..360e00c
--- /dev/null
+++ b/static/css/main.css
@@ -0,0 +1,53 @@
+body {
+ background: #111;
+ color: #eee;
+ font-family: sans-serif;
+ margin: 0;
+}
+
+.topbar {
+ display: flex;
+ justify-content: space-between;
+ padding: 1rem;
+ border-bottom: 1px solid #333;
+}
+
+.topbar a {
+ color: #9ecbff;
+ text-decoration: none;
+ margin-right: 1rem;
+}
+
+.container {
+ padding: 1rem;
+}
+
+.card {
+ border: 1px solid #333;
+ background: #1b1b1b;
+ padding: 1rem;
+ margin-bottom: 1rem;
+}
+
+.editor-grid {
+ display: grid;
+ grid-template-columns: 1fr 1fr;
+ gap: 1rem;
+}
+
+.editor {
+ width: 100%;
+ min-height: 70vh;
+ background: #111;
+ color: #eee;
+}
+
+.preview {
+ border: 1px solid #333;
+ padding: 1rem;
+ overflow: auto;
+}
+
+.page-html {
+ line-height: 1.8;
+}
diff --git a/static/css/modes.css b/static/css/modes.css
new file mode 100644
index 0000000..5fe1deb
--- /dev/null
+++ b/static/css/modes.css
@@ -0,0 +1,7 @@
+body.mode-editor .page-html {
+ display: none;
+}
+
+body.mode-view textarea.editor {
+ display: none;
+}
diff --git a/static/css/revisions.css b/static/css/revisions.css
new file mode 100644
index 0000000..1f9f94a
--- /dev/null
+++ b/static/css/revisions.css
@@ -0,0 +1,55 @@
+.diff-view {
+ margin: 0;
+ padding: 0;
+ white-space: pre-wrap;
+ font-family: monospace;
+ line-height: 1.0;
+}
+
+.diff-view div {
+ margin: 0;
+ padding: 0;
+ line-height: 1.0;
+}
+
+.diff-same {
+ color: #888;
+}
+
+.diff-add {
+ color: #7CFC7C;
+ opacity: 0.92;
+}
+
+.diff-del {
+ color: #FF7C7C;
+ opacity: 0.92;
+}
+
+.page-html {
+ line-height: 1.7;
+}
+
+.revision-textarea {
+ width: 100%;
+ min-height: 50vh;
+ background: #111;
+ color: #eee;
+ border: 1px solid #333;
+ padding: 1rem;
+ font-family: monospace;
+ white-space: pre;
+ margin-top: 1rem;
+}
+
+details summary {
+ cursor: pointer;
+ user-select: none;
+}
+
+.diff-line-no {
+ display: inline-block;
+ width: 4em;
+ color: #666;
+ user-select: none;
+}
diff --git a/static/js/app.js b/static/js/app.js
new file mode 100644
index 0000000..89cc3a7
--- /dev/null
+++ b/static/js/app.js
@@ -0,0 +1,163 @@
+let dirty = false
+
+async function renderMarkdownPreview() {
+
+ const editor =
+ document.getElementById(
+ "editor",
+ )
+
+ const preview =
+ document.getElementById(
+ "preview",
+ )
+
+ if (!editor || !preview) {
+ return
+ }
+
+ const res = await fetch(
+ "/_/api/v1/render/markdown",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type":
+ "application/json",
+ },
+ body: JSON.stringify({
+ markdown:
+ editor.value,
+ }),
+ },
+ )
+
+ const data =
+ await res.json()
+
+ preview.innerHTML =
+ data.html
+}
+
+async function restoreRevision(
+ revisionUUID,
+) {
+
+ const res = await fetch(
+ "/_/api/v1/revisions/restore?revision="
+ + revisionUUID,
+ )
+
+ if (!res.ok) {
+ alert("restore failed")
+ return
+ }
+
+ location.reload()
+}
+
+async function openRevisionDialog() {
+
+ const objectUUID =
+ document.getElementById(
+ "object-uuid",
+ ).value
+
+ const res = await fetch(
+ "/_/api/v1/revisions/list?uuid="
+ + objectUUID,
+ )
+
+ const revisions =
+ await res.json()
+
+ const root =
+ document.getElementById(
+ "revision-list",
+ )
+
+ root.innerHTML = ""
+
+ revisions.forEach((r) => {
+
+ const div =
+ document.createElement("div")
+
+ div.className =
+ "revision-item"
+
+ const ts =
+ new Date(
+ r.created_at * 1000,
+ )
+
+ div.innerHTML =
+ ""
+ + r.uuid
+ + " "
+ + ts.toLocaleString()
+ + " "
+ + r.message
+ + "Restore "
+
+ root.appendChild(div)
+ })
+
+ document.getElementById(
+ "revision-dialog",
+ ).showModal()
+}
+
+window.addEventListener(
+ "beforeunload",
+ (ev) => {
+
+ if (!dirty) {
+ return
+ }
+
+ ev.preventDefault()
+ },
+)
+
+document.addEventListener(
+ "DOMContentLoaded",
+ () => {
+
+ const editor =
+ document.getElementById(
+ "editor",
+ )
+
+ if (editor) {
+
+ renderMarkdownPreview()
+
+ editor.addEventListener(
+ "input",
+ () => {
+
+ dirty = true
+
+ renderMarkdownPreview()
+ },
+ )
+
+ setInterval(
+ () => {
+
+ if (!dirty) {
+ return
+ }
+
+ saveRevision()
+
+ dirty = false
+
+ },
+ 30000,
+ )
+ }
+ },
+)
diff --git a/static/js/editor.js b/static/js/editor.js
new file mode 100644
index 0000000..b3434c7
--- /dev/null
+++ b/static/js/editor.js
@@ -0,0 +1,315 @@
+window.PagesEditor = {
+
+ autosaveTimer: null,
+
+ init() {
+
+ const editor =
+ document.getElementById(
+ "editor",
+ )
+
+ const preview =
+ document.getElementById(
+ "preview",
+ )
+
+ const editType =
+ document.getElementById(
+ "edit-type",
+ )
+
+ if (
+ !editor
+ ||
+ !preview
+ ) {
+ return
+ }
+
+ const renderPreview =
+ async () => {
+
+ if (
+ editType.value
+ ===
+ "html"
+ ) {
+
+ preview.innerHTML =
+ editor.value
+
+ return editor.value
+ }
+
+ const res =
+ await fetch(
+ "/_/api/v1/render/markdown",
+ {
+ method: "POST",
+
+ headers: {
+ "Content-Type":
+ "application/json",
+ },
+
+ body: JSON.stringify({
+ markdown:
+ editor.value,
+ }),
+ },
+ )
+
+ if (!res.ok) {
+
+ preview.innerText =
+ editor.value
+
+ return editor.value
+ }
+
+ const data =
+ await res.json()
+
+ preview.innerHTML =
+ data.html
+
+ return data.html
+ }
+
+ editor.addEventListener(
+ "input",
+ async () => {
+
+ await renderPreview()
+
+ clearTimeout(
+ this.autosaveTimer,
+ )
+
+ this.autosaveTimer =
+ setTimeout(
+ () => {
+ this.autosave()
+ },
+ 3000,
+ )
+ },
+ )
+
+ document.addEventListener(
+ "keydown",
+ (ev) => {
+
+ if (
+ (ev.ctrlKey || ev.metaKey)
+ &&
+ ev.key === "s"
+ ) {
+
+ ev.preventDefault()
+
+ this.saveNow()
+ }
+ },
+ )
+
+ renderPreview()
+ },
+
+ async getCanonicalHTML() {
+
+ const editor =
+ document.getElementById(
+ "editor",
+ )
+
+ const editType =
+ document.getElementById(
+ "edit-type",
+ )
+
+ if (
+ editType.value
+ ===
+ "html"
+ ) {
+
+ return editor.value
+ }
+
+ const res =
+ await fetch(
+ "/_/api/v1/render/markdown",
+ {
+ method: "POST",
+
+ headers: {
+ "Content-Type":
+ "application/json",
+ },
+
+ body: JSON.stringify({
+ markdown:
+ editor.value,
+ }),
+ },
+ )
+
+ if (!res.ok) {
+ return editor.value
+ }
+
+ const data =
+ await res.json()
+
+ return data.html
+ },
+
+ async autosave() {
+
+ const objectUUID =
+ document.getElementById(
+ "object-uuid",
+ )
+
+ if (
+ !objectUUID
+ ||
+ !objectUUID.value
+ ) {
+ return
+ }
+
+ const canonicalHTML =
+ await this.getCanonicalHTML()
+
+ await fetch(
+ "/_/api/v1/revisions/save",
+ {
+ method: "POST",
+
+ headers: {
+ "Content-Type":
+ "application/json",
+ },
+
+ body: JSON.stringify({
+ object_uuid:
+ objectUUID.value,
+
+ body:
+ canonicalHTML,
+
+ message:
+ "autosave",
+ }),
+ },
+ )
+ },
+
+ async saveNow() {
+
+ const objectUUID =
+ document.getElementById(
+ "object-uuid",
+ )
+
+ if (
+ !objectUUID
+ ||
+ !objectUUID.value
+ ) {
+ return
+ }
+
+ const canonicalHTML =
+ await this.getCanonicalHTML()
+
+ const res =
+ await fetch(
+ "/_/api/v1/revisions/save",
+ {
+ method: "POST",
+
+ headers: {
+ "Content-Type":
+ "application/json",
+ },
+
+ body: JSON.stringify({
+ object_uuid:
+ objectUUID.value,
+
+ body:
+ canonicalHTML,
+
+ message:
+ "manual-save",
+ }),
+ },
+ )
+
+ if (!res.ok) {
+
+ alert(
+ "save failed",
+ )
+
+ return
+ }
+
+ alert(
+ "saved",
+ )
+ },
+}
+
+document.addEventListener(
+ "DOMContentLoaded",
+ () => {
+
+ if (
+ document.body.classList.contains(
+ "mode-editor",
+ )
+ ) {
+
+ PagesEditor.init()
+ }
+ },
+)
+
+document.addEventListener(
+ "DOMContentLoaded",
+ () => {
+
+ const sel =
+ document.getElementById(
+ "editor-type",
+ )
+
+ if (!sel) {
+ return
+ }
+
+ sel.addEventListener(
+ "change",
+ () => {
+
+ const u =
+ new URL(
+ location.href,
+ )
+
+ u.searchParams.set(
+ "edittype",
+ sel.value,
+ )
+
+ location.href =
+ u.toString()
+ },
+ )
+ },
+)
diff --git a/static/js/navigation.js b/static/js/navigation.js
new file mode 100644
index 0000000..f53b8e4
--- /dev/null
+++ b/static/js/navigation.js
@@ -0,0 +1,50 @@
+console.log("navigation.js loaded")
+
+function createChildPage() {
+ const name = prompt("child page name")
+ if (!name) return
+
+ let path = location.pathname
+ if (!path.endsWith("/")) path += "/"
+
+ location.href = "/e" + path + name
+}
+
+function selectObject(uuid) {
+ const input = document.getElementById("link-object-uuid")
+ if (input) input.value = uuid
+}
+
+async function bindPath() {
+ const objectUUID = document.getElementById("link-object-uuid")?.value
+ const path = document.getElementById("link-path")?.value
+
+ const res = await fetch("/_/api/v1/paths/bind", {
+ method: "POST",
+ headers: {"Content-Type": "application/json"},
+ body: JSON.stringify({object_uuid: objectUUID, path: path}),
+ })
+
+ if (!res.ok) {
+ alert("bind failed")
+ return
+ }
+
+ location.href = path
+}
+
+document.addEventListener("keydown", (ev) => {
+ if (ev.target && ["TEXTAREA", "INPUT"].includes(ev.target.tagName)) return
+
+ if (ev.key === "c") location.href = "/new"
+
+ if (ev.key === "e" && !location.pathname.startsWith("/e/")) {
+ location.href = "/e" + location.pathname
+ }
+
+ if (ev.key === "^") {
+ const parts = location.pathname.split("/").filter(Boolean)
+ parts.pop()
+ location.href = "/" + parts.join("/")
+ }
+})
diff --git a/static/js/path-actions.js b/static/js/path-actions.js
new file mode 100644
index 0000000..6ed5868
--- /dev/null
+++ b/static/js/path-actions.js
@@ -0,0 +1,105 @@
+window.PagesPathActions = {
+
+ async renameCurrentPath() {
+
+ const currentPath =
+ location.pathname.replace(
+ /^\/e/,
+ "",
+ )
+
+ const nextPath =
+ prompt(
+ "Rename path:",
+ currentPath,
+ )
+
+ if (
+ !nextPath
+ ||
+ nextPath === currentPath
+ ) {
+ return
+ }
+
+ const res =
+ await fetch(
+ "/_/api/v1/path/rename",
+ {
+ method: "POST",
+
+ headers: {
+ "Content-Type":
+ "application/json",
+ },
+
+ body: JSON.stringify({
+ old_path:
+ currentPath,
+
+ new_path:
+ nextPath,
+ }),
+ },
+ )
+
+ if (!res.ok) {
+
+ alert(
+ "rename failed",
+ )
+
+ return
+ }
+
+ location.href =
+ "/e" + nextPath
+ },
+
+ async removeCurrentPath() {
+
+ const currentPath =
+ location.pathname.replace(
+ /^\/e/,
+ "",
+ )
+
+ if (
+ !confirm(
+ "Remove path?\n\n" +
+ currentPath,
+ )
+ ) {
+ return
+ }
+
+ const res =
+ await fetch(
+ "/_/api/v1/path/remove",
+ {
+ method: "POST",
+
+ headers: {
+ "Content-Type":
+ "application/json",
+ },
+
+ body: JSON.stringify({
+ path:
+ currentPath,
+ }),
+ },
+ )
+
+ if (!res.ok) {
+
+ alert(
+ "remove failed",
+ )
+
+ return
+ }
+
+ location.href = "/"
+ },
+}
diff --git a/static/js/revisions.js b/static/js/revisions.js
new file mode 100644
index 0000000..9cae3f6
--- /dev/null
+++ b/static/js/revisions.js
@@ -0,0 +1,44 @@
+console.log("revisions.js loaded")
+
+async function restoreRevision(
+ revisionUUID,
+) {
+
+ if (
+ !confirm(
+ "restore revision?"
+ )
+ ) {
+ return
+ }
+
+ const res = await fetch(
+ "/_/api/v1/revisions/restore",
+ {
+ method: "POST",
+ headers: {
+ "Content-Type":
+ "application/json",
+ },
+ body: JSON.stringify({
+ revision_uuid:
+ revisionUUID,
+ }),
+ },
+ )
+
+ if (!res.ok) {
+
+ alert(
+ "restore failed",
+ )
+
+ return
+ }
+
+ alert(
+ "revision restored",
+ )
+
+ location.reload()
+}
diff --git a/static/js/search.js b/static/js/search.js
new file mode 100644
index 0000000..4eb4c96
--- /dev/null
+++ b/static/js/search.js
@@ -0,0 +1 @@
+console.log("search.js loaded")
diff --git a/templates/layouts/base.gohtml b/templates/layouts/base.gohtml
new file mode 100644
index 0000000..7ed3a63
--- /dev/null
+++ b/templates/layouts/base.gohtml
@@ -0,0 +1,60 @@
+{{ define "base" }}
+
+
+
+
+
+
+{{ .Title }}
+
+
+
+
+
+
+
+
+
+
+
+ {{ template "content" . }}
+
+
+{{ template "scripts" . }}
+
+
+
+{{ end }}
+
+{{ define "body-class" }}
+mode-view
+{{ end }}
diff --git a/templates/layouts/base.gohtml.append.txt b/templates/layouts/base.gohtml.append.txt
new file mode 100644
index 0000000..997b3e1
--- /dev/null
+++ b/templates/layouts/base.gohtml.append.txt
@@ -0,0 +1,3 @@
+Insert before
+
+
+
+
+
+
+
+
+{{ .Path }}
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+{{ template "scripts" . }}
diff --git a/templates/layouts/body_class.gohtml b/templates/layouts/body_class.gohtml
new file mode 100644
index 0000000..e1b0ade
--- /dev/null
+++ b/templates/layouts/body_class.gohtml
@@ -0,0 +1,3 @@
+{{ define "body-class" }}
+mode-view
+{{ end }}
diff --git a/templates/layouts/scripts.gohtml b/templates/layouts/scripts.gohtml
new file mode 100644
index 0000000..2cca69b
--- /dev/null
+++ b/templates/layouts/scripts.gohtml
@@ -0,0 +1,8 @@
+{{ define "scripts" }}
+
+
+
+
+
+
+{{ end }}
diff --git a/templates/pages/editor.gohtml b/templates/pages/editor.gohtml
new file mode 100644
index 0000000..ecaf575
--- /dev/null
+++ b/templates/pages/editor.gohtml
@@ -0,0 +1,148 @@
+{{ define "editor.gohtml" }}
+
+
+
+