This commit is contained in:
Anya Tokugawa committed 2026-05-19 21:30:42 +09:00
commit fa6a4c650f
93 files changed
+6555

No files matched your search

+3
View File
@@ -0,0 +1,3 @@
data/
.tmp/
*.sh
+16
View File
@@ -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"]
+1
View File
@@ -0,0 +1 @@
pageswiki
+65
View File
@@ -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)
}
}
+9
View File
@@ -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;
}
}
+18
View File
@@ -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
+24
View File
@@ -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
)
+51
View File
@@ -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=
+23
View File
@@ -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
}
+23
View File
@@ -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,
},
})
}
+79
View File
@@ -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',
?,
'<h1>Pages Wiki</h1><p>Bootstrap complete.</p>',
'bootstrap',
strftime('%s','now')
)
`,
rootUUID,
)
return err
}
+60
View File
@@ -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
}
+91
View File
@@ -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
}
+7
View File
@@ -0,0 +1,7 @@
package object
type Object struct {
UUID string
Kind string
Title string
}
+10
View File
@@ -0,0 +1,10 @@
package render
import "html/template"
func SafeHTML(
input string,
) template.HTML {
return template.HTML(input)
}
+15
View File
@@ -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)
}
+8
View File
@@ -0,0 +1,8 @@
package revision
type Revision struct {
UUID string
ObjectUUID string
Message string
CreatedAt int64
}
+109
View File
@@ -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",
})
}
+76
View File
@@ -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,
},
)
}
+190
View File
@@ -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)
}
+40
View File
@@ -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
}
+67
View File
@@ -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,
},
)
}
+75
View File
@@ -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,
},
)
}
+41
View File
@@ -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,
)
}
+18
View File
@@ -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"),
)
}
+22
View File
@@ -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,
},
)
}
+68
View File
@@ -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(
`<section class="children-list">`,
)
b.WriteString("<ul>")
for _, child := range children {
name :=
strings.TrimPrefix(
child,
currentPath,
)
name =
strings.TrimPrefix(
name,
"/",
)
b.WriteString(
fmt.Sprintf(
`<li><a href="%s">%s</a></li>`,
child,
name,
),
)
}
b.WriteString("</ul>")
b.WriteString("</section>")
body = strings.ReplaceAll(
body,
"{{children}}",
b.String(),
)
}
}
return body
}
+37
View File
@@ -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)
})
}
+31
View File
@@ -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),
)
},
)
}
+53
View File
@@ -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)
},
)
}
+38
View File
@@ -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)
},
)
}
+43
View File
@@ -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),
)
},
)
}
+103
View File
@@ -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,
)
}
+37
View File
@@ -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",
})
}
+96
View File
@@ -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,
)
}
+48
View File
@@ -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),
)
}
@@ -0,0 +1,3 @@
package server
func init() {}
+38
View File
@@ -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
}
}
+28
View File
@@ -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),
})
}
+64
View File
@@ -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)
}
+43
View File
@@ -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,
},
)
}
+56
View File
@@ -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"))
}
+215
View File
@@ -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,
`<pre class="diff-view">`,
)
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(
`<div class="diff-same"><span class="diff-line-no">%4d</span> %s</div>`,
lineNo,
html.EscapeString(a),
),
)
default:
if b != "" {
out = append(
out,
fmt.Sprintf(
`<div class="diff-del"><span class="diff-line-no">%4d</span> - %s</div>`,
lineNo,
html.EscapeString(b),
),
)
}
if a != "" {
out = append(
out,
fmt.Sprintf(
`<div class="diff-add"><span class="diff-line-no">%4d</span> + %s</div>`,
lineNo,
html.EscapeString(a),
),
)
}
}
}
out = append(
out,
"</pre>",
)
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,
),
},
)
}
+14
View File
@@ -0,0 +1,14 @@
package server
func init() {
/*
ADD THIS ROUTE
BEFORE semantic catch-all:
s.mux.HandleFunc(
"/r/",
s.handleRevisionBrowser,
)
*/
}
+78
View File
@@ -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,
)
}
+116
View File
@@ -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,
)
},
)
}
+3
View File
@@ -0,0 +1,3 @@
package server
func init() {}
+48
View File
@@ -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]
}
+186
View File
@@ -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,
"<h1>",
"# ",
)
out = strings.ReplaceAll(
out,
"</h1>",
"",
)
out = strings.ReplaceAll(
out,
"<ul>",
"",
)
out = strings.ReplaceAll(
out,
"</ul>",
"",
)
out = strings.ReplaceAll(
out,
"<li>",
"- ",
)
out = strings.ReplaceAll(
out,
"</li>",
"",
)
return out
}
+169
View File
@@ -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(),
)
}
@@ -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,
)
+37
View File
@@ -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",
})
}
+54
View File
@@ -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,
"/",
)
},
}
}
+74
View File
@@ -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,
},
)
}
+43
View File
@@ -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),
)
}
+51
View File
@@ -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
}
+88
View File
@@ -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
}
+51
View File
@@ -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
}
+46
View File
@@ -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
}
+32
View File
@@ -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
}
+146
View File
@@ -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
}
+140
View File
@@ -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
}
+54
View File
@@ -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
}
+16
View File
@@ -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,
}
}
+53
View File
@@ -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
}
+152
View File
@@ -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,
)
}
}
+24
View File
@@ -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;
}
+10
View File
@@ -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;
}
+53
View File
@@ -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;
}
+7
View File
@@ -0,0 +1,7 @@
body.mode-editor .page-html {
display: none;
}
body.mode-view textarea.editor {
display: none;
}
+55
View File
@@ -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;
}
+163
View File
@@ -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 =
"<code>"
+ r.uuid
+ "</code><br>"
+ ts.toLocaleString()
+ "<br>"
+ r.message
+ "<br><button onclick=\"restoreRevision('"
+ r.uuid
+ "')\">Restore</button>"
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,
)
}
},
)
+315
View File
@@ -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()
},
)
},
)
+50
View File
@@ -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("/")
}
})
+105
View File
@@ -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 = "/"
},
}
+44
View File
@@ -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()
}
+1
View File
@@ -0,0 +1 @@
console.log("search.js loaded")
+60
View File
@@ -0,0 +1,60 @@
{{ define "base" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ .Title }}</title>
<link rel="stylesheet" href="/static/css/main.css">
<link rel="stylesheet" href="/static/css/modes.css">
</head>
<body class="{{ template "body-class" . }}">
<header class="topbar">
<div class="brand">
<a href="/">Pages Wiki</a>
</div>
<nav>
<a href="/new">New</a>
<a href="/l">Links</a>
{{ if .Path }}
<a href="{{ .Path }}">
View
</a>
<a href="/e{{ .Path }}">
Edit
</a>
<a href="/raw{{ .Path }}">
Raw
</a>
{{ end }}
</nav>
</header>
<main class="container">
{{ template "content" . }}
</main>
{{ template "scripts" . }}
</body>
</html>
{{ end }}
{{ define "body-class" }}
mode-view
{{ end }}
+3
View File
@@ -0,0 +1,3 @@
Insert before </body>
{{ template "scripts" . }}
+3
View File
@@ -0,0 +1,3 @@
{{ define "body-class" }}
mode-view
{{ end }}
+8
View File
@@ -0,0 +1,8 @@
{{ define "scripts" }}
<script src="/static/js/editor.js"></script>
<script src="/static/js/navigation.js"></script>
<script src="/static/js/revisions.js"></script>
<script src="/static/js/search.js"></script>
{{ end }}
+148
View File
@@ -0,0 +1,148 @@
{{ define "editor.gohtml" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ .Title }}</title>
<link
rel="stylesheet"
href="/o/path:/system/static/css/main.css"
>
<link
rel="stylesheet"
href="/o/path:/system/static/css/modes.css"
>
</head>
<body class="mode-editor">
<header class="topbar">
<div class="brand">
<a href="/">Pages Wiki</a>
</div>
<nav>
<a href="/">Home</a>
{{ if .Path }}
<a href="{{ .Path }}">
View
</a>
<a href="/r/history/{{ .ObjectUUID }}">
History
</a>
<a href="/l?object_uuid={{ .ObjectUUID }}">
Links
</a>
{{ end }}
</nav>
</header>
<main class="container">
<section class="card">
<div class="path-label">
{{ .Path }}
</div>
<div class="editor-toolbar">
<button
type="button"
onclick="PagesEditor.saveNow()"
>
Save
</button>
<button
type="button"
onclick="PagesPathActions.renameCurrentPath()"
>
Rename
</button>
<button
type="button"
onclick="PagesPathActions.removeCurrentPath()"
>
Delete
</button>
<a
class="button"
href="/r/history/{{ .ObjectUUID }}"
>
History
</a>
<select id="editor-type">
<option
value="html"
{{ if eq .EditType "html" }}selected{{ end }}
>
HTML
</option>
<option
value="markdown"
{{ if eq .EditType "markdown" }}selected{{ end }}
>
Markdown
</option>
</select>
</div>
<div class="editor-grid">
<textarea
id="editor"
class="editor"
>{{ .Body }}</textarea>
<article
id="preview"
class="preview"
></article>
</div>
<input
type="hidden"
id="object-uuid"
value="{{ .ObjectUUID }}"
>
<input
type="hidden"
id="edit-type"
value="{{ .EditType }}"
>
</section>
</main>
<script src="/o/path:/system/static/js/editor.js"></script>
<script src="/o/path:/system/static/js/path-actions.js"></script>
</body>
</html>
{{ end }}
+3
View File
@@ -0,0 +1,3 @@
{{ define "editor-body-class" }}
mode-editor
{{ end }}
+41
View File
@@ -0,0 +1,41 @@
{{ define "explorer.gohtml" }}
{{ template "base" . }}
{{ end }}
{{ define "content" }}
<section class="card">
<h1>Explorer</h1>
<div class="tree-root">
{{ template "tree-node" .Tree }}
</div>
</section>
{{ end }}
{{ define "tree-node" }}
<ul class="tree">
{{ range . }}
<li>
<a href="{{ .Path }}">
{{ .Path }}
</a>
{{ if .Children }}
{{ template "tree-node" .Children }}
{{ end }}
</li>
{{ end }}
</ul>
{{ end }}
+200
View File
@@ -0,0 +1,200 @@
{{ define "home.gohtml" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Pages Wiki</title>
<link
rel="stylesheet"
href="/o/path:/system/static/css/main.css"
>
<link
rel="stylesheet"
href="/o/path:/system/static/css/modes.css"
>
</head>
<body class="mode-home">
<header class="topbar">
<div class="brand">
<a href="/">Pages Wiki</a>
</div>
<nav>
<a href="/tree">
Tree
</a>
<a href="/new">
Draft
</a>
</nav>
</header>
<main class="container">
<section class="card">
<h1>Pages Wiki</h1>
<p>
Path-first semantic wiki.
</p>
<div class="create-path-box">
<input
id="new-path"
type="text"
placeholder="/pageswiki/hogehoge"
autofocus
>
<button
type="button"
onclick="createOrEditPath()"
>
Create / Edit
</button>
</div>
<p class="hint">
Examples:
</p>
<ul>
<li>/pageswiki/network/bgp</li>
<li>/notes/todo</li>
<li>/dc/cooling</li>
</ul>
</section>
<section class="card">
<h2>Recent Objects</h2>
<ul class="object-list">
{{ range .Objects }}
<li>
<a href="/e/{{ .UUID }}">
{{ .UUID }}
</a>
</li>
{{ end }}
</ul>
</section>
</main>
<script>
function normalizePath(input) {
let p = input.trim()
if (!p.startsWith("/")) {
p = "/" + p
}
p = p.replace(/\/+/g, "/")
return p
}
function createOrEditPath() {
const input =
document.getElementById(
"new-path",
)
if (!input.value.trim()) {
return
}
const path =
normalizePath(
input.value,
)
location.href =
"/e" + path
}
document
.getElementById(
"new-path",
)
.addEventListener(
"keydown",
(ev) => {
if (ev.key === "Enter") {
ev.preventDefault()
createOrEditPath()
}
},
)
</script>
<style>
.create-path-box {
display: flex;
gap: 0.5rem;
margin: 1rem 0;
}
.create-path-box input {
flex: 1;
background: #111;
color: #eee;
border: 1px solid #333;
padding: 0.6rem;
font-family: monospace;
}
.create-path-box button {
padding: 0.6rem 1rem;
}
.hint {
margin-top: 1rem;
color: #888;
}
.object-list {
margin: 0;
padding-left: 1.2rem;
}
.object-list li {
margin: 0.2rem 0;
}
</style>
</body>
</html>
{{ end }}
+89
View File
@@ -0,0 +1,89 @@
{{ define "links.gohtml" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ .Title }}</title>
<link
rel="stylesheet"
href="/o/path:/system/static/css/main.css"
>
<link
rel="stylesheet"
href="/o/path:/system/static/css/modes.css"
>
</head>
<body class="mode-links">
<header class="topbar">
<div class="brand">
<a href="/">Pages Wiki</a>
</div>
<nav>
<a href="/">Home</a>
<a href="/new">New</a>
</nav>
</header>
<main class="container">
<section class="card">
<h1>Path Link Manager</h1>
<div class="link-grid">
<div>
<label>
Object UUID
</label>
<input
id="link-object-uuid"
class="input"
value="{{ .ObjectUUID }}"
>
<label>
Semantic Path
</label>
<input
id="link-path"
class="input"
placeholder="/research/network/bgp"
>
<button
type="button"
onclick="bindPath()"
>
Bind Path
</button>
</div>
</div>
</section>
</main>
<script src="/o/path:/system/static/js/navigation.js"></script>
</body>
</html>
{{ end }}
+90
View File
@@ -0,0 +1,90 @@
{{ define "page.gohtml" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ .Title }}</title>
<link
rel="stylesheet"
href="/o/path:/system/static/css/main.css"
>
<link
rel="stylesheet"
href="/o/path:/system/static/css/modes.css"
>
</head>
<body class="mode-page">
<header class="topbar">
<div class="brand">
<a href="/">Pages Wiki</a>
</div>
<nav>
<a href="/">Home</a>
{{ if .Path }}
<a href="/e{{ .Path }}">
Edit
</a>
<a href="/r/history/{{ .ObjectUUID }}">
History
</a>
<a href="/l?object_uuid={{ .ObjectUUID }}">
Links
</a>
<a href="/raw{{ .Path }}">
Raw
</a>
{{ end }}
</nav>
</header>
<main class="container">
<section class="card">
<div class="path-label">
{{ .Path }}
</div>
<article class="page-html">
{{ .RenderedHTML }}
</article>
</section>
</main>
<style>
.children-list ul {
margin: 0;
padding-left: 1.2rem;
}
.children-list li {
margin: 0.15rem 0;
}
</style>
</body>
</html>
{{ end }}
+49
View File
@@ -0,0 +1,49 @@
{{ define "revision_diff.gohtml" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ .Title }}</title>
<link rel="stylesheet" href="/o/path:/system/static/css/main.css">
<link rel="stylesheet" href="/o/path:/system/static/css/revisions.css">
</head>
<body>
<main class="container">
<section class="card">
<h1>Revision Diff</h1>
<div class="revision-meta">
<div>
Before:
<code>{{ .Before.Hash }}</code>
</div>
<div>
After:
<code>{{ .After.Hash }}</code>
</div>
</div>
</section>
<section class="card">
{{ .DiffHTML }}
</section>
</main>
</body>
</html>
{{ end }}
+106
View File
@@ -0,0 +1,106 @@
{{ define "revision_view.gohtml" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ .Title }}</title>
<link
rel="stylesheet"
href="/o/path:/system/static/css/main.css"
>
<link
rel="stylesheet"
href="/o/path:/system/static/css/revisions.css"
>
</head>
<body class="mode-revision-view">
<header class="topbar">
<div class="brand">
<a href="/">Pages Wiki</a>
</div>
<nav>
<a
href="/r/history/{{ .Revision.ObjectUUID }}"
>
History
</a>
</nav>
</header>
<main class="container">
<section class="card">
<h1>Revision View</h1>
<div class="revision-meta">
<div>
Revision Hash:
<code>{{ .Revision.Hash }}</code>
</div>
<div>
Object UUID:
<code>{{ .Revision.ObjectUUID }}</code>
</div>
<div>
Message:
{{ .Revision.Message }}
</div>
<div>
Created:
{{ .Revision.CreatedAt }}
</div>
</div>
</section>
<section class="card">
<h2>Rendered</h2>
<article class="page-html">
{{ .RenderedHTML }}
</article>
</section>
<section class="card">
<details>
<summary>
Raw HTML Source
</summary>
<textarea
readonly
class="revision-textarea"
>{{ .Revision.Body }}</textarea>
</details>
</section>
</main>
</body>
</html>
{{ end }}
+108
View File
@@ -0,0 +1,108 @@
{{ define "revisions.gohtml" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{{ .Title }}</title>
<link
rel="stylesheet"
href="/o/path:/system/static/css/main.css"
>
<link
rel="stylesheet"
href="/o/path:/system/static/css/revisions.css"
>
</head>
<body class="mode-revisions">
<header class="topbar">
<div class="brand">
<a href="/">Pages Wiki</a>
</div>
<nav>
<a href="/">Home</a>
</nav>
</header>
<main class="container">
<section class="card">
<h1>Revision History</h1>
<p>
Object UUID:
<code>{{ .ObjectUUID }}</code>
</p>
</section>
<section class="revision-timeline">
{{ range $i, $r := .Revisions }}
<article class="revision-card">
<div class="revision-header">
<div>
<code>{{ $r.Hash }}</code>
</div>
<div>
{{ $r.CreatedAt }}
</div>
</div>
<div class="revision-message">
{{ $r.Message }}
</div>
<div class="revision-actions">
<a
class="button"
href="/r/view/{{ $r.Hash }}"
>
View
</a>
{{ if lt (add $i 1) (len $.Revisions) }}
{{ $prev := index $.Revisions (add $i 1) }}
<a
class="button"
href="/r/diff/{{ $prev.Hash }}/{{ $r.Hash }}"
>
Diff Prev
</a>
{{ end }}
</div>
</article>
{{ end }}
</section>
</main>
</body>
</html>
{{ end }}
+978
View File
@@ -0,0 +1,978 @@
{{ define "tree.gohtml" }}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Tree</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/@fontsource/jetbrains-mono@5.0.20/index.css"
/>
<link
rel="stylesheet"
href="/o/path:/system/static/css/main.css"
>
<style>
:root {
--bg: #0b0b0c;
--panel: var(--bg);
--line:
rgba(255,255,255,0.06);
--link:
#c27cff;
--link-hover:
#e2b9ff;
--edit:
#e0c25f;
--rename:
#64d7ee;
--delete:
#ff6d6d;
}
body {
background: var(--bg);
color: #ddd;
margin: 0;
font-family:
Inter,
"Noto Sans JP",
sans-serif;
}
.topbar {
height: 48px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0 1rem;
border-bottom:
1px solid rgba(255,255,255,0.05);
}
.topbar a {
color: #9cc8ff;
text-decoration: none;
}
.container {
padding: 1rem;
}
.card {
background: transparent;
border: none;
padding: 1rem 1rem 2rem 1rem;
}
.tree-toolbar {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.tree-toolbar input {
width: 28rem;
background: #090909;
color: #ddd;
border:
1px solid rgba(255,255,255,0.08);
padding: 0.7rem;
font-family: monospace;
}
.tree {
display: flex;
flex-direction: column;
}
.tree-row {
position: relative;
display: flex;
align-items: center;
justify-content: space-between;
height: 30px;
border-bottom:
1px solid rgba(255,255,255,0.045);
transition:
background 0.08s linear;
}
.tree-row:hover {
background:
rgba(255,255,255,0.018);
}
.tree-left {
display: flex;
align-items: center;
min-width: 0;
flex: 1;
}
.tree-indent {
width: 18px;
height: 30px;
border-left:
1px solid rgba(255,255,255,0.08);
}
.tree-node {
display: flex;
align-items: center;
gap: 0.45rem;
}
.tree-icon {
width: 1rem;
text-align: center;
opacity: 0.9;
}
.tree-link {
text-decoration: none;
color: var(--link);
font-family:
"JetBrains Mono",
monospace;
transition:
color 0.08s linear,
text-shadow 0.08s linear;
}
.tree-link:hover {
color: var(--link-hover);
text-shadow:
0 0 0.45rem rgba(220,180,255,0.35);
}
.tree-actions {
display: flex;
gap: 0.85rem;
opacity: 0.52;
padding-right: 0.5rem;
transition:
opacity 0.08s linear;
}
.tree-row:hover .tree-actions {
opacity: 1;
}
.tree-btn {
border: none;
background: transparent;
cursor: pointer;
font-size: 0.78rem;
font-family:
"JetBrains Mono",
monospace;
text-decoration: none;
}
.tree-btn.edit {
color: var(--edit);
}
.tree-btn.rename {
color: var(--rename);
}
.tree-btn.delete {
color: var(--delete);
}
.tree-btn:hover {
filter: brightness(1.18);
transform: translateY(-1px);
}
.count-badge {
margin-left: 0.35rem;
padding:
0.08rem 0.42rem;
border-radius: 999px;
background:
rgba(255,255,255,0.12);
color: #ddd;
font-size: 0.68rem;
font-family: monospace;
}
.draft-row {
opacity: 0.45;
}
body {
background:
var(--bg);
min-height: 100vh;
}
.container {
padding:
1rem 1rem 4rem 1rem;
}
.tree {
background: transparent;
}
.tree-row {
background: transparent;
}
.tree-toolbar {
margin-bottom: 1.25rem;
}
.tree-toolbar input {
background:
rgba(255,255,255,0.02);
border:
1px solid rgba(255,255,255,0.06);
}
.tree-toolbar input:focus {
outline: none;
border-color:
rgba(180,120,255,0.45);
box-shadow:
0 0 0.6rem rgba(180,120,255,0.12);
}
.rename-progress-inner {
min-width: 22rem;
padding: 1rem;
}
.rename-progress-count {
margin-top: 0.5rem;
margin-bottom: 1rem;
opacity: 0.8;
}
#rename-progress {
background: #111;
color: #eee;
border:
1px solid rgba(255,255,255,0.08);
}
#rename-progress progress {
width: 100%;
}
.tree-node {
display: flex;
align-items: center;
gap: 0.48rem;
min-width: 0;
}
.tree-icon {
width: 1.2rem;
text-align: center;
font-family:
"Hack Nerd Font";
font-size: 1rem;
opacity: 0.92;
transition:
transform 0.08s linear,
text-shadow 0.08s linear,
opacity 0.08s linear;
}
.tree-row:hover .tree-icon {
transform:
translateY(-1px);
opacity: 1;
}
.tree-icon.dir {
color:
#c792ff;
text-shadow:
0 0 0.4rem rgba(180,120,255,0.18);
}
.tree-icon.file {
color:
#8ad6ff;
text-shadow:
0 0 0.4rem rgba(120,180,255,0.12);
}
.tree-icon.draft {
color:
#999;
opacity: 0.65;
}
.tree-link {
text-decoration: none;
color: var(--link);
font-family:
"JetBrains Mono",
monospace;
font-size: 0.92rem;
letter-spacing: -0.01em;
transition:
color 0.08s linear,
text-shadow 0.08s linear,
transform 0.08s linear;
}
.tree-link:hover {
color:
#f0d7ff;
text-shadow:
0 0 0.45rem rgba(220,180,255,0.32);
transform:
translateX(1px);
}
.tree-row {
position: relative;
border-left:
1px solid rgba(255,255,255,0.04);
padding-left: 0.2rem;
}
.tree-row:hover {
border-left-color:
rgba(200,140,255,0.35);
}
.count-badge {
margin-left: 0.35rem;
padding:
0.04rem 0.38rem;
border-radius: 999px;
background:
rgba(255,255,255,0.08);
color:
rgba(255,255,255,0.72);
font-size: 0.65rem;
font-family:
"JetBrains Mono",
monospace;
}
</style>
<style>
@font-face {
font-family:
"Hack Nerd Font";
src:
url(
"https://cdn.jsdelivr.net/gh/ryanoasis/nerd-fonts@master/patched-fonts/Hack/Regular/HackNerdFont-Regular.ttf"
)
format("truetype");
}
</style>
</head>
<body>
<header class="topbar">
<div>
Pages Wiki
</div>
<nav>
<a href="/">
Home
</a>
</nav>
</header>
<main class="container">
<section class="card">
<h1>Content Tree</h1>
<div class="tree-toolbar">
<input
id="tree-filter"
type="text"
placeholder="filter paths..."
oninput="filterTree()"
>
</div>
<div class="tree">
{{ range .Nodes }}
<div
class="tree-row {{ if .IsDraft }}draft-row{{ end }}"
data-path="{{ .Path }}"
>
<div class="tree-left">
{{ range $i := until .Depth }}
<div class="tree-indent"></div>
{{ end }}
<div class="tree-node">
<div
class="tree-icon
{{ if .IsDir }}dir{{ else }}file{{ end }}
{{ if .IsDraft }}draft{{ end }}"
>
{{ if .IsDir }}
󰉋
{{ else }}
󰈔
{{ end }}
</div>
<a
href="{{ .Path }}"
class="tree-link"
>
{{ .Name }}
</a>
{{ if .IsDir }}
<span class="count-badge">
{{ .ChildCount }}
</span>
{{ end }}
</div>
</div>
<div class="tree-actions">
<a
href="/e{{ .Path }}"
class="tree-btn edit"
>
✎ edit
</a>
<button
class="tree-btn rename"
onclick="renamePath('{{ .Path }}')">
⟲ rename
</button>
<button
class="tree-btn delete"
onclick="deletePath('{{ .Path }}')"
>
⌫ delete
</button>
</div>
</div>
{{ end }}
</div>
</section>
</main>
<script>
async function renamePath(oldPath) {
const newPath =
prompt(
"Rename path:",
oldPath,
)
if (
!newPath
||
newPath === oldPath
) {
return
}
let recursive = false
if (
confirm(
oldPath + "\n\n" + newPath,
)
) {
recursive = true
}
if (!recursive) {
await renameSinglePath(
oldPath,
newPath,
)
location.reload()
return
}
const previewRes =
await fetch(
"/_/api/v1/path/rename-preview?old_path=" +
encodeURIComponent(
oldPath,
),
)
if (!previewRes.ok) {
alert(
"preview failed",
)
return
}
const preview =
await previewRes.json()
const targets =
preview.targets
const ok =
confirm(
"Affected paths: " + "\n" + targets.length + "\n" + "Execute recursive rename?",
)
if (!ok) {
return
}
const dlg =
createRenameProgressDialog()
const bar =
dlg.querySelector(
"progress",
)
const label =
dlg.querySelector(
".rename-progress-label",
)
dlg.showModal()
let done = 0
for (const oldTarget of targets) {
const newTarget =
oldTarget.replace(
oldPath,
newPath,
)
label.textContent =
oldTarget
await renameSinglePath(
oldTarget,
newTarget,
)
done += 1
bar.value =
done
bar.max =
targets.length
}
dlg.close()
location.reload()
}
async function deletePath(path) {
if (
!confirm(
"Delete path?\n\n" + path,
)
) {
return
}
const res =
await fetch(
"/_/api/v1/path/remove",
{
method: "POST",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
path: path,
}),
},
)
if (!res.ok) {
alert(
"delete failed",
)
return
}
location.reload()
}
function filterTree() {
const q =
document
.getElementById(
"tree-filter",
)
.value
.toLowerCase()
for (
const row
of document.querySelectorAll(
".tree-row",
)
) {
const path =
row.dataset.path
.toLowerCase()
row.style.display =
path.includes(q)
? "flex"
: "none"
}
}
function showRenameProgress(count) {
let dlg =
document.getElementById(
"rename-progress",
)
if (!dlg) {
dlg =
document.createElement("dialog")
dlg.id =
"rename-progress"
dlg.innerHTML =
"<div class=\"rename-progress-inner\">" +
"<h3>Renaming namespace</h3>" +
"<div class=\"rename-progress-count\">" +
"affected pages: " + count +c
"</div>" +
"<progress></progress>" +
"</div>"
document.body.appendChild(
dlg,
)
}
dlg.showModal()
}
async function renameSinglePath(
oldPath,
newPath,
) {
const res =
await fetch(
"/_/api/v1/path/rename",
{
method: "POST",
headers: {
"Content-Type":
"application/json",
},
body: JSON.stringify({
old_path: oldPath,
new_path: newPath,
}),
},
)
if (!res.ok) {
throw new Error(
"rename failed: " +
oldPath,
)
}
}
function createRenameProgressDialog() {
let dlg =
document.getElementById(
"rename-progress",
)
if (dlg) {
return dlg
}
dlg =
document.createElement(
"dialog",
)
dlg.id =
"rename-progress"
dlg.innerHTML =
`
<div class="rename-progress-inner">
<h3>
Renaming namespace
</h3>
<div class="rename-progress-label">
</div>
<progress
value="0"
max="100"
></progress>
</div>
`
document.body.appendChild(
dlg,
)
return dlg
}
</script>
</body>
</html>
{{ end }}
+18
View File
@@ -0,0 +1,18 @@
{{ define "breadcrumbs" }}
<nav class="breadcrumbs">
<a href="/">root</a>
{{ range .Breadcrumbs }}
/
<a href="{{ .Path }}">
{{ .Name }}
</a>
{{ end }}
</nav>
{{ end }}
+15
View File
@@ -0,0 +1,15 @@
{{ define "search_dialog" }}
<dialog id="search-dialog" class="dialog">
<div class="dialog-body">
<input
id="search-input"
class="search-input"
placeholder="Search..."
>
<ul id="search-results" class="search-results"></ul>
</div>
</dialog>
{{ end }}