Add conflict resolution diff UI and app branding
This commit is contained in:
@@ -7,10 +7,10 @@ tmp_dir = "tmp"
|
||||
|
||||
[build]
|
||||
args_bin = []
|
||||
bin = "./bin/md-hub-secure"
|
||||
cmd = "CGO_ENABLED=1 go build -trimpath -o bin/md-hub-secure ./cmd/md-hub-secure"
|
||||
bin = "./bin/cairnquire"
|
||||
cmd = "CGO_ENABLED=1 go build -trimpath -o bin/cairnquire ./cmd/cairnquire"
|
||||
delay = 500
|
||||
entrypoint = ["./bin/md-hub-secure"]
|
||||
entrypoint = ["./bin/cairnquire"]
|
||||
exclude_dir = ["assets", "tmp", "vendor", "testdata", "bin"]
|
||||
exclude_file = []
|
||||
exclude_regex = ["_test.go"]
|
||||
|
||||
@@ -9,9 +9,9 @@ import (
|
||||
"os/signal"
|
||||
"syscall"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/app"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/config"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/logging"
|
||||
"github.com/tim/cairnquire/apps/server/internal/app"
|
||||
"github.com/tim/cairnquire/apps/server/internal/config"
|
||||
"github.com/tim/cairnquire/apps/server/internal/logging"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -1,4 +1,4 @@
|
||||
module github.com/tim/md-hub-secure/apps/server
|
||||
module github.com/tim/cairnquire/apps/server
|
||||
|
||||
go 1.24.2
|
||||
|
||||
|
||||
@@ -9,13 +9,14 @@ import (
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/config"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/database"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/docs"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/httpserver"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/markdown"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/realtime"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/store"
|
||||
"github.com/tim/cairnquire/apps/server/internal/config"
|
||||
"github.com/tim/cairnquire/apps/server/internal/database"
|
||||
"github.com/tim/cairnquire/apps/server/internal/docs"
|
||||
"github.com/tim/cairnquire/apps/server/internal/httpserver"
|
||||
"github.com/tim/cairnquire/apps/server/internal/markdown"
|
||||
"github.com/tim/cairnquire/apps/server/internal/realtime"
|
||||
"github.com/tim/cairnquire/apps/server/internal/store"
|
||||
"github.com/tim/cairnquire/apps/server/internal/sync"
|
||||
)
|
||||
|
||||
type App struct {
|
||||
@@ -58,6 +59,9 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*App, err
|
||||
logger.Warn("initial content sync failed", "error", err)
|
||||
}
|
||||
|
||||
syncRepo := sync.NewRepository(db.SQL())
|
||||
syncService := sync.NewService(syncRepo, service, contentStore, cfg.Content.SourceDir, logger)
|
||||
|
||||
handler, err := httpserver.New(httpserver.Dependencies{
|
||||
Config: cfg,
|
||||
Logger: logger,
|
||||
@@ -65,6 +69,8 @@ func New(ctx context.Context, cfg config.Config, logger *slog.Logger) (*App, err
|
||||
Repository: repo,
|
||||
ContentStore: contentStore,
|
||||
Hub: hub,
|
||||
SyncService: syncService,
|
||||
SyncRepo: syncRepo,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build http handler: %w", err)
|
||||
|
||||
@@ -49,7 +49,7 @@ func Default() Config {
|
||||
},
|
||||
Web: WebConfig{
|
||||
DistDir: filepath.Join("..", "web", "dist"),
|
||||
DevViteURL: os.Getenv("MD_HUB_DEV_VITE_URL"),
|
||||
DevViteURL: os.Getenv("CAIRNQUIRE_DEV_VITE_URL"),
|
||||
},
|
||||
LogLevel: "INFO",
|
||||
}
|
||||
@@ -58,21 +58,21 @@ func Default() Config {
|
||||
func Load() (Config, error) {
|
||||
cfg := Default()
|
||||
|
||||
if configPath := os.Getenv("MD_HUB_CONFIG"); configPath != "" {
|
||||
if configPath := os.Getenv("CAIRNQUIRE_CONFIG"); configPath != "" {
|
||||
if err := loadFile(configPath, &cfg); err != nil {
|
||||
return Config{}, err
|
||||
}
|
||||
}
|
||||
|
||||
overrideString(&cfg.Server.Addr, "MD_HUB_SERVER_ADDR")
|
||||
overrideString(&cfg.Database.Path, "MD_HUB_DATABASE_PATH")
|
||||
overrideString(&cfg.Database.PrimaryURL, "MD_HUB_DATABASE_PRIMARY_URL")
|
||||
overrideString(&cfg.Database.AuthToken, "MD_HUB_DATABASE_AUTH_TOKEN")
|
||||
overrideString(&cfg.Content.SourceDir, "MD_HUB_CONTENT_SOURCE_DIR")
|
||||
overrideString(&cfg.Content.StoreDir, "MD_HUB_CONTENT_STORE_DIR")
|
||||
overrideString(&cfg.Web.DistDir, "MD_HUB_WEB_DIST_DIR")
|
||||
overrideString(&cfg.Web.DevViteURL, "MD_HUB_DEV_VITE_URL")
|
||||
overrideString(&cfg.LogLevel, "MD_HUB_LOG_LEVEL")
|
||||
overrideString(&cfg.Server.Addr, "CAIRNQUIRE_SERVER_ADDR")
|
||||
overrideString(&cfg.Database.Path, "CAIRNQUIRE_DATABASE_PATH")
|
||||
overrideString(&cfg.Database.PrimaryURL, "CAIRNQUIRE_DATABASE_PRIMARY_URL")
|
||||
overrideString(&cfg.Database.AuthToken, "CAIRNQUIRE_DATABASE_AUTH_TOKEN")
|
||||
overrideString(&cfg.Content.SourceDir, "CAIRNQUIRE_CONTENT_SOURCE_DIR")
|
||||
overrideString(&cfg.Content.StoreDir, "CAIRNQUIRE_CONTENT_STORE_DIR")
|
||||
overrideString(&cfg.Web.DistDir, "CAIRNQUIRE_WEB_DIST_DIR")
|
||||
overrideString(&cfg.Web.DevViteURL, "CAIRNQUIRE_DEV_VITE_URL")
|
||||
overrideString(&cfg.LogLevel, "CAIRNQUIRE_LOG_LEVEL")
|
||||
|
||||
if cfg.Server.Addr == "" {
|
||||
return Config{}, fmt.Errorf("server.addr must not be empty")
|
||||
|
||||
@@ -10,7 +10,7 @@ import (
|
||||
|
||||
libsql "github.com/tursodatabase/go-libsql"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/config"
|
||||
"github.com/tim/cairnquire/apps/server/internal/config"
|
||||
)
|
||||
|
||||
type DB interface {
|
||||
|
||||
35
apps/server/internal/database/migrations/000008_sync.up.sql
Normal file
35
apps/server/internal/database/migrations/000008_sync.up.sql
Normal file
@@ -0,0 +1,35 @@
|
||||
CREATE TABLE IF NOT EXISTS api_keys (
|
||||
id TEXT PRIMARY KEY,
|
||||
user_id TEXT NOT NULL,
|
||||
name TEXT NOT NULL,
|
||||
key_hash TEXT NOT NULL UNIQUE,
|
||||
scopes TEXT NOT NULL DEFAULT 'sync:read,sync:write',
|
||||
created_at TEXT NOT NULL,
|
||||
expires_at TEXT,
|
||||
last_used_at TEXT,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_api_keys_key_hash ON api_keys(key_hash);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_snapshots (
|
||||
id TEXT PRIMARY KEY,
|
||||
device_id TEXT NOT NULL,
|
||||
user_id TEXT NOT NULL,
|
||||
created_at TEXT NOT NULL,
|
||||
FOREIGN KEY(user_id) REFERENCES users(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sync_snapshots_device ON sync_snapshots(device_id);
|
||||
|
||||
CREATE TABLE IF NOT EXISTS sync_files (
|
||||
snapshot_id TEXT NOT NULL,
|
||||
path TEXT NOT NULL,
|
||||
hash TEXT NOT NULL,
|
||||
size_bytes INTEGER NOT NULL DEFAULT 0,
|
||||
modified_at TEXT NOT NULL,
|
||||
PRIMARY KEY (snapshot_id, path),
|
||||
FOREIGN KEY(snapshot_id) REFERENCES sync_snapshots(id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_sync_files_hash ON sync_files(hash);
|
||||
@@ -12,8 +12,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/markdown"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/store"
|
||||
"github.com/tim/cairnquire/apps/server/internal/markdown"
|
||||
"github.com/tim/cairnquire/apps/server/internal/store"
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
@@ -41,6 +41,25 @@ type Page struct {
|
||||
Hash string
|
||||
}
|
||||
|
||||
type SourcePage struct {
|
||||
Path string
|
||||
Title string
|
||||
Tags []string
|
||||
Content string
|
||||
Hash string
|
||||
}
|
||||
|
||||
type DocumentConflictError struct {
|
||||
Path string
|
||||
BaseHash string
|
||||
CurrentHash string
|
||||
CurrentContent string
|
||||
}
|
||||
|
||||
func (e *DocumentConflictError) Error() string {
|
||||
return fmt.Sprintf("document %s changed since editor loaded", e.Path)
|
||||
}
|
||||
|
||||
func NewService(sourceDir string, store *store.ContentStore, renderer *markdown.Renderer, repo *Repository, logger *slog.Logger) *Service {
|
||||
return &Service{
|
||||
sourceDir: sourceDir,
|
||||
@@ -61,6 +80,11 @@ func (s *Service) SyncSourceDir(ctx context.Context) ([]DocumentChange, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
return s.syncSourceDirLocked(ctx)
|
||||
}
|
||||
|
||||
func (s *Service) syncSourceDirLocked(ctx context.Context) ([]DocumentChange, error) {
|
||||
|
||||
var changes []DocumentChange
|
||||
err := filepath.WalkDir(s.sourceDir, func(path string, entry fs.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
@@ -104,6 +128,116 @@ func (s *Service) LoadPage(ctx context.Context, requestPath string) (*Page, erro
|
||||
return nil, err
|
||||
}
|
||||
|
||||
record, normalized, err := s.resolveRecord(ctx, requestPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
content, err := s.store.Read(record.CurrentHash)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read content %s: %w", record.CurrentHash, err)
|
||||
}
|
||||
|
||||
rendered, err := s.renderer.RenderPath(content, normalized)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render page %s: %w", normalized, err)
|
||||
}
|
||||
|
||||
return &Page{
|
||||
Path: record.Path,
|
||||
Title: rendered.Title,
|
||||
Tags: record.Tags,
|
||||
HTML: string(rendered.HTML),
|
||||
Hash: record.CurrentHash,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) LoadSourcePage(ctx context.Context, requestPath string) (*SourcePage, error) {
|
||||
if _, err := s.SyncSourceDir(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
record, _, err := s.resolveRecord(ctx, requestPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
content, err := s.store.Read(record.CurrentHash)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read source content %s: %w", record.CurrentHash, err)
|
||||
}
|
||||
|
||||
return &SourcePage{
|
||||
Path: record.Path,
|
||||
Title: record.Title,
|
||||
Tags: record.Tags,
|
||||
Content: string(content),
|
||||
Hash: record.CurrentHash,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) SaveSourcePage(ctx context.Context, requestPath string, content string) (*SourcePage, error) {
|
||||
return s.SaveSourcePageWithBaseHash(ctx, requestPath, content, "")
|
||||
}
|
||||
|
||||
func (s *Service) SaveSourcePageWithBaseHash(ctx context.Context, requestPath string, content string, baseHash string) (*SourcePage, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
|
||||
if _, err := s.syncSourceDirLocked(ctx); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
record, _, err := s.resolveRecord(ctx, requestPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if baseHash != "" && record.CurrentHash != baseHash {
|
||||
currentContent, readErr := s.store.Read(record.CurrentHash)
|
||||
if readErr != nil {
|
||||
return nil, fmt.Errorf("read current content %s: %w", record.CurrentHash, readErr)
|
||||
}
|
||||
return nil, &DocumentConflictError{
|
||||
Path: record.Path,
|
||||
BaseHash: baseHash,
|
||||
CurrentHash: record.CurrentHash,
|
||||
CurrentContent: string(currentContent),
|
||||
}
|
||||
}
|
||||
|
||||
fullPath := filepath.Join(s.sourceDir, filepath.FromSlash(record.Path))
|
||||
if err := os.MkdirAll(filepath.Dir(fullPath), 0o755); err != nil {
|
||||
return nil, fmt.Errorf("create document directory %s: %w", record.Path, err)
|
||||
}
|
||||
if err := os.WriteFile(fullPath, []byte(content), 0o644); err != nil {
|
||||
return nil, fmt.Errorf("write document %s: %w", record.Path, err)
|
||||
}
|
||||
|
||||
change, err := s.syncFile(ctx, fullPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if change != nil && s.onChange != nil {
|
||||
s.onChange(*change)
|
||||
}
|
||||
|
||||
updated, _, err := s.resolveRecord(ctx, record.Path)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &SourcePage{
|
||||
Path: updated.Path,
|
||||
Title: updated.Title,
|
||||
Tags: updated.Tags,
|
||||
Content: content,
|
||||
Hash: updated.CurrentHash,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) resolveRecord(ctx context.Context, requestPath string) (*DocumentRecord, string, error) {
|
||||
|
||||
var (
|
||||
record *DocumentRecord
|
||||
normalized string
|
||||
@@ -119,26 +253,10 @@ func (s *Service) LoadPage(ctx context.Context, requestPath string) (*Page, erro
|
||||
lastErr = err
|
||||
}
|
||||
if record == nil {
|
||||
return nil, lastErr
|
||||
return nil, "", lastErr
|
||||
}
|
||||
|
||||
content, err := s.store.Read(record.CurrentHash)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("read content %s: %w", record.CurrentHash, err)
|
||||
}
|
||||
|
||||
rendered, err := s.renderer.Render(content)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render page %s: %w", normalized, err)
|
||||
}
|
||||
|
||||
return &Page{
|
||||
Path: record.Path,
|
||||
Title: rendered.Title,
|
||||
Tags: record.Tags,
|
||||
HTML: string(rendered.HTML),
|
||||
Hash: record.CurrentHash,
|
||||
}, nil
|
||||
return record, normalized, nil
|
||||
}
|
||||
|
||||
func normalizeRequestPathCandidates(path string) []string {
|
||||
@@ -158,7 +276,13 @@ func (s *Service) syncFile(ctx context.Context, path string) (*DocumentChange, e
|
||||
return nil, fmt.Errorf("read content file %s: %w", path, err)
|
||||
}
|
||||
|
||||
rendered, err := s.renderer.Render(content)
|
||||
relative, err := filepath.Rel(s.sourceDir, path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("compute relative path %s: %w", path, err)
|
||||
}
|
||||
relative = filepath.ToSlash(relative)
|
||||
|
||||
rendered, err := s.renderer.RenderPath(content, relative)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("render content file %s: %w", path, err)
|
||||
}
|
||||
@@ -168,12 +292,6 @@ func (s *Service) syncFile(ctx context.Context, path string) (*DocumentChange, e
|
||||
return nil, fmt.Errorf("store content file %s: %w", path, err)
|
||||
}
|
||||
|
||||
relative, err := filepath.Rel(s.sourceDir, path)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("compute relative path %s: %w", path, err)
|
||||
}
|
||||
relative = filepath.ToSlash(relative)
|
||||
|
||||
existing, err := s.repo.GetDocumentByPath(ctx, relative)
|
||||
if err != nil && !errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, err
|
||||
|
||||
@@ -1,8 +1,18 @@
|
||||
package docs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"errors"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
"github.com/tim/cairnquire/apps/server/internal/database"
|
||||
"github.com/tim/cairnquire/apps/server/internal/markdown"
|
||||
"github.com/tim/cairnquire/apps/server/internal/store"
|
||||
)
|
||||
|
||||
func TestNormalizeRequestPathCandidatesSupportsIndexFiles(t *testing.T) {
|
||||
@@ -37,3 +47,95 @@ func TestNormalizeRequestPathCandidatesSupportsIndexFiles(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveSourcePageWithBaseHashRejectsStaleEditor(t *testing.T) {
|
||||
service, sourceDir := setupDocsTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
page, err := service.LoadSourcePage(ctx, "hello")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadSourcePage() error = %v", err)
|
||||
}
|
||||
|
||||
serverContent := "# Hello\n\nServer edit"
|
||||
if err := os.WriteFile(filepath.Join(sourceDir, "hello.md"), []byte(serverContent), 0o644); err != nil {
|
||||
t.Fatalf("write server edit: %v", err)
|
||||
}
|
||||
|
||||
_, err = service.SaveSourcePageWithBaseHash(ctx, "hello", "# Hello\n\nClient edit", page.Hash)
|
||||
var conflict *DocumentConflictError
|
||||
if !errors.As(err, &conflict) {
|
||||
t.Fatalf("SaveSourcePageWithBaseHash() error = %v, want DocumentConflictError", err)
|
||||
}
|
||||
if conflict.BaseHash != page.Hash {
|
||||
t.Fatalf("conflict base hash = %q, want %q", conflict.BaseHash, page.Hash)
|
||||
}
|
||||
if conflict.CurrentContent != serverContent {
|
||||
t.Fatalf("conflict current content = %q, want %q", conflict.CurrentContent, serverContent)
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(filepath.Join(sourceDir, "hello.md"))
|
||||
if err != nil {
|
||||
t.Fatalf("read hello.md: %v", err)
|
||||
}
|
||||
if string(content) != serverContent {
|
||||
t.Fatalf("stale save overwrote content: %q", string(content))
|
||||
}
|
||||
}
|
||||
|
||||
func TestSaveSourcePageWithBaseHashAcceptsMatchingHash(t *testing.T) {
|
||||
service, sourceDir := setupDocsTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
page, err := service.LoadSourcePage(ctx, "hello")
|
||||
if err != nil {
|
||||
t.Fatalf("LoadSourcePage() error = %v", err)
|
||||
}
|
||||
|
||||
nextContent := "# Hello\n\nClient edit"
|
||||
updated, err := service.SaveSourcePageWithBaseHash(ctx, "hello", nextContent, page.Hash)
|
||||
if err != nil {
|
||||
t.Fatalf("SaveSourcePageWithBaseHash() error = %v", err)
|
||||
}
|
||||
if updated.Hash == page.Hash {
|
||||
t.Fatal("expected hash to change after save")
|
||||
}
|
||||
|
||||
content, err := os.ReadFile(filepath.Join(sourceDir, "hello.md"))
|
||||
if err != nil {
|
||||
t.Fatalf("read hello.md: %v", err)
|
||||
}
|
||||
if string(content) != nextContent {
|
||||
t.Fatalf("saved content = %q, want %q", string(content), nextContent)
|
||||
}
|
||||
}
|
||||
|
||||
func setupDocsTestService(t *testing.T) (*Service, string) {
|
||||
t.Helper()
|
||||
|
||||
sourceDir := t.TempDir()
|
||||
storeDir := t.TempDir()
|
||||
if err := os.WriteFile(filepath.Join(sourceDir, "hello.md"), []byte("# Hello\n\nOriginal"), 0o644); err != nil {
|
||||
t.Fatalf("create hello.md: %v", err)
|
||||
}
|
||||
|
||||
dbPath := filepath.Join(t.TempDir(), "test.db")
|
||||
db, err := sql.Open("libsql", "file:"+dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("open database: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
ctx := context.Background()
|
||||
if err := database.ApplyMigrations(ctx, db); err != nil {
|
||||
t.Fatalf("apply migrations: %v", err)
|
||||
}
|
||||
|
||||
contentStore, err := store.New(storeDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create content store: %v", err)
|
||||
}
|
||||
|
||||
repo := NewRepository(db)
|
||||
return NewService(sourceDir, contentStore, markdown.NewRenderer(), repo, slog.Default()), sourceDir
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/docs"
|
||||
"github.com/tim/cairnquire/apps/server/internal/docs"
|
||||
)
|
||||
|
||||
type adminUserInput struct {
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"io"
|
||||
"io/fs"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
@@ -17,7 +18,7 @@ import (
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/docs"
|
||||
"github.com/tim/cairnquire/apps/server/internal/docs"
|
||||
)
|
||||
|
||||
type layoutData struct {
|
||||
@@ -42,6 +43,16 @@ type documentData struct {
|
||||
Breadcrumbs []breadcrumb
|
||||
}
|
||||
|
||||
type documentEditData struct {
|
||||
Browser browserData
|
||||
Title string
|
||||
Path string
|
||||
Tags []string
|
||||
Hash string
|
||||
Source string
|
||||
Breadcrumbs []breadcrumb
|
||||
}
|
||||
|
||||
type breadcrumb struct {
|
||||
Name string
|
||||
URL string
|
||||
@@ -86,7 +97,7 @@ func (s *Server) handleIndex(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
activeFolder := strings.Trim(r.URL.Query().Get("folder"), "/")
|
||||
s.renderTemplate(w, http.StatusOK, "index.gohtml", layoutData{
|
||||
Title: "MD Hub Secure",
|
||||
Title: "Cairnquire",
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-index",
|
||||
BodyTemplate: "index_content",
|
||||
@@ -126,9 +137,47 @@ func (s *Server) handleDocsIndex(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
func (s *Server) handleDocument(w http.ResponseWriter, r *http.Request) {
|
||||
pagePath := chi.URLParam(r, "*")
|
||||
if editPath, ok := trimEditSuffix(pagePath); ok {
|
||||
s.renderDocumentEditor(w, r, editPath)
|
||||
return
|
||||
}
|
||||
s.renderDocumentPage(w, r, pagePath)
|
||||
}
|
||||
|
||||
func (s *Server) renderDocumentEditor(w http.ResponseWriter, r *http.Request, pagePath string) {
|
||||
page, err := s.documents.LoadSourcePage(r.Context(), pagePath)
|
||||
if err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
s.renderError(w, r, http.StatusNotFound, "document not found")
|
||||
return
|
||||
}
|
||||
s.renderError(w, r, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
items, err := s.documents.ListDocuments(r.Context())
|
||||
if err != nil {
|
||||
s.renderError(w, r, http.StatusInternalServerError, err.Error())
|
||||
return
|
||||
}
|
||||
|
||||
s.renderTemplate(w, http.StatusOK, "document_edit.gohtml", layoutData{
|
||||
Title: "Edit: " + page.Title,
|
||||
WebEnabled: s.webEnabled,
|
||||
BodyClass: "page-document-edit",
|
||||
BodyTemplate: "document_edit_content",
|
||||
Data: documentEditData{
|
||||
Browser: buildBrowser(items, page.Path),
|
||||
Title: page.Title,
|
||||
Path: page.Path,
|
||||
Tags: page.Tags,
|
||||
Hash: page.Hash,
|
||||
Source: page.Content,
|
||||
Breadcrumbs: buildBreadcrumbs(page.Path),
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) renderDocumentPage(w http.ResponseWriter, r *http.Request, pagePath string) {
|
||||
page, err := s.documents.LoadPage(r.Context(), pagePath)
|
||||
if err != nil {
|
||||
@@ -184,6 +233,20 @@ func (s *Server) handleHealth(w http.ResponseWriter, r *http.Request) {
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleServiceWorker(w http.ResponseWriter, r *http.Request) {
|
||||
content, err := fs.ReadFile(assets, "static/sw.js")
|
||||
if err != nil {
|
||||
http.Error(w, "service worker unavailable", http.StatusInternalServerError)
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/javascript; charset=utf-8")
|
||||
w.Header().Set("Cache-Control", "no-cache")
|
||||
w.Header().Set("Service-Worker-Allowed", "/")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_, _ = w.Write(content)
|
||||
}
|
||||
|
||||
func (s *Server) handleSearch(w http.ResponseWriter, r *http.Request) {
|
||||
query := r.URL.Query().Get("q")
|
||||
if query == "" {
|
||||
@@ -340,6 +403,52 @@ func (s *Server) handleDocuments(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"documents": results})
|
||||
}
|
||||
|
||||
func (s *Server) handleDocumentSave(w http.ResponseWriter, r *http.Request) {
|
||||
pagePath := chi.URLParam(r, "*")
|
||||
if pagePath == "" {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": "document path is required"})
|
||||
return
|
||||
}
|
||||
|
||||
var req struct {
|
||||
Content string `json:"content"`
|
||||
BaseHash string `json:"baseHash"`
|
||||
}
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSONWithStatus(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
page, err := s.documents.SaveSourcePageWithBaseHash(r.Context(), pagePath, req.Content, req.BaseHash)
|
||||
if err != nil {
|
||||
var conflict *docs.DocumentConflictError
|
||||
if errors.As(err, &conflict) {
|
||||
writeJSONWithStatus(w, http.StatusConflict, map[string]any{
|
||||
"error": "document conflict",
|
||||
"status": "conflict",
|
||||
"path": conflict.Path,
|
||||
"baseHash": conflict.BaseHash,
|
||||
"currentHash": conflict.CurrentHash,
|
||||
"currentContent": conflict.CurrentContent,
|
||||
})
|
||||
return
|
||||
}
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
writeJSONWithStatus(w, http.StatusNotFound, map[string]string{"error": "document not found"})
|
||||
return
|
||||
}
|
||||
writeJSONWithStatus(w, http.StatusInternalServerError, map[string]string{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSONWithStatus(w, http.StatusOK, map[string]any{
|
||||
"status": "saved",
|
||||
"path": page.Path,
|
||||
"title": page.Title,
|
||||
"hash": page.Hash,
|
||||
})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, payload any) {
|
||||
writeJSONWithStatus(w, status, payload)
|
||||
}
|
||||
@@ -350,6 +459,16 @@ func writeJSONWithStatus(w http.ResponseWriter, status int, payload any) {
|
||||
_ = json.NewEncoder(w).Encode(payload)
|
||||
}
|
||||
|
||||
func trimEditSuffix(path string) (string, bool) {
|
||||
if path == "edit" {
|
||||
return "", true
|
||||
}
|
||||
if !strings.HasSuffix(path, "/edit") {
|
||||
return "", false
|
||||
}
|
||||
return strings.TrimSuffix(path, "/edit"), true
|
||||
}
|
||||
|
||||
func buildBrowser(records []docs.DocumentRecord, activePath string) browserData {
|
||||
paths := make([]string, 0, len(records))
|
||||
titleByPath := make(map[string]string, len(records))
|
||||
|
||||
@@ -4,7 +4,7 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/docs"
|
||||
"github.com/tim/cairnquire/apps/server/internal/docs"
|
||||
)
|
||||
|
||||
func TestBuildBrowserUsesFolderIndex(t *testing.T) {
|
||||
@@ -41,3 +41,25 @@ func TestBuildBrowserUsesFolderIndex(t *testing.T) {
|
||||
t.Fatalf("folder index file should be represented by the folder, not repeated as a child file")
|
||||
}
|
||||
}
|
||||
|
||||
func TestTrimEditSuffix(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
input string
|
||||
wantPath string
|
||||
wantOK bool
|
||||
}{
|
||||
{name: "nested path", input: "guide/setup/edit", wantPath: "guide/setup", wantOK: true},
|
||||
{name: "root edit sentinel", input: "edit", wantPath: "", wantOK: true},
|
||||
{name: "document route", input: "guide/setup", wantPath: "", wantOK: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
gotPath, gotOK := trimEditSuffix(tt.input)
|
||||
if gotPath != tt.wantPath || gotOK != tt.wantOK {
|
||||
t.Fatalf("trimEditSuffix(%q) = (%q, %t), want (%q, %t)", tt.input, gotPath, gotOK, tt.wantPath, tt.wantOK)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,10 +12,11 @@ import (
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/config"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/docs"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/realtime"
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/store"
|
||||
"github.com/tim/cairnquire/apps/server/internal/config"
|
||||
"github.com/tim/cairnquire/apps/server/internal/docs"
|
||||
"github.com/tim/cairnquire/apps/server/internal/realtime"
|
||||
"github.com/tim/cairnquire/apps/server/internal/store"
|
||||
"github.com/tim/cairnquire/apps/server/internal/sync"
|
||||
)
|
||||
|
||||
//go:embed templates/*.gohtml static/*
|
||||
@@ -28,6 +29,8 @@ type Dependencies struct {
|
||||
Repository *docs.Repository
|
||||
ContentStore *store.ContentStore
|
||||
Hub *realtime.Hub
|
||||
SyncService *sync.Service
|
||||
SyncRepo *sync.Repository
|
||||
}
|
||||
|
||||
type Server struct {
|
||||
@@ -37,6 +40,8 @@ type Server struct {
|
||||
repository *docs.Repository
|
||||
contentStore *store.ContentStore
|
||||
hub *realtime.Hub
|
||||
syncService *sync.Service
|
||||
syncRepo *sync.Repository
|
||||
templates *template.Template
|
||||
webEnabled bool
|
||||
}
|
||||
@@ -61,6 +66,8 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
repository: deps.Repository,
|
||||
contentStore: deps.ContentStore,
|
||||
hub: deps.Hub,
|
||||
syncService: deps.SyncService,
|
||||
syncRepo: deps.SyncRepo,
|
||||
templates: templates,
|
||||
}
|
||||
|
||||
@@ -75,9 +82,11 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Use(server.timeoutExceptWebSocket(30 * time.Second))
|
||||
router.Use(server.requestLogger)
|
||||
router.Use(server.securityHeaders)
|
||||
router.Use(server.apiKeyMiddleware)
|
||||
|
||||
router.Get("/", server.handleIndex)
|
||||
router.Get("/health", server.handleHealth)
|
||||
router.Get("/sw.js", server.handleServiceWorker)
|
||||
router.Get("/ws", server.handleWebSocket)
|
||||
router.Post("/api/admin/login", server.handleAdminLogin)
|
||||
router.Get("/api/admin/users", server.handleAdminUsers)
|
||||
@@ -87,9 +96,17 @@ func New(deps Dependencies) (http.Handler, error) {
|
||||
router.Get("/docs", server.handleDocsIndex)
|
||||
router.Get("/docs/*", server.handleDocument)
|
||||
router.Get("/api/documents", server.handleDocuments)
|
||||
router.Post("/api/documents/*", server.handleDocumentSave)
|
||||
router.Get("/api/search", server.handleSearch)
|
||||
router.Post("/api/uploads", server.handleUpload)
|
||||
router.Get("/attachments/{hash}", server.handleAttachment)
|
||||
|
||||
// Sync protocol endpoints
|
||||
router.Post("/api/sync/init", server.handleSyncInit)
|
||||
router.Post("/api/sync/delta", server.handleSyncDelta)
|
||||
router.Post("/api/sync/resolve", server.handleSyncResolve)
|
||||
router.Get("/api/content/{hash}", server.handleContentFetch)
|
||||
|
||||
router.Handle("/static/*", http.StripPrefix("/static/", http.FileServer(mustSub("static"))))
|
||||
|
||||
if server.webEnabled {
|
||||
|
||||
29
apps/server/internal/httpserver/service_worker_test.go
Normal file
29
apps/server/internal/httpserver/service_worker_test.go
Normal file
@@ -0,0 +1,29 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestHandleServiceWorkerServesJavaScript(t *testing.T) {
|
||||
server := &Server{}
|
||||
req := httptest.NewRequest(http.MethodGet, "/sw.js", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
server.handleServiceWorker(recorder, req)
|
||||
|
||||
response := recorder.Result()
|
||||
if response.StatusCode != http.StatusOK {
|
||||
t.Fatalf("status = %d, want %d", response.StatusCode, http.StatusOK)
|
||||
}
|
||||
if got := response.Header.Get("Content-Type"); got != "application/javascript; charset=utf-8" {
|
||||
t.Fatalf("Content-Type = %q, want application/javascript; charset=utf-8", got)
|
||||
}
|
||||
if got := response.Header.Get("Service-Worker-Allowed"); got != "/" {
|
||||
t.Fatalf("Service-Worker-Allowed = %q, want /", got)
|
||||
}
|
||||
if recorder.Body.Len() == 0 {
|
||||
t.Fatal("expected non-empty service worker body")
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
(function () {
|
||||
const DB_NAME = "md-hub-cache";
|
||||
const DB_VERSION = 1;
|
||||
const DB_VERSION = 3;
|
||||
const STORE_DOCUMENTS = "documents";
|
||||
const STORE_CONTENT = "content";
|
||||
const STORE_PAGES = "pages";
|
||||
const STORE_PENDING_EDITS = "pending_edits";
|
||||
|
||||
function openDB() {
|
||||
return new Promise(function (resolve, reject) {
|
||||
@@ -21,10 +23,22 @@
|
||||
if (!db.objectStoreNames.contains(STORE_CONTENT)) {
|
||||
db.createObjectStore(STORE_CONTENT, { keyPath: "path" });
|
||||
}
|
||||
if (!db.objectStoreNames.contains(STORE_PAGES)) {
|
||||
db.createObjectStore(STORE_PAGES, { keyPath: "path" });
|
||||
}
|
||||
if (!db.objectStoreNames.contains(STORE_PENDING_EDITS)) {
|
||||
db.createObjectStore(STORE_PENDING_EDITS, { keyPath: "path" });
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
function normalizePath(path) {
|
||||
if (!path) return "/";
|
||||
if (path === "/") return path;
|
||||
return path.replace(/\/$/, "") || "/";
|
||||
}
|
||||
|
||||
function cacheDocuments(documents) {
|
||||
return openDB().then(function (db) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
@@ -91,10 +105,158 @@
|
||||
});
|
||||
}
|
||||
|
||||
function cachePage(path, html, title) {
|
||||
const normalizedPath = normalizePath(path);
|
||||
return openDB().then(function (db) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PAGES, "readwrite");
|
||||
const store = tx.objectStore(STORE_PAGES);
|
||||
store.put({
|
||||
path: normalizedPath,
|
||||
html: html,
|
||||
title: title,
|
||||
cachedAt: Date.now(),
|
||||
});
|
||||
tx.oncomplete = function () {
|
||||
resolve();
|
||||
};
|
||||
tx.onerror = function () {
|
||||
reject(tx.error);
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getCachedPage(path) {
|
||||
const normalizedPath = normalizePath(path);
|
||||
return openDB().then(function (db) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PAGES, "readonly");
|
||||
const store = tx.objectStore(STORE_PAGES);
|
||||
const request = store.get(normalizedPath);
|
||||
request.onsuccess = function () {
|
||||
resolve(request.result);
|
||||
};
|
||||
request.onerror = function () {
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function putPendingEdit(path, content, baseHash) {
|
||||
const normalizedPath = normalizePath(path);
|
||||
return openDB().then(function (db) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PENDING_EDITS, "readwrite");
|
||||
const store = tx.objectStore(STORE_PENDING_EDITS);
|
||||
store.put({
|
||||
path: normalizedPath,
|
||||
content: content,
|
||||
baseHash: baseHash || "",
|
||||
conflict: null,
|
||||
retries: 0,
|
||||
updatedAt: Date.now(),
|
||||
});
|
||||
tx.oncomplete = function () {
|
||||
resolve();
|
||||
};
|
||||
tx.onerror = function () {
|
||||
reject(tx.error);
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function markPendingEditConflict(path, conflict) {
|
||||
const normalizedPath = normalizePath(path);
|
||||
return openDB().then(function (db) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PENDING_EDITS, "readwrite");
|
||||
const store = tx.objectStore(STORE_PENDING_EDITS);
|
||||
const request = store.get(normalizedPath);
|
||||
request.onsuccess = function () {
|
||||
const record = request.result;
|
||||
if (!record) {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
record.conflict = conflict;
|
||||
record.updatedAt = Date.now();
|
||||
store.put(record);
|
||||
};
|
||||
tx.oncomplete = function () {
|
||||
resolve();
|
||||
};
|
||||
tx.onerror = function () {
|
||||
reject(tx.error);
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getPendingEdits() {
|
||||
return openDB().then(function (db) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PENDING_EDITS, "readonly");
|
||||
const store = tx.objectStore(STORE_PENDING_EDITS);
|
||||
const request = store.getAll();
|
||||
request.onsuccess = function () {
|
||||
resolve(request.result || []);
|
||||
};
|
||||
request.onerror = function () {
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function getPendingEdit(path) {
|
||||
const normalizedPath = normalizePath(path);
|
||||
return openDB().then(function (db) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PENDING_EDITS, "readonly");
|
||||
const store = tx.objectStore(STORE_PENDING_EDITS);
|
||||
const request = store.get(normalizedPath);
|
||||
request.onsuccess = function () {
|
||||
resolve(request.result);
|
||||
};
|
||||
request.onerror = function () {
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function deletePendingEdit(path) {
|
||||
const normalizedPath = normalizePath(path);
|
||||
return openDB().then(function (db) {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PENDING_EDITS, "readwrite");
|
||||
const store = tx.objectStore(STORE_PENDING_EDITS);
|
||||
store.delete(normalizedPath);
|
||||
tx.oncomplete = function () {
|
||||
resolve();
|
||||
};
|
||||
tx.onerror = function () {
|
||||
reject(tx.error);
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
window.MDHubCache = {
|
||||
cacheDocuments: cacheDocuments,
|
||||
cacheContent: cacheContent,
|
||||
cachePage: cachePage,
|
||||
putPendingEdit: putPendingEdit,
|
||||
markPendingEditConflict: markPendingEditConflict,
|
||||
getPendingEdits: getPendingEdits,
|
||||
getPendingEdit: getPendingEdit,
|
||||
deletePendingEdit: deletePendingEdit,
|
||||
getCachedDocuments: getCachedDocuments,
|
||||
getCachedContent: getCachedContent,
|
||||
getCachedPage: getCachedPage,
|
||||
normalizePath: normalizePath,
|
||||
};
|
||||
})();
|
||||
|
||||
BIN
apps/server/internal/httpserver/static/cairnquire logo@2x.webp
Normal file
BIN
apps/server/internal/httpserver/static/cairnquire logo@2x.webp
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 415 KiB |
579
apps/server/internal/httpserver/static/editor.js
Normal file
579
apps/server/internal/httpserver/static/editor.js
Normal file
@@ -0,0 +1,579 @@
|
||||
(function () {
|
||||
var form = document.querySelector("[data-editor-form]");
|
||||
var textarea = document.querySelector("[data-document-editor]");
|
||||
var statusNodes = document.querySelectorAll("[data-sync-status], [data-sync-status-secondary]");
|
||||
var hashEl = document.querySelector("[data-editor-hash]");
|
||||
var documentShell = document.querySelector("[data-document-path][data-document-hash]");
|
||||
var conflictNotice = document.querySelector("[data-conflict-notice]");
|
||||
var conflictHash = document.querySelector("[data-conflict-hash]");
|
||||
var conflictStatus = document.querySelector("[data-conflict-status]");
|
||||
var conflictDiff = document.querySelector("[data-conflict-diff]");
|
||||
var conflictApply = document.querySelector("[data-conflict-apply]");
|
||||
var conflictDismiss = document.querySelector("[data-conflict-dismiss]");
|
||||
var conflictResolution = document.querySelector("[data-conflict-resolution]");
|
||||
var conflictResolutionMount = document.querySelector("[data-conflict-monaco-mount]");
|
||||
var conflictUseServer = document.querySelector("[data-conflict-use='server']");
|
||||
var conflictUseLocal = document.querySelector("[data-conflict-use='local']");
|
||||
var conflictUseBoth = document.querySelector("[data-conflict-use='both']");
|
||||
var monacoContainer = document.querySelector("[data-monaco-mount]");
|
||||
var monacoLoaded = false;
|
||||
var monacoReadyPromise = null;
|
||||
var monacoDarkTheme = "cairnquire-dark";
|
||||
var monacoLightTheme = "cairnquire-light";
|
||||
|
||||
if (!form || !textarea || statusNodes.length === 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
var path = form.getAttribute("data-document-path");
|
||||
var baseHash = documentShell ? documentShell.getAttribute("data-document-hash") : "";
|
||||
var saveTimer = null;
|
||||
var lastSavedValue = textarea.value;
|
||||
var editor = null;
|
||||
var currentConflict = null;
|
||||
var currentConflictLocalContent = "";
|
||||
var resolvedConflictContent = "";
|
||||
var conflictDiffView = null;
|
||||
var resolutionEditor = null;
|
||||
var suppressResolutionEvents = false;
|
||||
|
||||
function setStatus(nextStatus) {
|
||||
statusNodes.forEach(function (node) {
|
||||
node.textContent = nextStatus;
|
||||
node.dataset.state = nextStatus.toLowerCase();
|
||||
});
|
||||
}
|
||||
|
||||
function getEditorValue() {
|
||||
return editor ? editor.getValue() : textarea.value;
|
||||
}
|
||||
|
||||
function setEditorValue(value) {
|
||||
textarea.value = value;
|
||||
if (editor && editor.getValue() !== value) {
|
||||
editor.setValue(value);
|
||||
}
|
||||
}
|
||||
|
||||
function getResolutionValue() {
|
||||
return resolutionEditor ? resolutionEditor.getValue() : resolvedConflictContent;
|
||||
}
|
||||
|
||||
function setResolutionEditorValue(value) {
|
||||
resolvedConflictContent = value;
|
||||
if (conflictResolution) {
|
||||
conflictResolution.value = value;
|
||||
}
|
||||
if (resolutionEditor && resolutionEditor.getValue() !== value) {
|
||||
suppressResolutionEvents = true;
|
||||
resolutionEditor.setValue(value);
|
||||
suppressResolutionEvents = false;
|
||||
}
|
||||
}
|
||||
|
||||
function ensureTrailingNewline(value) {
|
||||
return value.endsWith("\n") ? value : value + "\n";
|
||||
}
|
||||
|
||||
function buildCombinedResolution(serverContent, localContent) {
|
||||
return ensureTrailingNewline(serverContent) + "\n" + ensureTrailingNewline(localContent);
|
||||
}
|
||||
|
||||
function setConflictMessage(message) {
|
||||
if (conflictStatus) {
|
||||
conflictStatus.textContent = message;
|
||||
}
|
||||
}
|
||||
|
||||
function setResolutionContent(content, message) {
|
||||
setResolutionEditorValue(content);
|
||||
if (conflictApply) {
|
||||
conflictApply.disabled = false;
|
||||
}
|
||||
if (message) {
|
||||
setConflictMessage(message);
|
||||
}
|
||||
}
|
||||
|
||||
async function loadDiffs() {
|
||||
var modules = await Promise.all([
|
||||
import("https://cdn.jsdelivr.net/npm/@pierre/diffs@1.1.22/+esm"),
|
||||
import("https://cdn.jsdelivr.net/npm/@pierre/diffs@1.1.22/dist/style.js"),
|
||||
]);
|
||||
return {
|
||||
renderer: modules[0],
|
||||
stylesheet: modules[1].default || "",
|
||||
};
|
||||
}
|
||||
|
||||
function styleDiffContainer(diffContainer) {
|
||||
diffContainer.style.setProperty("--diffs-light-bg", "#fcfaf5");
|
||||
diffContainer.style.setProperty("--diffs-light", "#1c2430");
|
||||
diffContainer.style.setProperty("--diffs-dark-bg", "#1e1e1e");
|
||||
diffContainer.style.setProperty("--diffs-dark", "#e8ecf0");
|
||||
diffContainer.style.setProperty("--diffs-addition-color", "#3f8f59");
|
||||
diffContainer.style.setProperty("--diffs-deletion-color", "#c8553d");
|
||||
diffContainer.style.setProperty("--diffs-modified-color", "#c67a2a");
|
||||
diffContainer.style.setProperty("--diffs-font-family", "'Iosevka', 'JetBrains Mono', ui-monospace, SFMono-Regular, monospace");
|
||||
diffContainer.style.setProperty("--diffs-header-font-family", "'Inter', system-ui, -apple-system, BlinkMacSystemFont, sans-serif");
|
||||
}
|
||||
|
||||
function injectDiffStyles(diffContainer, stylesheet) {
|
||||
var root = diffContainer.shadowRoot;
|
||||
if (!root || !stylesheet || root.querySelector("[data-cairnquire-diffs-style]")) {
|
||||
return;
|
||||
}
|
||||
|
||||
var style = document.createElement("style");
|
||||
style.setAttribute("data-cairnquire-diffs-style", "");
|
||||
style.textContent = stylesheet;
|
||||
root.prepend(style);
|
||||
}
|
||||
|
||||
function renderConflictResolver(conflict, localContent) {
|
||||
if (!conflictDiff) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (conflictDiffView) {
|
||||
conflictDiffView.cleanUp();
|
||||
conflictDiffView = null;
|
||||
}
|
||||
conflictDiff.replaceChildren();
|
||||
currentConflictLocalContent = localContent;
|
||||
setResolutionEditorValue(localContent);
|
||||
if (conflictApply) {
|
||||
conflictApply.disabled = false;
|
||||
}
|
||||
ensureResolutionEditor();
|
||||
setConflictMessage("Loading conflict resolver...");
|
||||
|
||||
loadDiffs().then(function (diffsModule) {
|
||||
var diffs = diffsModule.renderer;
|
||||
var diffContainer = document.createElement("div");
|
||||
styleDiffContainer(diffContainer);
|
||||
conflictDiff.appendChild(diffContainer);
|
||||
var serverFile = {
|
||||
name: path,
|
||||
contents: conflict.currentContent || "",
|
||||
lang: "markdown",
|
||||
cacheKey: "server:" + (conflict.currentHash || ""),
|
||||
};
|
||||
var localFile = {
|
||||
name: path,
|
||||
contents: localContent,
|
||||
lang: "markdown",
|
||||
cacheKey: "local:" + (conflict.baseHash || "") + ":" + localContent.length,
|
||||
};
|
||||
|
||||
conflictDiffView = new diffs.FileDiff({
|
||||
disableFileHeader: false,
|
||||
diffStyle: "unified",
|
||||
diffIndicators: "classic",
|
||||
lineDiffType: "word",
|
||||
overflow: "scroll",
|
||||
parseDiffOptions: { context: 4 },
|
||||
});
|
||||
conflictDiffView.render({
|
||||
oldFile: serverFile,
|
||||
newFile: localFile,
|
||||
fileContainer: diffContainer,
|
||||
});
|
||||
injectDiffStyles(diffContainer, diffsModule.stylesheet);
|
||||
setConflictMessage("Red deletions are from the server copy. Green additions are from your queued edit.");
|
||||
}).catch(function () {
|
||||
setConflictMessage("Could not load the diff renderer. Your edit is still queued locally.");
|
||||
});
|
||||
}
|
||||
|
||||
function showConflict(conflict, localContent) {
|
||||
currentConflict = conflict;
|
||||
setStatus("Conflict");
|
||||
form.hidden = true;
|
||||
if (conflictHash && conflict && conflict.currentHash) {
|
||||
conflictHash.textContent = conflict.currentHash;
|
||||
}
|
||||
if (conflictNotice) {
|
||||
conflictNotice.hidden = false;
|
||||
}
|
||||
renderConflictResolver(conflict, localContent || getEditorValue());
|
||||
}
|
||||
|
||||
function hideConflict() {
|
||||
form.hidden = false;
|
||||
if (conflictNotice) {
|
||||
conflictNotice.hidden = true;
|
||||
}
|
||||
if (conflictDiff) {
|
||||
conflictDiff.replaceChildren();
|
||||
}
|
||||
if (conflictDiffView) {
|
||||
conflictDiffView.cleanUp();
|
||||
conflictDiffView = null;
|
||||
}
|
||||
if (conflictApply) {
|
||||
conflictApply.disabled = true;
|
||||
}
|
||||
setResolutionEditorValue("");
|
||||
currentConflict = null;
|
||||
currentConflictLocalContent = "";
|
||||
}
|
||||
|
||||
async function saveNow() {
|
||||
var value = getEditorValue();
|
||||
if (value === lastSavedValue) {
|
||||
setStatus("Saved");
|
||||
return;
|
||||
}
|
||||
|
||||
hideConflict();
|
||||
setStatus("Saving");
|
||||
|
||||
if (!window.MDHubSync) {
|
||||
setStatus("Queued");
|
||||
return;
|
||||
}
|
||||
|
||||
var result = await window.MDHubSync.saveDocument(path, value, baseHash);
|
||||
if (result.status === "saved") {
|
||||
lastSavedValue = value;
|
||||
if (hashEl && result.result && result.result.hash) {
|
||||
hashEl.textContent = result.result.hash;
|
||||
baseHash = result.result.hash;
|
||||
if (documentShell) {
|
||||
documentShell.setAttribute("data-document-hash", result.result.hash);
|
||||
}
|
||||
}
|
||||
setStatus("Saved");
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status === "conflict") {
|
||||
showConflict(result.conflict, value);
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus("Queued");
|
||||
}
|
||||
|
||||
async function applyResolvedConflict() {
|
||||
if (!window.MDHubSync || !currentConflict) {
|
||||
return;
|
||||
}
|
||||
|
||||
var resolutionContent = getResolutionValue();
|
||||
resolvedConflictContent = resolutionContent;
|
||||
setConflictMessage("Saving resolved document...");
|
||||
if (conflictApply) {
|
||||
conflictApply.disabled = true;
|
||||
}
|
||||
|
||||
var result = await window.MDHubSync.saveDocument(path, resolutionContent, currentConflict.currentHash);
|
||||
if (result.status === "saved") {
|
||||
setEditorValue(resolutionContent);
|
||||
lastSavedValue = resolutionContent;
|
||||
if (hashEl && result.result && result.result.hash) {
|
||||
hashEl.textContent = result.result.hash;
|
||||
baseHash = result.result.hash;
|
||||
if (documentShell) {
|
||||
documentShell.setAttribute("data-document-hash", result.result.hash);
|
||||
}
|
||||
}
|
||||
hideConflict();
|
||||
setStatus("Saved");
|
||||
return;
|
||||
}
|
||||
|
||||
if (result.status === "conflict") {
|
||||
showConflict(result.conflict, resolutionContent);
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus("Queued");
|
||||
setConflictMessage("Resolved document is queued and will retry when the server is reachable.");
|
||||
}
|
||||
|
||||
function restorePendingConflict() {
|
||||
if (!window.MDHubCache || !window.MDHubCache.getPendingEdit) {
|
||||
return;
|
||||
}
|
||||
var normalizedPath = window.MDHubCache.normalizePath("/docs/" + path.replace(/^\/+/, ""));
|
||||
window.MDHubCache.getPendingEdit(normalizedPath).then(function (pending) {
|
||||
if (pending && pending.conflict) {
|
||||
showConflict(pending.conflict, pending.content || getEditorValue());
|
||||
}
|
||||
}).catch(function () {});
|
||||
}
|
||||
|
||||
function scheduleSave() {
|
||||
setStatus("Unsaved");
|
||||
if (saveTimer) {
|
||||
clearTimeout(saveTimer);
|
||||
}
|
||||
saveTimer = setTimeout(function () {
|
||||
saveNow().catch(function () {
|
||||
setStatus("Queued");
|
||||
});
|
||||
}, 2000);
|
||||
}
|
||||
|
||||
function loadMonaco() {
|
||||
if (monacoReadyPromise) {
|
||||
return monacoReadyPromise;
|
||||
}
|
||||
if (monacoLoaded && window.monaco) {
|
||||
monacoReadyPromise = Promise.resolve();
|
||||
return monacoReadyPromise;
|
||||
}
|
||||
monacoLoaded = true;
|
||||
|
||||
var isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
|
||||
monacoReadyPromise = new Promise(function (resolve) {
|
||||
var script = document.createElement("script");
|
||||
script.src = "https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs/loader.js";
|
||||
script.onload = function () {
|
||||
require.config({
|
||||
paths: { vs: "https://cdn.jsdelivr.net/npm/monaco-editor@0.52.2/min/vs" },
|
||||
});
|
||||
require(["vs/editor/editor.main"], function () {
|
||||
monaco.editor.defineTheme(monacoDarkTheme, {
|
||||
base: "vs-dark",
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: "comment", foreground: "8B9DAF", fontStyle: "italic" },
|
||||
{ token: "keyword", foreground: "E8943A" },
|
||||
{ token: "string", foreground: "C9A96E" },
|
||||
{ token: "number", foreground: "C9A96E" },
|
||||
{ token: "type", foreground: "E8943A" },
|
||||
{ token: "tag", foreground: "E8943A" },
|
||||
{ token: "attribute.name", foreground: "D4A05A" },
|
||||
{ token: "attribute.value", foreground: "C9A96E" },
|
||||
{ token: "delimiter", foreground: "B0B8C4" },
|
||||
{ token: "variable", foreground: "D4D8DE" },
|
||||
],
|
||||
colors: {
|
||||
"editor.background": "#1E1E1E",
|
||||
"editor.foreground": "#E8ECF0",
|
||||
"editor.lineHighlightBackground": "#282828",
|
||||
"editor.selectionBackground": "#3A3A3A",
|
||||
"editorLineNumber.foreground": "#555555",
|
||||
"editorLineNumber.activeForeground": "#E8943A",
|
||||
"editor.inactiveSelectionBackground": "#333333",
|
||||
"editorCursor.foreground": "#E8943A",
|
||||
"editorIndentGuide.background": "#2A2A2A",
|
||||
"editorIndentGuide.activeBackground": "#3A3A3A",
|
||||
"editorWhitespace.foreground": "#2A2A2A",
|
||||
"editorGutter.background": "#1E1E1E",
|
||||
"editorOverviewRuler.border": "#1E1E1E",
|
||||
"scrollbarSlider.background": "#3A3A3A88",
|
||||
"scrollbarSlider.hoverBackground": "#4A4A4A88",
|
||||
"scrollbarSlider.activeBackground": "#5A5A5A88",
|
||||
"minimap.background": "#1E1E1E",
|
||||
},
|
||||
});
|
||||
|
||||
monaco.editor.defineTheme(monacoLightTheme, {
|
||||
base: "vs",
|
||||
inherit: true,
|
||||
rules: [
|
||||
{ token: "comment", foreground: "6A7B8C", fontStyle: "italic" },
|
||||
{ token: "keyword", foreground: "C67A2A" },
|
||||
{ token: "string", foreground: "8A6D3B" },
|
||||
{ token: "number", foreground: "8A6D3B" },
|
||||
{ token: "type", foreground: "C67A2A" },
|
||||
{ token: "tag", foreground: "C67A2A" },
|
||||
{ token: "attribute.name", foreground: "A87D3A" },
|
||||
{ token: "attribute.value", foreground: "8A6D3B" },
|
||||
],
|
||||
colors: {
|
||||
"editor.background": "#FCFAF5",
|
||||
"editor.foreground": "#1C2430",
|
||||
"editor.lineHighlightBackground": "#F0EDE5",
|
||||
"editor.selectionBackground": "#E8943A33",
|
||||
"editorLineNumber.foreground": "#AAAAAA",
|
||||
"editorLineNumber.activeForeground": "#C67A2A",
|
||||
"editorCursor.foreground": "#C67A2A",
|
||||
"editorIndentGuide.background": "#E8E5DD",
|
||||
"editorGutter.background": "#FCFAF5",
|
||||
},
|
||||
});
|
||||
|
||||
if (monacoContainer) {
|
||||
editor = monaco.editor.create(monacoContainer, {
|
||||
value: textarea.value,
|
||||
language: "markdown",
|
||||
theme: isDark ? monacoDarkTheme : monacoLightTheme,
|
||||
fontFamily: "'Iosevka', 'JetBrains Mono', ui-monospace, SFMono-Regular, monospace",
|
||||
fontSize: 14,
|
||||
lineHeight: 22,
|
||||
minimap: { enabled: false },
|
||||
wordWrap: "on",
|
||||
scrollBeyondLastLine: false,
|
||||
padding: { top: 12 },
|
||||
renderLineHighlight: "line",
|
||||
smoothScrolling: true,
|
||||
cursorBlinking: "smooth",
|
||||
cursorSmoothCaretAnimation: "on",
|
||||
bracketPairColorization: { enabled: true },
|
||||
automaticLayout: true,
|
||||
});
|
||||
|
||||
textarea.hidden = true;
|
||||
monacoContainer.classList.add("monaco-mounted");
|
||||
|
||||
editor.onDidChangeModelContent(function () {
|
||||
textarea.value = editor.getValue();
|
||||
scheduleSave();
|
||||
});
|
||||
|
||||
if (window.MDHubSync) {
|
||||
editor.addCommand(monaco.KeyMod.CtrlCmd | monaco.KeyCode.KeyS, function () {
|
||||
saveNow().catch(function () {
|
||||
setStatus("Queued");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
var darkMQ = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
darkMQ.addEventListener("change", function (e) {
|
||||
monaco.editor.setTheme(e.matches ? monacoDarkTheme : monacoLightTheme);
|
||||
});
|
||||
|
||||
editor.focus();
|
||||
}
|
||||
|
||||
resolve();
|
||||
});
|
||||
};
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
return monacoReadyPromise;
|
||||
}
|
||||
|
||||
function ensureResolutionEditor() {
|
||||
if (!conflictResolution || !conflictResolutionMount) {
|
||||
return;
|
||||
}
|
||||
|
||||
loadMonaco().then(function () {
|
||||
if (!window.monaco || resolutionEditor) {
|
||||
return;
|
||||
}
|
||||
|
||||
var isDark = window.matchMedia("(prefers-color-scheme: dark)").matches;
|
||||
resolutionEditor = monaco.editor.create(conflictResolutionMount, {
|
||||
value: conflictResolution.value || resolvedConflictContent,
|
||||
language: "markdown",
|
||||
theme: isDark ? monacoDarkTheme : monacoLightTheme,
|
||||
fontFamily: "'Iosevka', 'JetBrains Mono', ui-monospace, SFMono-Regular, monospace",
|
||||
fontSize: 14,
|
||||
lineHeight: 22,
|
||||
minimap: { enabled: false },
|
||||
wordWrap: "on",
|
||||
scrollBeyondLastLine: false,
|
||||
padding: { top: 12 },
|
||||
renderLineHighlight: "line",
|
||||
smoothScrolling: true,
|
||||
cursorBlinking: "smooth",
|
||||
cursorSmoothCaretAnimation: "on",
|
||||
bracketPairColorization: { enabled: true },
|
||||
automaticLayout: true,
|
||||
});
|
||||
|
||||
conflictResolution.hidden = true;
|
||||
conflictResolutionMount.classList.add("monaco-mounted");
|
||||
|
||||
resolutionEditor.onDidChangeModelContent(function () {
|
||||
if (suppressResolutionEvents) {
|
||||
return;
|
||||
}
|
||||
resolvedConflictContent = resolutionEditor.getValue();
|
||||
conflictResolution.value = resolvedConflictContent;
|
||||
if (conflictApply) {
|
||||
conflictApply.disabled = false;
|
||||
}
|
||||
setConflictMessage("Manual resolution updated. Apply it to save the resolved document.");
|
||||
});
|
||||
|
||||
resolutionEditor.focus();
|
||||
}).catch(function () {
|
||||
conflictResolution.hidden = false;
|
||||
});
|
||||
}
|
||||
|
||||
if (monacoContainer) {
|
||||
loadMonaco().catch(function () {
|
||||
textarea.addEventListener("input", scheduleSave);
|
||||
});
|
||||
} else {
|
||||
textarea.addEventListener("input", scheduleSave);
|
||||
}
|
||||
|
||||
form.addEventListener("submit", function (event) {
|
||||
event.preventDefault();
|
||||
saveNow().catch(function () {
|
||||
setStatus("Queued");
|
||||
});
|
||||
});
|
||||
|
||||
if (conflictApply) {
|
||||
conflictApply.addEventListener("click", function () {
|
||||
applyResolvedConflict().catch(function () {
|
||||
setStatus("Queued");
|
||||
setConflictMessage("Could not save the resolved document. It remains queued locally.");
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
if (conflictDismiss) {
|
||||
conflictDismiss.addEventListener("click", function () {
|
||||
hideConflict();
|
||||
});
|
||||
}
|
||||
|
||||
if (conflictResolution) {
|
||||
conflictResolution.addEventListener("input", function () {
|
||||
resolvedConflictContent = conflictResolution.value;
|
||||
if (conflictApply) {
|
||||
conflictApply.disabled = false;
|
||||
}
|
||||
setConflictMessage("Manual resolution updated. Apply it to save the resolved document.");
|
||||
});
|
||||
}
|
||||
|
||||
if (conflictUseServer) {
|
||||
conflictUseServer.addEventListener("click", function () {
|
||||
if (!currentConflict) {
|
||||
return;
|
||||
}
|
||||
setResolutionContent(currentConflict.currentContent || "", "Using the server copy as the resolution. You can edit it before applying.");
|
||||
});
|
||||
}
|
||||
|
||||
if (conflictUseLocal) {
|
||||
conflictUseLocal.addEventListener("click", function () {
|
||||
setResolutionContent(currentConflictLocalContent, "Using your queued edit as the resolution. You can edit it before applying.");
|
||||
});
|
||||
}
|
||||
|
||||
if (conflictUseBoth) {
|
||||
conflictUseBoth.addEventListener("click", function () {
|
||||
if (!currentConflict) {
|
||||
return;
|
||||
}
|
||||
setResolutionContent(
|
||||
buildCombinedResolution(currentConflict.currentContent || "", currentConflictLocalContent),
|
||||
"Using both versions as the resolution. Edit the combined content before applying."
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
restorePendingConflict();
|
||||
|
||||
document.addEventListener("keydown", function (e) {
|
||||
if ((e.metaKey || e.ctrlKey) && e.key === "s") {
|
||||
e.preventDefault();
|
||||
}
|
||||
});
|
||||
})();
|
||||
BIN
apps/server/internal/httpserver/static/favicon.png
Normal file
BIN
apps/server/internal/httpserver/static/favicon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.2 KiB |
@@ -2,8 +2,10 @@
|
||||
const notice = document.querySelector("[data-version-notice]");
|
||||
const reload = document.querySelector("[data-version-reload]");
|
||||
const offlineNotice = document.querySelector("[data-offline-notice]");
|
||||
const cachedNotice = document.querySelector("[data-cached-notice]");
|
||||
const documentShell = document.querySelector("[data-document-path][data-document-hash]");
|
||||
const browser = document.querySelector(".miller-browser");
|
||||
const isEditing = Boolean(document.querySelector("[data-editor-form]"));
|
||||
|
||||
// Auto-scroll miller browser to show the rightmost (active) column
|
||||
function scrollBrowserToRight() {
|
||||
@@ -23,6 +25,120 @@
|
||||
|
||||
scrollBrowserToRight();
|
||||
|
||||
function initColumnPreviewExpansion() {
|
||||
if (!browser) {
|
||||
return;
|
||||
}
|
||||
|
||||
let hoverTimer = null;
|
||||
let expandedColumn = null;
|
||||
|
||||
function isCompressedColumn(column) {
|
||||
return (
|
||||
column &&
|
||||
column.matches(".miller-column:not(:first-child):not(:last-child)")
|
||||
);
|
||||
}
|
||||
|
||||
function collapseColumn(column) {
|
||||
if (!column) return;
|
||||
column.classList.remove("is-preview-expanded");
|
||||
column.style.removeProperty("--expanded-column-width");
|
||||
if (expandedColumn === column) {
|
||||
expandedColumn = null;
|
||||
}
|
||||
}
|
||||
|
||||
function expandColumn(column) {
|
||||
if (!isCompressedColumn(column)) return;
|
||||
if (expandedColumn && expandedColumn !== column) {
|
||||
collapseColumn(expandedColumn);
|
||||
}
|
||||
|
||||
const expandedWidth = Math.min(Math.max(column.scrollWidth + 12, 192), 384);
|
||||
column.style.setProperty("--expanded-column-width", expandedWidth + "px");
|
||||
column.classList.add("is-preview-expanded");
|
||||
expandedColumn = column;
|
||||
|
||||
requestAnimationFrame(function () {
|
||||
const leftEdge = column.offsetLeft;
|
||||
const rightEdge = leftEdge + expandedWidth;
|
||||
let targetLeft = browser.scrollLeft;
|
||||
|
||||
if (leftEdge < browser.scrollLeft) {
|
||||
targetLeft = leftEdge - 8;
|
||||
} else if (rightEdge > browser.scrollLeft + browser.clientWidth) {
|
||||
targetLeft = rightEdge - browser.clientWidth + 8;
|
||||
}
|
||||
|
||||
browser.scrollTo({
|
||||
left: Math.max(0, targetLeft),
|
||||
behavior: "smooth",
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function scheduleExpansion(column) {
|
||||
if (!isCompressedColumn(column)) return;
|
||||
clearTimeout(hoverTimer);
|
||||
hoverTimer = setTimeout(function () {
|
||||
expandColumn(column);
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
browser.querySelectorAll(".miller-column").forEach(function (column) {
|
||||
column.addEventListener("pointerenter", function () {
|
||||
scheduleExpansion(column);
|
||||
});
|
||||
|
||||
column.addEventListener("mouseenter", function () {
|
||||
scheduleExpansion(column);
|
||||
});
|
||||
|
||||
column.addEventListener("mouseover", function () {
|
||||
if (!isCompressedColumn(column)) return;
|
||||
if (expandedColumn === column) return;
|
||||
scheduleExpansion(column);
|
||||
});
|
||||
|
||||
column.addEventListener("pointerleave", function () {
|
||||
clearTimeout(hoverTimer);
|
||||
collapseColumn(column);
|
||||
});
|
||||
|
||||
column.addEventListener("mouseleave", function () {
|
||||
clearTimeout(hoverTimer);
|
||||
collapseColumn(column);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
initColumnPreviewExpansion();
|
||||
|
||||
function updateCachedUI(isCached) {
|
||||
if (!cachedNotice) return;
|
||||
cachedNotice.hidden = !isCached;
|
||||
}
|
||||
|
||||
function cacheCurrentPage() {
|
||||
if (!window.MDHubCache) return;
|
||||
|
||||
const html = document.documentElement.outerHTML;
|
||||
const title = document.title;
|
||||
const pagePath = window.MDHubCache.normalizePath(window.location.pathname);
|
||||
window.MDHubCache.cachePage(pagePath, html, title).catch(function () {});
|
||||
}
|
||||
|
||||
function registerServiceWorker() {
|
||||
if (!("serviceWorker" in navigator)) return;
|
||||
window.addEventListener("load", function () {
|
||||
navigator.serviceWorker.register("/sw.js").catch(function () {});
|
||||
});
|
||||
}
|
||||
|
||||
registerServiceWorker();
|
||||
updateCachedUI(Boolean(window.__MDHUB_OFFLINE_CACHED__));
|
||||
|
||||
function updateOfflineUI() {
|
||||
if (!offlineNotice) return;
|
||||
if (navigator.onLine) {
|
||||
@@ -54,6 +170,8 @@
|
||||
}
|
||||
}
|
||||
|
||||
cacheCurrentPage();
|
||||
|
||||
// Fetch and cache documents
|
||||
function fetchAndCacheDocuments() {
|
||||
if (!window.MDHubCache) return;
|
||||
@@ -130,6 +248,9 @@
|
||||
const bodyEl = documentShell.querySelector(".markdown-body");
|
||||
if (bodyEl) bodyEl.innerHTML = html;
|
||||
|
||||
updateCachedUI(true);
|
||||
cacheCurrentPage();
|
||||
|
||||
// Re-render math and mermaid
|
||||
if (typeof renderMath === "function") renderMath();
|
||||
if (typeof renderMermaid === "function") renderMermaid();
|
||||
@@ -185,6 +306,10 @@
|
||||
|
||||
const change = payload.data;
|
||||
|
||||
if (isEditing && currentPath && change.path === currentPath) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (currentPath && change.path === currentPath && change.hash !== currentHash) {
|
||||
if (notice) notice.hidden = false;
|
||||
return;
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
:root {
|
||||
color-scheme: light;
|
||||
color-scheme: light dark;
|
||||
--bg: #fbf7ef;
|
||||
--panel: rgba(255, 255, 255, 0.82);
|
||||
--panel-strong: #ffffff;
|
||||
@@ -15,10 +15,28 @@
|
||||
font-family: "Charter", "Iowan Old Style", "Palatino Linotype", serif;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--bg: oklch(0.14 0.012 55);
|
||||
--panel: oklch(0.18 0.014 55 / 0.85);
|
||||
--panel-strong: oklch(0.21 0.015 55);
|
||||
--text: oklch(0.93 0.006 55);
|
||||
--muted: oklch(0.66 0.018 55);
|
||||
--accent: oklch(0.705 0.165 55);
|
||||
--accent-soft: oklch(0.705 0.165 55 / 0.14);
|
||||
--border: oklch(0.27 0.018 55);
|
||||
--shadow: 0 16px 48px oklch(0.08 0.02 55 / 0.35);
|
||||
}
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html {
|
||||
transition: color-scheme 0.4s ease;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
@@ -27,6 +45,18 @@ body {
|
||||
radial-gradient(circle at top left, rgba(56, 189, 248, 0.28), transparent 34%),
|
||||
radial-gradient(circle at bottom right, rgba(99, 102, 241, 0.22), transparent 30%),
|
||||
linear-gradient(180deg, #eef6ff 0%, #dbeafe 100%);
|
||||
transition:
|
||||
color 0.35s ease,
|
||||
background 0.55s ease;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
body {
|
||||
background:
|
||||
radial-gradient(circle at top left, oklch(0.24 0.04 55 / 0.45), transparent 36%),
|
||||
radial-gradient(circle at bottom right, oklch(0.20 0.035 50 / 0.35), transparent 32%),
|
||||
linear-gradient(180deg, oklch(0.12 0.012 55) 0%, oklch(0.14 0.012 55) 100%);
|
||||
}
|
||||
}
|
||||
|
||||
a {
|
||||
@@ -60,12 +90,20 @@ code {
|
||||
}
|
||||
|
||||
.site-brand {
|
||||
color: var(--text);
|
||||
font-size: 1.15rem;
|
||||
font-weight: 700;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
flex: 0 0 auto;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.site-brand img {
|
||||
display: block;
|
||||
width: auto;
|
||||
height: 2.5rem;
|
||||
max-width: min(12rem, 42vw);
|
||||
object-fit: contain;
|
||||
}
|
||||
|
||||
.site-nav {
|
||||
display: flex;
|
||||
gap: 1.25rem;
|
||||
@@ -157,6 +195,7 @@ code {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
overflow: hidden;
|
||||
transition: width 180ms ease, min-width 180ms ease, box-shadow 180ms ease;
|
||||
}
|
||||
|
||||
/* Root column - fixed width for top-level navigation */
|
||||
@@ -170,6 +209,18 @@ code {
|
||||
width: 48px;
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover,
|
||||
.miller-column:not(:first-child):not(:last-child).is-preview-expanded {
|
||||
width: var(--expanded-column-width, max-content);
|
||||
min-width: 12rem;
|
||||
max-width: 24rem;
|
||||
box-shadow: 8px 0 24px rgba(24, 32, 42, 0.08);
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover {
|
||||
transition-delay: 1s;
|
||||
}
|
||||
|
||||
/* Active/last column - grows to fill remaining sidebar space */
|
||||
.miller-column:last-child {
|
||||
flex: 1 1 auto;
|
||||
@@ -207,6 +258,17 @@ code {
|
||||
vertical-align: bottom;
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover h2,
|
||||
.miller-column:not(:first-child):not(:last-child).is-preview-expanded h2 {
|
||||
padding: 0.7rem 0.8rem;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover h2 .miller-column-title-text,
|
||||
.miller-column:not(:first-child):not(:last-child).is-preview-expanded h2 .miller-column-title-text {
|
||||
max-width: min(20rem, calc(var(--expanded-column-width, 14rem) - 2rem));
|
||||
}
|
||||
|
||||
.miller-column ul {
|
||||
margin: 0;
|
||||
padding: 0.3rem;
|
||||
@@ -252,6 +314,28 @@ code {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover a,
|
||||
.miller-column:not(:first-child):not(:last-child).is-preview-expanded a {
|
||||
padding: 0.4rem 0.5rem;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover .browser-item-label,
|
||||
.miller-column:not(:first-child):not(:last-child).is-preview-expanded .browser-item-label {
|
||||
justify-content: flex-start;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover .browser-item-name,
|
||||
.miller-column:not(:first-child):not(:last-child).is-preview-expanded .browser-item-name {
|
||||
max-width: min(18rem, calc(var(--expanded-column-width, 14rem) - 3.5rem));
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover .browser-item-chevron,
|
||||
.miller-column:not(:first-child):not(:last-child).is-preview-expanded .browser-item-chevron {
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.browser-item-label {
|
||||
display: inline-flex;
|
||||
min-width: 0;
|
||||
@@ -260,69 +344,24 @@ code {
|
||||
}
|
||||
|
||||
.browser-icon {
|
||||
position: relative;
|
||||
display: inline-block;
|
||||
width: 1rem;
|
||||
height: 0.9rem;
|
||||
height: 1rem;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.browser-icon--folder {
|
||||
margin-top: 0.1rem;
|
||||
border: 1px solid rgba(15, 91, 216, 0.24);
|
||||
border-radius: 0;
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.browser-icon--folder::before {
|
||||
position: absolute;
|
||||
top: -0.22rem;
|
||||
left: 0.1rem;
|
||||
width: 0.45rem;
|
||||
height: 0.25rem;
|
||||
border: 1px solid rgba(15, 91, 216, 0.24);
|
||||
border-bottom: 0;
|
||||
border-radius: 0;
|
||||
background: var(--accent-soft);
|
||||
content: "";
|
||||
color: #0f5bd8;
|
||||
}
|
||||
|
||||
.browser-icon--page {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 0;
|
||||
background: rgba(255, 255, 255, 0.72);
|
||||
}
|
||||
|
||||
.browser-icon--page::before {
|
||||
position: absolute;
|
||||
right: -1px;
|
||||
top: -1px;
|
||||
width: 0.3rem;
|
||||
height: 0.3rem;
|
||||
border-left: 1px solid var(--border);
|
||||
border-bottom: 1px solid var(--border);
|
||||
background: var(--panel);
|
||||
content: "";
|
||||
color: #465365;
|
||||
}
|
||||
|
||||
.browser-icon--root {
|
||||
width: 0.85rem;
|
||||
height: 0.85rem;
|
||||
border: 1.5px solid var(--accent);
|
||||
border-radius: 0;
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.browser-icon--root::before {
|
||||
position: absolute;
|
||||
top: 50%;
|
||||
left: 50%;
|
||||
width: 0.3rem;
|
||||
height: 0.3rem;
|
||||
border-radius: 0;
|
||||
background: var(--accent);
|
||||
transform: translate(-50%, -50%);
|
||||
content: "";
|
||||
width: 0.95rem;
|
||||
height: 0.95rem;
|
||||
color: var(--accent);
|
||||
}
|
||||
|
||||
.miller-column--root h2 {
|
||||
@@ -343,6 +382,12 @@ code {
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.browser-item-chevron {
|
||||
width: 0.95rem;
|
||||
height: 0.95rem;
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
/* Document shell */
|
||||
.document-shell,
|
||||
.error-panel,
|
||||
@@ -447,11 +492,51 @@ code {
|
||||
}
|
||||
|
||||
.document-meta h1 {
|
||||
margin: 0 0 0.75rem;
|
||||
margin: 0;
|
||||
font-size: 1.85rem;
|
||||
line-height: 1.1;
|
||||
}
|
||||
|
||||
.document-meta-panel {
|
||||
margin-top: 0.9rem;
|
||||
border: 1px solid var(--border);
|
||||
background: rgba(255, 255, 255, 0.45);
|
||||
}
|
||||
|
||||
.document-meta-panel summary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
padding: 0.7rem 0.85rem;
|
||||
cursor: pointer;
|
||||
list-style: none;
|
||||
color: var(--muted);
|
||||
font: 700 0.78rem/1.2 ui-monospace, SFMono-Regular, monospace;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.document-meta-panel summary::-webkit-details-marker {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.document-meta-panel summary::after {
|
||||
content: "+";
|
||||
margin-left: auto;
|
||||
color: var(--text);
|
||||
font-size: 1rem;
|
||||
letter-spacing: 0;
|
||||
}
|
||||
|
||||
.document-meta-panel[open] summary::after {
|
||||
content: "-";
|
||||
}
|
||||
|
||||
.document-meta-panel .meta-grid {
|
||||
padding: 0 0.85rem 0.85rem;
|
||||
}
|
||||
|
||||
.meta-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
||||
@@ -535,6 +620,26 @@ code {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.cached-notice {
|
||||
position: fixed;
|
||||
left: 1rem;
|
||||
bottom: 4.5rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
max-width: min(28rem, calc(100vw - 2rem));
|
||||
padding: 0.6rem 0.85rem;
|
||||
border: 1px solid rgba(37, 99, 235, 0.25);
|
||||
border-radius: 0;
|
||||
background: rgba(239, 246, 255, 0.96);
|
||||
color: #1d4ed8;
|
||||
font-size: 0.9rem;
|
||||
}
|
||||
|
||||
.cached-notice[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.offline-icon {
|
||||
display: inline-block;
|
||||
width: 0.6rem;
|
||||
@@ -544,6 +649,15 @@ code {
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.cached-icon {
|
||||
display: inline-block;
|
||||
width: 0.6rem;
|
||||
height: 0.6rem;
|
||||
border-radius: 0;
|
||||
background: #2563eb;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.version-notice[hidden] {
|
||||
display: none;
|
||||
}
|
||||
@@ -564,6 +678,284 @@ code {
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.document-meta__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.document-meta__header--editor {
|
||||
align-items: end;
|
||||
}
|
||||
|
||||
.document-edit-link {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-height: 2.4rem;
|
||||
padding: 0 0.9rem;
|
||||
border: 1px solid var(--border);
|
||||
color: var(--text);
|
||||
text-decoration: none;
|
||||
background: var(--panel);
|
||||
}
|
||||
|
||||
.document-shell--editor {
|
||||
display: grid;
|
||||
grid-template-rows: auto auto 1fr;
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.editor-form {
|
||||
min-height: 0;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.editor-form[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
[data-monaco-mount] {
|
||||
display: none;
|
||||
width: 100%;
|
||||
min-height: 60vh;
|
||||
height: 100%;
|
||||
border: 1px solid var(--border);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
[data-monaco-mount].monaco-mounted {
|
||||
display: block;
|
||||
}
|
||||
|
||||
.editor-form textarea {
|
||||
width: 100%;
|
||||
min-height: 60vh;
|
||||
height: 100%;
|
||||
resize: vertical;
|
||||
border: 1px solid var(--border);
|
||||
background: #fbfbf9;
|
||||
color: var(--text);
|
||||
padding: 1rem;
|
||||
font: 400 0.98rem/1.6 ui-monospace, SFMono-Regular, monospace;
|
||||
}
|
||||
|
||||
[data-monaco-mount].monaco-mounted ~ textarea {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@keyframes monaco-shimmer {
|
||||
0% { background-position: -200% 0; }
|
||||
100% { background-position: 200% 0; }
|
||||
}
|
||||
|
||||
[data-monaco-mount]:not(.monaco-mounted) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: linear-gradient(90deg, var(--panel-strong) 25%, var(--panel) 50%, var(--panel-strong) 75%);
|
||||
background-size: 200% 100%;
|
||||
animation: monaco-shimmer 1.5s ease infinite;
|
||||
color: var(--muted);
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.editor-status {
|
||||
display: inline-block;
|
||||
min-width: 5.5rem;
|
||||
font-weight: 600;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.editor-status[data-state="queued"] {
|
||||
color: #92400e;
|
||||
}
|
||||
|
||||
.editor-status[data-state="conflict"] {
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.editor-status[data-state="saving"],
|
||||
.editor-status[data-state="unsaved"] {
|
||||
color: #1d4ed8;
|
||||
}
|
||||
|
||||
.editor-conflict {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
margin-top: 0.8rem;
|
||||
padding: 0.75rem 0.9rem;
|
||||
border: 1px solid #fecaca;
|
||||
background: #fff1f2;
|
||||
color: #7f1d1d;
|
||||
}
|
||||
|
||||
.editor-conflict[hidden] {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.editor-conflict__header {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.editor-conflict__header > div:first-child {
|
||||
display: grid;
|
||||
gap: 0.2rem;
|
||||
}
|
||||
|
||||
.editor-conflict__actions {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.editor-conflict__actions button {
|
||||
min-height: 2.1rem;
|
||||
padding: 0 0.75rem;
|
||||
border: 1px solid #fecaca;
|
||||
background: #fff;
|
||||
color: #7f1d1d;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.editor-conflict__actions button:disabled {
|
||||
cursor: not-allowed;
|
||||
opacity: 0.55;
|
||||
}
|
||||
|
||||
.editor-conflict__choices {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.editor-conflict__choices button {
|
||||
min-height: 2rem;
|
||||
padding: 0 0.65rem;
|
||||
border: 1px solid rgba(127, 29, 29, 0.2);
|
||||
background: rgba(255, 255, 255, 0.72);
|
||||
color: #7f1d1d;
|
||||
cursor: pointer;
|
||||
font: inherit;
|
||||
font-size: 0.85rem;
|
||||
}
|
||||
|
||||
.editor-conflict__choices button[data-conflict-use="server"] {
|
||||
border-color: rgba(185, 28, 28, 0.25);
|
||||
background: rgba(254, 202, 202, 0.6);
|
||||
}
|
||||
|
||||
.editor-conflict__choices button[data-conflict-use="local"] {
|
||||
border-color: rgba(22, 101, 52, 0.25);
|
||||
background: rgba(187, 247, 208, 0.55);
|
||||
color: #14532d;
|
||||
}
|
||||
|
||||
.editor-conflict p {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.editor-conflict__legend {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem 1rem;
|
||||
font-size: 0.86rem;
|
||||
}
|
||||
|
||||
.editor-conflict__legend span {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.editor-conflict__swatch {
|
||||
width: 0.75rem;
|
||||
height: 0.75rem;
|
||||
border: 1px solid currentColor;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.editor-conflict__swatch--server {
|
||||
background: rgba(200, 85, 61, 0.2);
|
||||
color: #b91c1c;
|
||||
}
|
||||
|
||||
.editor-conflict__swatch--local {
|
||||
background: rgba(63, 143, 89, 0.2);
|
||||
color: #166534;
|
||||
}
|
||||
|
||||
.editor-conflict__diff {
|
||||
min-height: 16rem;
|
||||
overflow: auto;
|
||||
border: 1px solid rgba(127, 29, 29, 0.18);
|
||||
background: #fff;
|
||||
}
|
||||
|
||||
.editor-conflict code {
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.editor-conflict__resolution {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.editor-conflict__resolution label {
|
||||
font-size: 0.78rem;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.08em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.editor-conflict__resolution textarea {
|
||||
width: 100%;
|
||||
min-height: 16rem;
|
||||
resize: vertical;
|
||||
border: 1px solid rgba(127, 29, 29, 0.18);
|
||||
background: #fff;
|
||||
color: #1c2430;
|
||||
font-family: "Iosevka", "JetBrains Mono", ui-monospace, SFMono-Regular, monospace;
|
||||
font-size: 0.9rem;
|
||||
line-height: 1.55;
|
||||
padding: 0.75rem;
|
||||
}
|
||||
|
||||
[data-conflict-monaco-mount] {
|
||||
display: none;
|
||||
width: 100%;
|
||||
min-height: 18rem;
|
||||
height: 32rem;
|
||||
border: 1px solid rgba(127, 29, 29, 0.18);
|
||||
background: #fff;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
[data-conflict-monaco-mount].monaco-mounted {
|
||||
display: block;
|
||||
}
|
||||
|
||||
[data-conflict-monaco-mount].monaco-mounted + textarea {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.sr-only {
|
||||
position: absolute;
|
||||
width: 1px;
|
||||
height: 1px;
|
||||
padding: 0;
|
||||
margin: -1px;
|
||||
overflow: hidden;
|
||||
clip: rect(0, 0, 0, 0);
|
||||
white-space: nowrap;
|
||||
border: 0;
|
||||
}
|
||||
|
||||
/* Adaptive breakpoints */
|
||||
@media (max-width: 1024px) {
|
||||
.workspace-shell,
|
||||
@@ -579,6 +971,10 @@ code {
|
||||
}
|
||||
|
||||
@media (max-width: 768px) {
|
||||
.site-brand img {
|
||||
height: 2.25rem;
|
||||
}
|
||||
|
||||
.site-header__inner {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
@@ -655,6 +1051,12 @@ code {
|
||||
.meta-grid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.document-meta-panel summary,
|
||||
.document-meta__header {
|
||||
align-items: flex-start;
|
||||
flex-direction: column;
|
||||
}
|
||||
}
|
||||
|
||||
@media (min-width: 1600px) {
|
||||
@@ -709,3 +1111,149 @@ code {
|
||||
font-size: 0.85rem;
|
||||
font-family: ui-monospace, SFMono-Regular, monospace;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.site-header {
|
||||
border-bottom-color: oklch(0.28 0.018 55 / 0.5);
|
||||
background: oklch(0.16 0.014 55 / 0.92);
|
||||
}
|
||||
|
||||
.miller-column h2 {
|
||||
background: oklch(0.20 0.015 55 / 0.72);
|
||||
}
|
||||
|
||||
.miller-column a:hover,
|
||||
.miller-column a.is-active {
|
||||
background: var(--accent-soft);
|
||||
}
|
||||
|
||||
.browser-icon--folder {
|
||||
color: oklch(0.705 0.165 55);
|
||||
}
|
||||
|
||||
.browser-icon--page {
|
||||
color: oklch(0.66 0.018 55);
|
||||
}
|
||||
|
||||
.markdown-body pre {
|
||||
background: oklch(0.12 0.015 55);
|
||||
color: oklch(0.93 0.006 55);
|
||||
}
|
||||
|
||||
.markdown-body blockquote {
|
||||
border-left-color: var(--accent);
|
||||
background: oklch(0.705 0.165 55 / 0.07);
|
||||
}
|
||||
|
||||
.document-meta-panel {
|
||||
background: oklch(0.20 0.015 55 / 0.5);
|
||||
}
|
||||
|
||||
.editor-form textarea {
|
||||
background: oklch(0.15 0.012 55);
|
||||
color: var(--text);
|
||||
border-color: var(--border);
|
||||
}
|
||||
|
||||
.editor-conflict {
|
||||
border-color: oklch(0.55 0.18 25 / 0.4);
|
||||
background: oklch(0.22 0.04 25);
|
||||
color: oklch(0.75 0.12 25);
|
||||
}
|
||||
|
||||
.editor-conflict__actions button {
|
||||
border-color: oklch(0.55 0.18 25 / 0.4);
|
||||
background: oklch(0.18 0.018 55);
|
||||
color: oklch(0.75 0.12 25);
|
||||
}
|
||||
|
||||
.editor-conflict__choices button {
|
||||
border-color: oklch(0.55 0.18 25 / 0.35);
|
||||
background: oklch(0.18 0.018 55);
|
||||
color: oklch(0.75 0.12 25);
|
||||
}
|
||||
|
||||
.editor-conflict__choices button[data-conflict-use="server"] {
|
||||
border-color: oklch(0.65 0.18 25 / 0.45);
|
||||
background: oklch(0.28 0.08 25 / 0.8);
|
||||
color: oklch(0.78 0.13 25);
|
||||
}
|
||||
|
||||
.editor-conflict__choices button[data-conflict-use="local"] {
|
||||
border-color: oklch(0.65 0.15 145 / 0.45);
|
||||
background: oklch(0.25 0.07 145 / 0.8);
|
||||
color: oklch(0.78 0.12 145);
|
||||
}
|
||||
|
||||
.editor-conflict__swatch--server {
|
||||
background: oklch(0.35 0.12 25 / 0.65);
|
||||
color: oklch(0.72 0.14 25);
|
||||
}
|
||||
|
||||
.editor-conflict__swatch--local {
|
||||
background: oklch(0.33 0.10 145 / 0.65);
|
||||
color: oklch(0.72 0.13 145);
|
||||
}
|
||||
|
||||
.editor-conflict__diff {
|
||||
border-color: oklch(0.55 0.18 25 / 0.3);
|
||||
background: oklch(0.14 0.012 55);
|
||||
}
|
||||
|
||||
.editor-conflict__resolution textarea {
|
||||
border-color: oklch(0.55 0.18 25 / 0.3);
|
||||
background: oklch(0.14 0.012 55);
|
||||
color: var(--text);
|
||||
}
|
||||
|
||||
[data-conflict-monaco-mount] {
|
||||
border-color: oklch(0.55 0.18 25 / 0.3);
|
||||
background: oklch(0.14 0.012 55);
|
||||
}
|
||||
|
||||
.offline-notice {
|
||||
border-color: oklch(0.75 0.15 85 / 0.4);
|
||||
background: oklch(0.22 0.03 85 / 0.95);
|
||||
color: oklch(0.75 0.12 85);
|
||||
}
|
||||
|
||||
.offline-icon {
|
||||
background: oklch(0.78 0.165 85);
|
||||
}
|
||||
|
||||
.cached-notice {
|
||||
border-color: oklch(0.55 0.15 250 / 0.3);
|
||||
background: oklch(0.20 0.035 250 / 0.96);
|
||||
color: oklch(0.65 0.12 250);
|
||||
}
|
||||
|
||||
.cached-icon {
|
||||
background: oklch(0.60 0.15 250);
|
||||
}
|
||||
|
||||
.version-notice button {
|
||||
background: var(--accent);
|
||||
}
|
||||
|
||||
.miller-column:not(:first-child):not(:last-child):hover,
|
||||
.miller-column:not(:first-child):not(:last-child).is-preview-expanded {
|
||||
box-shadow: 8px 0 24px oklch(0.08 0.02 55 / 0.3);
|
||||
}
|
||||
|
||||
.editor-status[data-state="queued"] {
|
||||
color: oklch(0.65 0.12 75);
|
||||
}
|
||||
|
||||
.editor-status[data-state="conflict"] {
|
||||
color: oklch(0.60 0.18 25);
|
||||
}
|
||||
|
||||
.editor-status[data-state="saving"],
|
||||
.editor-status[data-state="unsaved"] {
|
||||
color: oklch(0.65 0.12 250);
|
||||
}
|
||||
|
||||
.markdown-body blockquote {
|
||||
background: oklch(0.705 0.165 55 / 0.07);
|
||||
}
|
||||
}
|
||||
|
||||
204
apps/server/internal/httpserver/static/sw.js
Normal file
204
apps/server/internal/httpserver/static/sw.js
Normal file
@@ -0,0 +1,204 @@
|
||||
const STATIC_CACHE = "md-hub-static-v1";
|
||||
const DB_NAME = "md-hub-cache";
|
||||
const DB_VERSION = 3;
|
||||
const STORE_PAGES = "pages";
|
||||
const STATIC_ASSETS = [
|
||||
"/static/site.css",
|
||||
"/static/cache.js",
|
||||
"/static/sync.js",
|
||||
"/static/realtime.js",
|
||||
"/static/editor.js",
|
||||
"/static/render.js",
|
||||
"/static/favicon.png",
|
||||
"/static/cairnquire%20logo%402x.webp",
|
||||
"/",
|
||||
"/docs",
|
||||
];
|
||||
|
||||
self.addEventListener("install", function (event) {
|
||||
event.waitUntil(
|
||||
caches.open(STATIC_CACHE).then(function (cache) {
|
||||
return cache.addAll(STATIC_ASSETS);
|
||||
}).then(function () {
|
||||
return self.skipWaiting();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener("activate", function (event) {
|
||||
event.waitUntil(
|
||||
caches.keys().then(function (keys) {
|
||||
return Promise.all(
|
||||
keys.map(function (key) {
|
||||
if (key === STATIC_CACHE) {
|
||||
return null;
|
||||
}
|
||||
return caches.delete(key);
|
||||
})
|
||||
);
|
||||
}).then(function () {
|
||||
return self.clients.claim();
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
self.addEventListener("fetch", function (event) {
|
||||
const request = event.request;
|
||||
if (request.method !== "GET") {
|
||||
return;
|
||||
}
|
||||
|
||||
const url = new URL(request.url);
|
||||
if (url.origin !== self.location.origin) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (request.mode === "navigate") {
|
||||
event.respondWith(handleNavigation(request, url));
|
||||
return;
|
||||
}
|
||||
|
||||
if (url.pathname.startsWith("/static/")) {
|
||||
event.respondWith(handleStaticAsset(request));
|
||||
}
|
||||
});
|
||||
|
||||
async function handleNavigation(request, url) {
|
||||
try {
|
||||
const response = await fetch(request);
|
||||
cachePageResponse(url.pathname, response.clone());
|
||||
return response;
|
||||
} catch (_error) {
|
||||
const cachedPage = await getCachedPage(url.pathname);
|
||||
if (cachedPage && cachedPage.html) {
|
||||
return new Response(markOfflineHTML(cachedPage.html), {
|
||||
headers: {
|
||||
"Content-Type": "text/html; charset=utf-8",
|
||||
"X-MDHub-Cache": "offline",
|
||||
},
|
||||
status: 200,
|
||||
});
|
||||
}
|
||||
|
||||
const fallback = await caches.match("/");
|
||||
if (fallback) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
return new Response("Offline", {
|
||||
status: 503,
|
||||
headers: { "Content-Type": "text/plain; charset=utf-8" },
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async function handleStaticAsset(request) {
|
||||
const cache = await caches.open(STATIC_CACHE);
|
||||
const cached = await cache.match(request);
|
||||
if (cached) {
|
||||
fetch(request).then(function (response) {
|
||||
if (response && response.ok) {
|
||||
cache.put(request, response.clone());
|
||||
}
|
||||
}).catch(function () {});
|
||||
return cached;
|
||||
}
|
||||
|
||||
const response = await fetch(request);
|
||||
if (response && response.ok) {
|
||||
cache.put(request, response.clone());
|
||||
}
|
||||
return response;
|
||||
}
|
||||
|
||||
async function cachePageResponse(pathname, response) {
|
||||
if (!response || !response.ok) {
|
||||
return;
|
||||
}
|
||||
|
||||
const contentType = response.headers.get("Content-Type") || "";
|
||||
if (contentType.indexOf("text/html") === -1) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const html = await response.text();
|
||||
await putCachedPage(normalizePath(pathname), {
|
||||
path: normalizePath(pathname),
|
||||
html: html,
|
||||
title: extractTitle(html),
|
||||
cachedAt: Date.now(),
|
||||
});
|
||||
} catch (_error) {}
|
||||
}
|
||||
|
||||
function markOfflineHTML(html) {
|
||||
const marker = "<script>window.__MDHUB_OFFLINE_CACHED__=true;<\/script>";
|
||||
if (html.indexOf("window.__MDHUB_OFFLINE_CACHED__") !== -1) {
|
||||
return html;
|
||||
}
|
||||
if (html.indexOf("</head>") !== -1) {
|
||||
return html.replace("</head>", marker + "</head>");
|
||||
}
|
||||
return marker + html;
|
||||
}
|
||||
|
||||
function extractTitle(html) {
|
||||
const match = html.match(/<title>([^<]*)<\/title>/i);
|
||||
return match ? match[1] : "Cairnquire";
|
||||
}
|
||||
|
||||
function normalizePath(path) {
|
||||
if (!path || path === "/") {
|
||||
return "/";
|
||||
}
|
||||
return path.replace(/\/$/, "") || "/";
|
||||
}
|
||||
|
||||
function openDB() {
|
||||
return new Promise(function (resolve, reject) {
|
||||
const request = indexedDB.open(DB_NAME, DB_VERSION);
|
||||
request.onerror = function () {
|
||||
reject(request.error);
|
||||
};
|
||||
request.onsuccess = function () {
|
||||
resolve(request.result);
|
||||
};
|
||||
request.onupgradeneeded = function (event) {
|
||||
const db = event.target.result;
|
||||
if (!db.objectStoreNames.contains(STORE_PAGES)) {
|
||||
db.createObjectStore(STORE_PAGES, { keyPath: "path" });
|
||||
}
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function putCachedPage(path, record) {
|
||||
const db = await openDB();
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PAGES, "readwrite");
|
||||
const store = tx.objectStore(STORE_PAGES);
|
||||
store.put(record);
|
||||
tx.oncomplete = function () {
|
||||
resolve();
|
||||
};
|
||||
tx.onerror = function () {
|
||||
reject(tx.error);
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function getCachedPage(path) {
|
||||
const db = await openDB();
|
||||
return new Promise(function (resolve, reject) {
|
||||
const tx = db.transaction(STORE_PAGES, "readonly");
|
||||
const store = tx.objectStore(STORE_PAGES);
|
||||
const request = store.get(normalizePath(path));
|
||||
request.onsuccess = function () {
|
||||
resolve(request.result);
|
||||
};
|
||||
request.onerror = function () {
|
||||
reject(request.error);
|
||||
};
|
||||
});
|
||||
}
|
||||
96
apps/server/internal/httpserver/static/sync.js
Normal file
96
apps/server/internal/httpserver/static/sync.js
Normal file
@@ -0,0 +1,96 @@
|
||||
(function () {
|
||||
if (!window.MDHubCache) {
|
||||
return;
|
||||
}
|
||||
|
||||
function normalizeDocPath(path) {
|
||||
if (!path) return "";
|
||||
return path.replace(/^\/+/, "");
|
||||
}
|
||||
|
||||
async function postDocument(path, content, baseHash) {
|
||||
const response = await fetch("/api/documents/" + normalizeDocPath(path), {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ content: content, baseHash: baseHash || "" }),
|
||||
});
|
||||
|
||||
const payload = await response.json().catch(function () {
|
||||
return {};
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
if (response.status === 409) {
|
||||
const conflict = new Error("document conflict");
|
||||
conflict.name = "DocumentConflictError";
|
||||
conflict.details = payload;
|
||||
throw conflict;
|
||||
}
|
||||
throw new Error("save failed");
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
|
||||
async function saveDocument(path, content, baseHash) {
|
||||
const normalizedPath = window.MDHubCache.normalizePath("/docs/" + normalizeDocPath(path));
|
||||
|
||||
try {
|
||||
const result = await postDocument(path, content, baseHash);
|
||||
await window.MDHubCache.deletePendingEdit(normalizedPath);
|
||||
return {
|
||||
status: "saved",
|
||||
result: result,
|
||||
};
|
||||
} catch (error) {
|
||||
if (error.name === "DocumentConflictError") {
|
||||
await window.MDHubCache.putPendingEdit(normalizedPath, content, baseHash);
|
||||
await window.MDHubCache.markPendingEditConflict(normalizedPath, error.details);
|
||||
return {
|
||||
status: "conflict",
|
||||
conflict: error.details,
|
||||
};
|
||||
}
|
||||
await window.MDHubCache.putPendingEdit(normalizedPath, content, baseHash);
|
||||
return {
|
||||
status: "queued",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
async function syncPending() {
|
||||
if (!navigator.onLine) {
|
||||
return;
|
||||
}
|
||||
|
||||
const pending = await window.MDHubCache.getPendingEdits();
|
||||
pending.sort(function (a, b) {
|
||||
return (a.updatedAt || 0) - (b.updatedAt || 0);
|
||||
});
|
||||
|
||||
for (const edit of pending) {
|
||||
try {
|
||||
await postDocument(edit.path.replace(/^\/docs\//, ""), edit.content, edit.baseHash);
|
||||
await window.MDHubCache.deletePendingEdit(edit.path);
|
||||
} catch (error) {
|
||||
if (error.name === "DocumentConflictError") {
|
||||
await window.MDHubCache.markPendingEditConflict(edit.path, error.details);
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
window.addEventListener("online", function () {
|
||||
syncPending().catch(function () {});
|
||||
});
|
||||
|
||||
syncPending().catch(function () {});
|
||||
|
||||
window.MDHubSync = {
|
||||
saveDocument: saveDocument,
|
||||
syncPending: syncPending,
|
||||
};
|
||||
})();
|
||||
141
apps/server/internal/httpserver/sync_handlers.go
Normal file
141
apps/server/internal/httpserver/sync_handlers.go
Normal file
@@ -0,0 +1,141 @@
|
||||
package httpserver
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"github.com/tim/cairnquire/apps/server/internal/sync"
|
||||
)
|
||||
|
||||
func (s *Server) handleSyncInit(w http.ResponseWriter, r *http.Request) {
|
||||
var req sync.InitRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.DeviceID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "deviceId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
userID := r.Context().Value("userID").(string)
|
||||
|
||||
snapshot, err := s.syncService.InitSync(r.Context(), req.DeviceID, userID)
|
||||
if err != nil {
|
||||
s.logger.Error("sync init failed", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to initialize sync"})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, sync.InitResponse{
|
||||
SnapshotID: snapshot.ID,
|
||||
ServerSnapshot: snapshot.Files,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleSyncDelta(w http.ResponseWriter, r *http.Request) {
|
||||
var req sync.DeltaRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.SnapshotID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshotId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
result, err := s.syncService.ApplyDelta(r.Context(), req.SnapshotID, sync.Delta{Changes: req.ClientDelta})
|
||||
if err != nil {
|
||||
s.logger.Error("sync delta failed", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to apply delta"})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, sync.DeltaResponse{
|
||||
ServerDelta: result.ServerDelta,
|
||||
Conflicts: result.Conflicts,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleSyncResolve(w http.ResponseWriter, r *http.Request) {
|
||||
var req sync.ResolveRequest
|
||||
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "invalid request body"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.SnapshotID == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "snapshotId is required"})
|
||||
return
|
||||
}
|
||||
|
||||
snapshot, err := s.syncService.ResolveConflicts(r.Context(), req.SnapshotID, req.Resolutions)
|
||||
if err != nil {
|
||||
s.logger.Error("sync resolve failed", "error", err)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to resolve conflicts"})
|
||||
return
|
||||
}
|
||||
|
||||
writeJSON(w, http.StatusOK, sync.ResolveResponse{
|
||||
NewSnapshotID: snapshot.ID,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Server) handleContentFetch(w http.ResponseWriter, r *http.Request) {
|
||||
hash := chi.URLParam(r, "hash")
|
||||
if hash == "" {
|
||||
writeJSON(w, http.StatusBadRequest, map[string]string{"error": "hash is required"})
|
||||
return
|
||||
}
|
||||
|
||||
content, err := s.syncService.GetContent(hash)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
writeJSON(w, http.StatusNotFound, map[string]string{"error": "content not found"})
|
||||
return
|
||||
}
|
||||
s.logger.Error("content fetch failed", "error", err, "hash", hash)
|
||||
writeJSON(w, http.StatusInternalServerError, map[string]string{"error": "failed to fetch content"})
|
||||
return
|
||||
}
|
||||
|
||||
w.Header().Set("Content-Type", "application/octet-stream")
|
||||
w.Header().Set("Cache-Control", "public, max-age=31536000, immutable")
|
||||
w.Header().Set("ETag", "\""+hash+"\"")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write(content)
|
||||
}
|
||||
|
||||
func (s *Server) apiKeyMiddleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Skip for non-sync routes
|
||||
if !strings.HasPrefix(r.URL.Path, "/api/sync/") && !strings.HasPrefix(r.URL.Path, "/api/content/") {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
apiKey := r.Header.Get("X-API-Key")
|
||||
if apiKey == "" {
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "missing API key"})
|
||||
return
|
||||
}
|
||||
|
||||
// Validate API key against database
|
||||
record, err := s.syncRepo.ValidateAPIKey(r.Context(), apiKey)
|
||||
if err != nil {
|
||||
s.logger.Warn("invalid api key", "error", err)
|
||||
writeJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid API key"})
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(r.Context(), "userID", record.UserID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
@@ -1,52 +1,68 @@
|
||||
{{ define "base" }}
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<title>{{ .Title }}</title>
|
||||
<link rel="stylesheet" href="/static/site.css" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
|
||||
</head>
|
||||
<body class="{{ .BodyClass }}">
|
||||
<header class="site-header">
|
||||
<div class="site-header__inner">
|
||||
<a class="site-brand" href="/">MD Hub Secure</a>
|
||||
<form class="site-search" action="/" method="get">
|
||||
<input type="search" name="q" placeholder="Search..." aria-label="Search documents" />
|
||||
<button type="submit" aria-label="Search">🔍</button>
|
||||
</form>
|
||||
<nav class="site-nav">
|
||||
<a href="/">Docs</a>
|
||||
{{ if .WebEnabled }}<a href="/app/">App</a>{{ end }}
|
||||
<a href="/health">Health</a>
|
||||
</nav>
|
||||
</div>
|
||||
</header>
|
||||
<main class="site-main">
|
||||
{{ if eq .BodyTemplate "index_content" }}
|
||||
{{ template "index_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "document_content" }}
|
||||
{{ template "document_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "search_content" }}
|
||||
{{ template "search_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "error_content" }}
|
||||
{{ template "error_content" .Data }}
|
||||
{{ end }}
|
||||
</main>
|
||||
<div class="offline-notice" data-offline-notice hidden>
|
||||
<span aria-hidden="true" class="offline-icon"></span>
|
||||
<p>You are offline. Some content may be stale.</p>
|
||||
|
||||
<head>
|
||||
<meta charset="utf-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
||||
<meta name="color-scheme" content="light dark" />
|
||||
<title>{{ .Title }}</title>
|
||||
<link rel="icon" type="image/png" href="/static/favicon.png" />
|
||||
<link rel="apple-touch-icon" href="/static/favicon.png" />
|
||||
<link rel="stylesheet" href="/static/site.css" />
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.css" />
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/mermaid@10/dist/mermaid.min.js"></script>
|
||||
<script defer src="https://cdn.jsdelivr.net/npm/katex@0.16.9/dist/katex.min.js"></script>
|
||||
</head>
|
||||
|
||||
<body class="{{ .BodyClass }}">
|
||||
<header class="site-header">
|
||||
<div class="site-header__inner">
|
||||
<a class="site-brand" href="/" aria-label="Cairnquire home">
|
||||
<img src="/static/cairnquire%20logo%402x.webp" alt="" width="160" height="40" decoding="async" />
|
||||
<span class="sr-only">Cairnquire</span>
|
||||
</a>
|
||||
<form class="site-search" action="/" method="get">
|
||||
<input type="search" name="q" placeholder="Search..." aria-label="Search documents" />
|
||||
<button type="submit" aria-label="Search">🔍</button>
|
||||
</form>
|
||||
<nav class="site-nav">
|
||||
<a href="/">Docs</a>
|
||||
{{ if .WebEnabled }}<a href="/app/">Admin</a>{{ end }}
|
||||
</nav>
|
||||
</div>
|
||||
<div class="version-notice" data-version-notice hidden>
|
||||
<p>A newer version is available.</p>
|
||||
<button type="button" data-version-reload>Reload</button>
|
||||
</div>
|
||||
<script src="/static/cache.js" defer></script>
|
||||
<script src="/static/realtime.js" defer></script>
|
||||
<script src="/static/render.js" defer></script>
|
||||
</body>
|
||||
</header>
|
||||
<main class="site-main">
|
||||
{{ if eq .BodyTemplate "index_content" }}
|
||||
{{ template "index_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "document_content" }}
|
||||
{{ template "document_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "document_edit_content" }}
|
||||
{{ template "document_edit_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "search_content" }}
|
||||
{{ template "search_content" .Data }}
|
||||
{{ else if eq .BodyTemplate "error_content" }}
|
||||
{{ template "error_content" .Data }}
|
||||
{{ end }}
|
||||
</main>
|
||||
<div class="offline-notice" data-offline-notice hidden>
|
||||
<span aria-hidden="true" class="offline-icon"></span>
|
||||
<p>You are offline. Some content may be stale.</p>
|
||||
</div>
|
||||
<div class="cached-notice" data-cached-notice hidden>
|
||||
<span aria-hidden="true" class="cached-icon"></span>
|
||||
<p>Viewing cached offline content.</p>
|
||||
</div>
|
||||
<div class="version-notice" data-version-notice hidden>
|
||||
<p>A newer version is available.</p>
|
||||
<button type="button" data-version-reload>Reload</button>
|
||||
</div>
|
||||
<script src="/static/cache.js" defer></script>
|
||||
<script src="/static/sync.js" defer></script>
|
||||
<script src="/static/realtime.js" defer></script>
|
||||
<script src="/static/editor.js" defer></script>
|
||||
<script src="/static/render.js" defer></script>
|
||||
</body>
|
||||
|
||||
</html>
|
||||
{{ end }}
|
||||
|
||||
@@ -19,29 +19,37 @@
|
||||
</ol>
|
||||
</nav>
|
||||
<div class="document-meta">
|
||||
<h1>{{ .Title }}</h1>
|
||||
<dl class="meta-grid">
|
||||
<div>
|
||||
<dt>File</dt>
|
||||
<dd><code>{{ .Path }}</code></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Hash</dt>
|
||||
<dd><code>{{ .Hash }}</code></dd>
|
||||
</div>
|
||||
{{ if .Tags }}
|
||||
<div class="document-meta__header">
|
||||
<h1>{{ .Title }}</h1>
|
||||
<a class="document-edit-link" href="/docs/{{ trimMd .Path }}/edit">Edit</a>
|
||||
</div>
|
||||
<details class="document-meta-panel">
|
||||
<summary>
|
||||
<span>Document details</span>
|
||||
</summary>
|
||||
<dl class="meta-grid">
|
||||
<div>
|
||||
<dt>Tags</dt>
|
||||
<dd>
|
||||
<ul class="tag-list">
|
||||
{{ range .Tags }}
|
||||
<li><a href="/?tag={{ . }}">#{{ . }}</a></li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
</dd>
|
||||
<dt>File</dt>
|
||||
<dd><code>{{ .Path }}</code></dd>
|
||||
</div>
|
||||
{{ end }}
|
||||
</dl>
|
||||
<div>
|
||||
<dt>Hash</dt>
|
||||
<dd><code>{{ .Hash }}</code></dd>
|
||||
</div>
|
||||
{{ if .Tags }}
|
||||
<div>
|
||||
<dt>Tags</dt>
|
||||
<dd>
|
||||
<ul class="tag-list">
|
||||
{{ range .Tags }}
|
||||
<li><a href="/?tag={{ . }}">#{{ . }}</a></li>
|
||||
{{ end }}
|
||||
</ul>
|
||||
</dd>
|
||||
</div>
|
||||
{{ end }}
|
||||
</dl>
|
||||
</details>
|
||||
</div>
|
||||
|
||||
<div class="markdown-body">
|
||||
@@ -57,7 +65,7 @@
|
||||
<section class="miller-column {{ if eq .Title "Content" }}miller-column--root{{ end }}" aria-label="{{ .Title }}">
|
||||
<h2 title="{{ .Title }}">
|
||||
{{ if eq .Title "Content" }}
|
||||
<span class="browser-icon browser-icon--root" aria-hidden="true"></span>
|
||||
{{ template "icon-library" }}
|
||||
{{ end }}
|
||||
<span class="miller-column-title-text">{{ .Title }}</span>
|
||||
</h2>
|
||||
@@ -66,10 +74,10 @@
|
||||
<li>
|
||||
<a class="{{ if .Active }}is-active{{ end }} {{ if .IsFolder }}is-folder{{ end }}" href="{{ .URL }}" title="{{ .Name }}">
|
||||
<span class="browser-item-label">
|
||||
<span class="browser-icon {{ if .IsFolder }}browser-icon--folder{{ else }}browser-icon--page{{ end }}" aria-hidden="true"></span>
|
||||
{{ if .IsFolder }}{{ template "icon-folder" }}{{ else }}{{ template "icon-file-text" }}{{ end }}
|
||||
<span class="browser-item-name">{{ .Name }}</span>
|
||||
</span>
|
||||
{{ if .IsFolder }}<span class="browser-item-chevron" aria-hidden="true">›</span>{{ end }}
|
||||
{{ if .IsFolder }}{{ template "icon-chevron-right" }}{{ end }}
|
||||
</a>
|
||||
</li>
|
||||
{{ end }}
|
||||
@@ -78,3 +86,34 @@
|
||||
{{ end }}
|
||||
</nav>
|
||||
{{ end }}
|
||||
|
||||
{{ define "icon-folder" }}
|
||||
<svg class="browser-icon browser-icon--folder" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.7-.9l-.8-1.2A2 2 0 0 0 7.9 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z"></path>
|
||||
</svg>
|
||||
{{ end }}
|
||||
|
||||
{{ define "icon-file-text" }}
|
||||
<svg class="browser-icon browser-icon--page" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z"></path>
|
||||
<path d="M14 2v4a2 2 0 0 0 2 2h4"></path>
|
||||
<path d="M10 9H8"></path>
|
||||
<path d="M16 13H8"></path>
|
||||
<path d="M16 17H8"></path>
|
||||
</svg>
|
||||
{{ end }}
|
||||
|
||||
{{ define "icon-library" }}
|
||||
<svg class="browser-icon browser-icon--root" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.9" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="m16 6 4 14"></path>
|
||||
<path d="M12 6v14"></path>
|
||||
<path d="M8 8v12"></path>
|
||||
<path d="M4 4v16"></path>
|
||||
</svg>
|
||||
{{ end }}
|
||||
|
||||
{{ define "icon-chevron-right" }}
|
||||
<svg class="browser-item-chevron" aria-hidden="true" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.1" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="m9 18 6-6-6-6"></path>
|
||||
</svg>
|
||||
{{ end }}
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
{{ define "document_edit.gohtml" }}{{ template "base" . }}{{ end }}
|
||||
|
||||
{{ define "document_edit_content" }}
|
||||
<section class="workspace-shell workspace-shell--document-edit">
|
||||
{{ template "browser" .Browser }}
|
||||
<article class="document-shell document-shell--editor" data-document-path="{{ .Path }}" data-document-hash="{{ .Hash }}">
|
||||
<nav class="breadcrumbs" aria-label="Breadcrumb">
|
||||
<ol>
|
||||
{{ $lastIdx := sub (len .Breadcrumbs) 1 }}
|
||||
{{ range $i, $crumb := .Breadcrumbs }}
|
||||
<li>
|
||||
{{ if eq $i $lastIdx }}
|
||||
<span aria-current="page">{{ $crumb.Name }}</span>
|
||||
{{ else }}
|
||||
<a href="{{ $crumb.URL }}">{{ $crumb.Name }}</a>
|
||||
{{ end }}
|
||||
</li>
|
||||
{{ end }}
|
||||
</ol>
|
||||
</nav>
|
||||
<div class="document-meta">
|
||||
<div class="document-meta__header document-meta__header--editor">
|
||||
<div>
|
||||
<p class="eyebrow">Editing</p>
|
||||
<h1>{{ .Title }}</h1>
|
||||
</div>
|
||||
<a class="document-edit-link" href="/docs/{{ trimMd .Path }}">Done</a>
|
||||
</div>
|
||||
<details class="document-meta-panel">
|
||||
<summary>
|
||||
<span>Editor details</span>
|
||||
<span class="editor-status" data-sync-status>Saved</span>
|
||||
</summary>
|
||||
<dl class="meta-grid">
|
||||
<div>
|
||||
<dt>File</dt>
|
||||
<dd><code>{{ .Path }}</code></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Hash</dt>
|
||||
<dd><code data-editor-hash>{{ .Hash }}</code></dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>Status</dt>
|
||||
<dd><span class="editor-status" data-sync-status-secondary>Saved</span></dd>
|
||||
</div>
|
||||
</dl>
|
||||
</details>
|
||||
<div class="editor-conflict" data-conflict-notice hidden>
|
||||
<div class="editor-conflict__header">
|
||||
<div>
|
||||
<strong>Conflict detected.</strong>
|
||||
<span>The server has a newer copy (<code data-conflict-hash></code>). Resolve it before saving more edits.</span>
|
||||
</div>
|
||||
<div class="editor-conflict__actions">
|
||||
<button type="button" data-conflict-apply disabled>Apply Resolution</button>
|
||||
<button type="button" data-conflict-dismiss>Dismiss</button>
|
||||
</div>
|
||||
</div>
|
||||
<p data-conflict-status>Red deletions are from the server copy. Green additions are from your queued edit.</p>
|
||||
<div class="editor-conflict__legend" aria-label="Diff color meaning">
|
||||
<span><span class="editor-conflict__swatch editor-conflict__swatch--server"></span>Red / - Server copy</span>
|
||||
<span><span class="editor-conflict__swatch editor-conflict__swatch--local"></span>Green / + Your edit</span>
|
||||
</div>
|
||||
<div class="editor-conflict__choices" role="group" aria-label="Resolution starting point">
|
||||
<button type="button" data-conflict-use="server">Use Server</button>
|
||||
<button type="button" data-conflict-use="local">Use My Edit</button>
|
||||
<button type="button" data-conflict-use="both">Use Both</button>
|
||||
</div>
|
||||
<div class="editor-conflict__diff" data-conflict-diff></div>
|
||||
<div class="editor-conflict__resolution">
|
||||
<label for="conflict-resolution">Resolved document</label>
|
||||
<div data-conflict-monaco-mount></div>
|
||||
<textarea id="conflict-resolution" data-conflict-resolution spellcheck="false"></textarea>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<form class="editor-form" data-editor-form data-document-path="{{ .Path }}">
|
||||
<label class="sr-only" for="document-editor">Markdown editor</label>
|
||||
<div data-monaco-mount></div>
|
||||
<textarea id="document-editor" name="content" data-document-editor spellcheck="false">{{ .Source }}</textarea>
|
||||
</form>
|
||||
</article>
|
||||
</section>
|
||||
{{ end }}
|
||||
@@ -5,7 +5,7 @@
|
||||
{{ template "browser" .Browser }}
|
||||
<section class="empty-preview">
|
||||
<p class="eyebrow">Documents</p>
|
||||
<h1>MD Hub Secure</h1>
|
||||
<h1>Cairnquire</h1>
|
||||
</section>
|
||||
</section>
|
||||
{{ end }}
|
||||
|
||||
@@ -6,7 +6,7 @@ import (
|
||||
|
||||
"github.com/gorilla/websocket"
|
||||
|
||||
"github.com/tim/md-hub-secure/apps/server/internal/realtime"
|
||||
"github.com/tim/cairnquire/apps/server/internal/realtime"
|
||||
)
|
||||
|
||||
const (
|
||||
|
||||
@@ -53,7 +53,16 @@ func NewRenderer() *Renderer {
|
||||
}
|
||||
|
||||
func (r *Renderer) Render(content []byte) (Result, error) {
|
||||
title := extractTitle(string(content))
|
||||
title, titleFromHeading := extractTitle(string(content), "")
|
||||
return r.renderWithTitle(content, title, titleFromHeading)
|
||||
}
|
||||
|
||||
func (r *Renderer) RenderPath(content []byte, path string) (Result, error) {
|
||||
title, titleFromHeading := extractTitle(string(content), path)
|
||||
return r.renderWithTitle(content, title, titleFromHeading)
|
||||
}
|
||||
|
||||
func (r *Renderer) renderWithTitle(content []byte, title string, titleFromHeading bool) (Result, error) {
|
||||
tags := extractTags(string(content))
|
||||
prepared := preprocess(string(content))
|
||||
|
||||
@@ -62,7 +71,10 @@ func (r *Renderer) Render(content []byte) (Result, error) {
|
||||
return Result{}, fmt.Errorf("render markdown: %w", err)
|
||||
}
|
||||
|
||||
html := firstH1Pattern.ReplaceAllString(output.String(), "")
|
||||
html := output.String()
|
||||
if titleFromHeading {
|
||||
html = firstH1Pattern.ReplaceAllString(html, "")
|
||||
}
|
||||
|
||||
return Result{
|
||||
HTML: template.HTML(html),
|
||||
@@ -123,13 +135,14 @@ func normalizeAdmonition(line string) string {
|
||||
}
|
||||
}
|
||||
|
||||
func extractTitle(content string) string {
|
||||
func extractTitle(content string, path string) (string, bool) {
|
||||
for _, line := range strings.Split(content, "\n") {
|
||||
if strings.HasPrefix(line, "# ") {
|
||||
return strings.TrimSpace(strings.TrimPrefix(line, "# "))
|
||||
trimmed := strings.TrimSpace(line)
|
||||
if strings.HasPrefix(trimmed, "# ") {
|
||||
return strings.TrimSpace(strings.TrimPrefix(trimmed, "# ")), true
|
||||
}
|
||||
}
|
||||
return "Untitled"
|
||||
return titleFromPath(path), false
|
||||
}
|
||||
|
||||
func extractTags(content string) []string {
|
||||
@@ -169,3 +182,35 @@ func slugify(value string) string {
|
||||
}
|
||||
return strings.Trim(builder.String(), "-")
|
||||
}
|
||||
|
||||
func titleFromPath(path string) string {
|
||||
path = strings.Trim(path, "/")
|
||||
path = strings.TrimSuffix(path, ".md")
|
||||
if path == "" {
|
||||
return "Home"
|
||||
}
|
||||
|
||||
base := path
|
||||
if strings.HasSuffix(base, "/index") {
|
||||
base = strings.TrimSuffix(base, "/index")
|
||||
}
|
||||
if base == "index" {
|
||||
return "Home"
|
||||
}
|
||||
if idx := strings.LastIndex(base, "/"); idx >= 0 {
|
||||
base = base[idx+1:]
|
||||
}
|
||||
base = strings.ReplaceAll(base, "-", " ")
|
||||
base = strings.ReplaceAll(base, "_", " ")
|
||||
parts := strings.Fields(base)
|
||||
for i, part := range parts {
|
||||
if part == strings.ToUpper(part) {
|
||||
continue
|
||||
}
|
||||
parts[i] = strings.ToUpper(part[:1]) + strings.ToLower(part[1:])
|
||||
}
|
||||
if len(parts) == 0 {
|
||||
return "Home"
|
||||
}
|
||||
return strings.Join(parts, " ")
|
||||
}
|
||||
|
||||
@@ -20,4 +20,34 @@ func TestRenderRewritesWikiLinksAndTags(t *testing.T) {
|
||||
if len(result.Tags) != 2 || result.Tags[0] != "alpha" || result.Tags[1] != "beta" {
|
||||
t.Fatalf("unexpected tags: %#v", result.Tags)
|
||||
}
|
||||
|
||||
if strings.Contains(string(result.HTML), "<h1") {
|
||||
t.Fatalf("expected first h1 to be removed from body html, got %s", result.HTML)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderPathFallsBackToCleanedFileName(t *testing.T) {
|
||||
renderer := NewRenderer()
|
||||
|
||||
result, err := renderer.RenderPath([]byte("Body only\n"), "guide/api-reference.md")
|
||||
if err != nil {
|
||||
t.Fatalf("RenderPath() error = %v", err)
|
||||
}
|
||||
|
||||
if result.Title != "Api Reference" {
|
||||
t.Fatalf("Title = %q, want Api Reference", result.Title)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenderPathUsesFolderNameForIndexFiles(t *testing.T) {
|
||||
renderer := NewRenderer()
|
||||
|
||||
result, err := renderer.RenderPath([]byte("Body only\n"), "guide/index.md")
|
||||
if err != nil {
|
||||
t.Fatalf("RenderPath() error = %v", err)
|
||||
}
|
||||
|
||||
if result.Title != "Guide" {
|
||||
t.Fatalf("Title = %q, want Guide", result.Title)
|
||||
}
|
||||
}
|
||||
|
||||
114
apps/server/internal/sync/protocol.go
Normal file
114
apps/server/internal/sync/protocol.go
Normal file
@@ -0,0 +1,114 @@
|
||||
package sync
|
||||
|
||||
import "time"
|
||||
|
||||
// ChangeType represents the type of file change in a delta.
|
||||
type ChangeType string
|
||||
|
||||
const (
|
||||
ChangeCreate ChangeType = "create"
|
||||
ChangeUpdate ChangeType = "update"
|
||||
ChangeDelete ChangeType = "delete"
|
||||
ChangeRename ChangeType = "rename"
|
||||
)
|
||||
|
||||
// ResolutionStrategy defines how to resolve a sync conflict.
|
||||
type ResolutionStrategy string
|
||||
|
||||
const (
|
||||
ResolutionLastWriteWins ResolutionStrategy = "last-write-wins"
|
||||
ResolutionRenameBoth ResolutionStrategy = "rename-both"
|
||||
ResolutionManualMerge ResolutionStrategy = "manual-merge"
|
||||
ResolutionServerWins ResolutionStrategy = "server-wins"
|
||||
ResolutionClientWins ResolutionStrategy = "client-wins"
|
||||
)
|
||||
|
||||
// FileEntry represents a single file in a snapshot.
|
||||
type FileEntry struct {
|
||||
Path string `json:"path"`
|
||||
Hash string `json:"hash"`
|
||||
Size int64 `json:"size"`
|
||||
Modified time.Time `json:"modified"`
|
||||
}
|
||||
|
||||
// Snapshot represents a point-in-time view of the filesystem.
|
||||
type Snapshot struct {
|
||||
ID string `json:"id"`
|
||||
DeviceID string `json:"deviceId"`
|
||||
UserID string `json:"userId,omitempty"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
Files []FileEntry `json:"files"`
|
||||
}
|
||||
|
||||
// Change represents a single file change.
|
||||
type Change struct {
|
||||
Type ChangeType `json:"type"`
|
||||
Path string `json:"path"`
|
||||
OldPath string `json:"oldPath,omitempty"`
|
||||
Hash string `json:"hash,omitempty"`
|
||||
Size int64 `json:"size,omitempty"`
|
||||
Modified time.Time `json:"modified,omitempty"`
|
||||
}
|
||||
|
||||
// Delta is a list of changes since a snapshot.
|
||||
type Delta struct {
|
||||
Changes []Change `json:"changes"`
|
||||
}
|
||||
|
||||
// Conflict represents a file changed on both client and server.
|
||||
type Conflict struct {
|
||||
Path string `json:"path"`
|
||||
ServerHash string `json:"serverHash"`
|
||||
ClientHash string `json:"clientHash"`
|
||||
ServerModified time.Time `json:"serverModified"`
|
||||
ClientModified time.Time `json:"clientModified"`
|
||||
Strategy ResolutionStrategy `json:"strategy,omitempty"`
|
||||
}
|
||||
|
||||
// DeltaResult is the server's response to a delta upload.
|
||||
type DeltaResult struct {
|
||||
ServerDelta []Change `json:"serverDelta"`
|
||||
Conflicts []Conflict `json:"conflicts"`
|
||||
}
|
||||
|
||||
// Resolution is a user's choice for resolving a conflict.
|
||||
type Resolution struct {
|
||||
Path string `json:"path"`
|
||||
Strategy ResolutionStrategy `json:"strategy"`
|
||||
NewPath string `json:"newPath,omitempty"` // for rename-both
|
||||
}
|
||||
|
||||
// InitRequest starts a new sync session.
|
||||
type InitRequest struct {
|
||||
DeviceID string `json:"deviceId"`
|
||||
RootPath string `json:"rootPath"`
|
||||
}
|
||||
|
||||
// InitResponse returns the server's current snapshot.
|
||||
type InitResponse struct {
|
||||
SnapshotID string `json:"snapshotId"`
|
||||
ServerSnapshot []FileEntry `json:"serverSnapshot"`
|
||||
}
|
||||
|
||||
// DeltaRequest uploads client changes.
|
||||
type DeltaRequest struct {
|
||||
SnapshotID string `json:"snapshotId"`
|
||||
ClientDelta []Change `json:"clientDelta"`
|
||||
}
|
||||
|
||||
// DeltaResponse returns server changes and conflicts.
|
||||
type DeltaResponse struct {
|
||||
ServerDelta []Change `json:"serverDelta"`
|
||||
Conflicts []Conflict `json:"conflicts"`
|
||||
}
|
||||
|
||||
// ResolveRequest uploads conflict resolutions.
|
||||
type ResolveRequest struct {
|
||||
SnapshotID string `json:"snapshotId"`
|
||||
Resolutions []Resolution `json:"resolutions"`
|
||||
}
|
||||
|
||||
// ResolveResponse confirms the new snapshot.
|
||||
type ResolveResponse struct {
|
||||
NewSnapshotID string `json:"newSnapshotId"`
|
||||
}
|
||||
273
apps/server/internal/sync/service.go
Normal file
273
apps/server/internal/sync/service.go
Normal file
@@ -0,0 +1,273 @@
|
||||
package sync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
|
||||
"github.com/tim/cairnquire/apps/server/internal/docs"
|
||||
"github.com/tim/cairnquire/apps/server/internal/store"
|
||||
)
|
||||
|
||||
// Service handles sync protocol business logic.
|
||||
type Service struct {
|
||||
repo *Repository
|
||||
docService *docs.Service
|
||||
contentStore *store.ContentStore
|
||||
logger *slog.Logger
|
||||
sourceDir string
|
||||
}
|
||||
|
||||
// NewService creates a new sync service.
|
||||
func NewService(repo *Repository, docService *docs.Service, contentStore *store.ContentStore, sourceDir string, logger *slog.Logger) *Service {
|
||||
return &Service{
|
||||
repo: repo,
|
||||
docService: docService,
|
||||
contentStore: contentStore,
|
||||
logger: logger,
|
||||
sourceDir: sourceDir,
|
||||
}
|
||||
}
|
||||
|
||||
// InitSync creates a new snapshot from the current server state.
|
||||
func (s *Service) InitSync(ctx context.Context, deviceID, userID string) (*Snapshot, error) {
|
||||
files, err := s.buildSnapshotFromDisk(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build snapshot: %w", err)
|
||||
}
|
||||
|
||||
snap, err := s.repo.CreateSnapshot(ctx, deviceID, userID, files)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create snapshot: %w", err)
|
||||
}
|
||||
|
||||
s.logger.Info("sync initialized", "device", deviceID, "snapshot", snap.ID, "files", len(files))
|
||||
return snap, nil
|
||||
}
|
||||
|
||||
// ApplyDelta processes client changes and computes server delta + conflicts.
|
||||
func (s *Service) ApplyDelta(ctx context.Context, snapshotID string, clientDelta Delta) (*DeltaResult, error) {
|
||||
snap, err := s.repo.GetSnapshot(ctx, snapshotID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get snapshot: %w", err)
|
||||
}
|
||||
|
||||
serverFiles := make(map[string]FileEntry)
|
||||
for _, f := range snap.Files {
|
||||
serverFiles[f.Path] = f
|
||||
}
|
||||
|
||||
clientFiles := make(map[string]FileEntry)
|
||||
for _, c := range clientDelta.Changes {
|
||||
if c.Type == ChangeDelete || c.Type == ChangeRename {
|
||||
continue
|
||||
}
|
||||
clientFiles[c.Path] = FileEntry{
|
||||
Path: c.Path,
|
||||
Hash: c.Hash,
|
||||
Size: c.Size,
|
||||
Modified: c.Modified,
|
||||
}
|
||||
}
|
||||
|
||||
// Rebuild current server state (may have changed since snapshot)
|
||||
currentFiles, err := s.buildSnapshotFromDisk(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build current snapshot: %w", err)
|
||||
}
|
||||
|
||||
currentMap := make(map[string]FileEntry)
|
||||
for _, f := range currentFiles {
|
||||
currentMap[f.Path] = f
|
||||
}
|
||||
|
||||
var serverDelta []Change
|
||||
var conflicts []Conflict
|
||||
|
||||
// Detect server changes since snapshot
|
||||
for path, current := range currentMap {
|
||||
old, existed := serverFiles[path]
|
||||
if !existed {
|
||||
// Server created this file
|
||||
serverDelta = append(serverDelta, Change{
|
||||
Type: ChangeCreate,
|
||||
Path: path,
|
||||
Hash: current.Hash,
|
||||
Size: current.Size,
|
||||
Modified: current.Modified,
|
||||
})
|
||||
} else if old.Hash != current.Hash {
|
||||
// Server updated this file
|
||||
serverDelta = append(serverDelta, Change{
|
||||
Type: ChangeUpdate,
|
||||
Path: path,
|
||||
Hash: current.Hash,
|
||||
Size: current.Size,
|
||||
Modified: current.Modified,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Detect server deletions
|
||||
for path := range serverFiles {
|
||||
if _, exists := currentMap[path]; !exists {
|
||||
serverDelta = append(serverDelta, Change{
|
||||
Type: ChangeDelete,
|
||||
Path: path,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Check for conflicts: both client and server changed same file
|
||||
for _, clientChange := range clientDelta.Changes {
|
||||
if clientChange.Type == ChangeCreate || clientChange.Type == ChangeUpdate {
|
||||
serverCurrent, serverHas := currentMap[clientChange.Path]
|
||||
serverOld, serverHad := serverFiles[clientChange.Path]
|
||||
|
||||
if serverHad && serverHas && serverOld.Hash != serverCurrent.Hash &&
|
||||
serverCurrent.Hash != clientChange.Hash {
|
||||
conflicts = append(conflicts, Conflict{
|
||||
Path: clientChange.Path,
|
||||
ServerHash: serverCurrent.Hash,
|
||||
ClientHash: clientChange.Hash,
|
||||
ServerModified: serverCurrent.Modified,
|
||||
ClientModified: clientChange.Modified,
|
||||
Strategy: ResolutionLastWriteWins,
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return &DeltaResult{
|
||||
ServerDelta: serverDelta,
|
||||
Conflicts: conflicts,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// ResolveConflicts applies resolved changes and creates a new snapshot.
|
||||
func (s *Service) ResolveConflicts(ctx context.Context, snapshotID string, resolutions []Resolution) (*Snapshot, error) {
|
||||
snap, err := s.repo.GetSnapshot(ctx, snapshotID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get snapshot: %w", err)
|
||||
}
|
||||
|
||||
// Build a map of resolutions by path
|
||||
resMap := make(map[string]Resolution)
|
||||
for _, r := range resolutions {
|
||||
resMap[r.Path] = r
|
||||
}
|
||||
|
||||
// Get current server state
|
||||
currentFiles, err := s.buildSnapshotFromDisk(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("build current snapshot: %w", err)
|
||||
}
|
||||
|
||||
currentMap := make(map[string]FileEntry)
|
||||
for _, f := range currentFiles {
|
||||
currentMap[f.Path] = f
|
||||
}
|
||||
|
||||
// Apply resolutions to create the merged state
|
||||
merged := make(map[string]FileEntry)
|
||||
for path, f := range currentMap {
|
||||
merged[path] = f
|
||||
}
|
||||
|
||||
for _, res := range resolutions {
|
||||
switch res.Strategy {
|
||||
case ResolutionClientWins:
|
||||
// In a real implementation, we'd apply the client's content here.
|
||||
// For now, we keep the server state and mark it resolved.
|
||||
s.logger.Debug("conflict resolved: client wins", "path", res.Path)
|
||||
case ResolutionServerWins:
|
||||
// Keep server state (already in merged)
|
||||
s.logger.Debug("conflict resolved: server wins", "path", res.Path)
|
||||
case ResolutionRenameBoth:
|
||||
if existing, ok := merged[res.Path]; ok {
|
||||
merged[res.NewPath] = existing
|
||||
delete(merged, res.Path)
|
||||
}
|
||||
case ResolutionLastWriteWins:
|
||||
// Keep whichever is newer - in practice server state since
|
||||
// we haven't received client content yet
|
||||
s.logger.Debug("conflict resolved: last-write-wins", "path", res.Path)
|
||||
case ResolutionManualMerge:
|
||||
// Flag for later UI resolution
|
||||
s.logger.Debug("conflict deferred: manual merge", "path", res.Path)
|
||||
}
|
||||
}
|
||||
|
||||
// Create new snapshot from merged state
|
||||
var files []FileEntry
|
||||
for _, f := range merged {
|
||||
files = append(files, f)
|
||||
}
|
||||
|
||||
newSnap, err := s.repo.CreateSnapshot(ctx, snap.DeviceID, snap.UserID, files)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("create new snapshot: %w", err)
|
||||
}
|
||||
|
||||
s.logger.Info("conflicts resolved", "snapshot", snapshotID, "newSnapshot", newSnap.ID, "resolutions", len(resolutions))
|
||||
return newSnap, nil
|
||||
}
|
||||
|
||||
// GetContent returns raw file content by hash.
|
||||
func (s *Service) GetContent(hash string) ([]byte, error) {
|
||||
return s.contentStore.Read(hash)
|
||||
}
|
||||
|
||||
// buildSnapshotFromDisk walks the source directory and builds a file list.
|
||||
func (s *Service) buildSnapshotFromDisk(ctx context.Context) ([]FileEntry, error) {
|
||||
var files []FileEntry
|
||||
|
||||
err := filepath.WalkDir(s.sourceDir, func(path string, entry os.DirEntry, err error) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if entry.IsDir() {
|
||||
return nil
|
||||
}
|
||||
if filepath.Ext(path) != ".md" {
|
||||
return nil
|
||||
}
|
||||
|
||||
info, err := entry.Info()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
relative, err := filepath.Rel(s.sourceDir, path)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
relative = filepath.ToSlash(relative)
|
||||
|
||||
content, err := os.ReadFile(path)
|
||||
if err != nil {
|
||||
return fmt.Errorf("read file %s: %w", path, err)
|
||||
}
|
||||
|
||||
record, err := s.contentStore.PutBytes(content)
|
||||
if err != nil {
|
||||
return fmt.Errorf("store file %s: %w", path, err)
|
||||
}
|
||||
|
||||
files = append(files, FileEntry{
|
||||
Path: relative,
|
||||
Hash: record.Hash,
|
||||
Size: info.Size(),
|
||||
Modified: info.ModTime().UTC(),
|
||||
})
|
||||
|
||||
return nil
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return files, nil
|
||||
}
|
||||
231
apps/server/internal/sync/service_test.go
Normal file
231
apps/server/internal/sync/service_test.go
Normal file
@@ -0,0 +1,231 @@
|
||||
package sync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"log/slog"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/tim/cairnquire/apps/server/internal/database"
|
||||
"github.com/tim/cairnquire/apps/server/internal/docs"
|
||||
"github.com/tim/cairnquire/apps/server/internal/markdown"
|
||||
"github.com/tim/cairnquire/apps/server/internal/store"
|
||||
)
|
||||
|
||||
func setupTestDB(t *testing.T) *sql.DB {
|
||||
t.Helper()
|
||||
|
||||
dbPath := filepath.Join(t.TempDir(), "test.db")
|
||||
db, err := sql.Open("libsql", "file:"+dbPath)
|
||||
if err != nil {
|
||||
t.Fatalf("open test database: %v", err)
|
||||
}
|
||||
t.Cleanup(func() { db.Close() })
|
||||
|
||||
if _, err := db.Exec("PRAGMA foreign_keys=ON"); err != nil {
|
||||
t.Fatalf("enable foreign keys: %v", err)
|
||||
}
|
||||
|
||||
ctx := context.Background()
|
||||
if err := database.ApplyMigrations(ctx, db); err != nil {
|
||||
t.Fatalf("apply migrations: %v", err)
|
||||
}
|
||||
|
||||
return db
|
||||
}
|
||||
|
||||
func setupTestService(t *testing.T) (*Service, string) {
|
||||
t.Helper()
|
||||
|
||||
sourceDir := t.TempDir()
|
||||
storeDir := t.TempDir()
|
||||
|
||||
db := setupTestDB(t)
|
||||
|
||||
// Insert a test user to satisfy foreign key constraints
|
||||
if _, err := db.ExecContext(context.Background(), `
|
||||
INSERT INTO users (id, email, display_name, created_at)
|
||||
VALUES ('user:test', 'test@example.com', 'Test User', ?)
|
||||
`, time.Now().UTC().Format(time.RFC3339)); err != nil {
|
||||
t.Fatalf("insert test user: %v", err)
|
||||
}
|
||||
|
||||
// Create some test markdown files
|
||||
if err := os.WriteFile(filepath.Join(sourceDir, "hello.md"), []byte("# Hello\n\nWorld"), 0o644); err != nil {
|
||||
t.Fatalf("create hello.md: %v", err)
|
||||
}
|
||||
if err := os.WriteFile(filepath.Join(sourceDir, "guide.md"), []byte("# Guide\n\nSteps"), 0o644); err != nil {
|
||||
t.Fatalf("create guide.md: %v", err)
|
||||
}
|
||||
|
||||
contentStore, err := store.New(storeDir)
|
||||
if err != nil {
|
||||
t.Fatalf("create content store: %v", err)
|
||||
}
|
||||
|
||||
renderer := markdown.NewRenderer()
|
||||
repo := docs.NewRepository(db)
|
||||
docService := docs.NewService(sourceDir, contentStore, renderer, repo, slog.Default())
|
||||
syncRepo := NewRepository(db)
|
||||
|
||||
service := NewService(syncRepo, docService, contentStore, sourceDir, slog.Default())
|
||||
return service, sourceDir
|
||||
}
|
||||
|
||||
func TestInitSyncCreatesSnapshot(t *testing.T) {
|
||||
service, _ := setupTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
snap, err := service.InitSync(ctx, "device-1", "user:test")
|
||||
if err != nil {
|
||||
t.Fatalf("InitSync() error = %v", err)
|
||||
}
|
||||
|
||||
if snap.ID == "" {
|
||||
t.Fatal("expected snapshot ID to be set")
|
||||
}
|
||||
if snap.DeviceID != "device-1" {
|
||||
t.Fatalf("expected device ID device-1, got %s", snap.DeviceID)
|
||||
}
|
||||
if len(snap.Files) != 2 {
|
||||
t.Fatalf("expected 2 files, got %d", len(snap.Files))
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyDeltaDetectsServerChanges(t *testing.T) {
|
||||
service, sourceDir := setupTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
snap, err := service.InitSync(ctx, "device-1", "user:test")
|
||||
if err != nil {
|
||||
t.Fatalf("InitSync() error = %v", err)
|
||||
}
|
||||
|
||||
// Modify a file on the server
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if err := os.WriteFile(filepath.Join(sourceDir, "hello.md"), []byte("# Hello\n\nUpdated"), 0o644); err != nil {
|
||||
t.Fatalf("update hello.md: %v", err)
|
||||
}
|
||||
|
||||
// Client sends empty delta
|
||||
result, err := service.ApplyDelta(ctx, snap.ID, Delta{Changes: nil})
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyDelta() error = %v", err)
|
||||
}
|
||||
|
||||
if len(result.ServerDelta) != 1 {
|
||||
t.Fatalf("expected 1 server delta, got %d", len(result.ServerDelta))
|
||||
}
|
||||
|
||||
change := result.ServerDelta[0]
|
||||
if change.Type != ChangeUpdate {
|
||||
t.Fatalf("expected update change, got %s", change.Type)
|
||||
}
|
||||
if change.Path != "hello.md" {
|
||||
t.Fatalf("expected path hello.md, got %s", change.Path)
|
||||
}
|
||||
if len(result.Conflicts) != 0 {
|
||||
t.Fatalf("expected 0 conflicts, got %d", len(result.Conflicts))
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyDeltaDetectsConflicts(t *testing.T) {
|
||||
service, sourceDir := setupTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
snap, err := service.InitSync(ctx, "device-1", "user:test")
|
||||
if err != nil {
|
||||
t.Fatalf("InitSync() error = %v", err)
|
||||
}
|
||||
|
||||
// Both server and client change the same file
|
||||
time.Sleep(10 * time.Millisecond)
|
||||
if err := os.WriteFile(filepath.Join(sourceDir, "hello.md"), []byte("# Hello\n\nServer Update"), 0o644); err != nil {
|
||||
t.Fatalf("update hello.md: %v", err)
|
||||
}
|
||||
|
||||
// Client also changes the file (different content = different hash)
|
||||
clientChange := Change{
|
||||
Type: ChangeUpdate,
|
||||
Path: "hello.md",
|
||||
Hash: "clienthash123456789012345678901234567890123456789012345678901234",
|
||||
Size: 100,
|
||||
Modified: time.Now().UTC(),
|
||||
}
|
||||
|
||||
result, err := service.ApplyDelta(ctx, snap.ID, Delta{Changes: []Change{clientChange}})
|
||||
if err != nil {
|
||||
t.Fatalf("ApplyDelta() error = %v", err)
|
||||
}
|
||||
|
||||
if len(result.Conflicts) != 1 {
|
||||
t.Fatalf("expected 1 conflict, got %d", len(result.Conflicts))
|
||||
}
|
||||
|
||||
conflict := result.Conflicts[0]
|
||||
if conflict.Path != "hello.md" {
|
||||
t.Fatalf("expected conflict path hello.md, got %s", conflict.Path)
|
||||
}
|
||||
if conflict.Strategy != ResolutionLastWriteWins {
|
||||
t.Fatalf("expected strategy last-write-wins, got %s", conflict.Strategy)
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveConflictsCreatesNewSnapshot(t *testing.T) {
|
||||
service, _ := setupTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
snap, err := service.InitSync(ctx, "device-1", "user:test")
|
||||
if err != nil {
|
||||
t.Fatalf("InitSync() error = %v", err)
|
||||
}
|
||||
|
||||
resolutions := []Resolution{
|
||||
{
|
||||
Path: "hello.md",
|
||||
Strategy: ResolutionServerWins,
|
||||
},
|
||||
}
|
||||
|
||||
newSnap, err := service.ResolveConflicts(ctx, snap.ID, resolutions)
|
||||
if err != nil {
|
||||
t.Fatalf("ResolveConflicts() error = %v", err)
|
||||
}
|
||||
|
||||
if newSnap.ID == "" {
|
||||
t.Fatal("expected new snapshot ID to be set")
|
||||
}
|
||||
if newSnap.ID == snap.ID {
|
||||
t.Fatal("expected new snapshot ID to be different from old")
|
||||
}
|
||||
if len(newSnap.Files) != 2 {
|
||||
t.Fatalf("expected 2 files in new snapshot, got %d", len(newSnap.Files))
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetContentReturnsFileBytes(t *testing.T) {
|
||||
service, _ := setupTestService(t)
|
||||
ctx := context.Background()
|
||||
|
||||
snap, err := service.InitSync(ctx, "device-1", "user:test")
|
||||
if err != nil {
|
||||
t.Fatalf("InitSync() error = %v", err)
|
||||
}
|
||||
|
||||
if len(snap.Files) == 0 {
|
||||
t.Fatal("expected at least one file")
|
||||
}
|
||||
|
||||
hash := snap.Files[0].Hash
|
||||
content, err := service.GetContent(hash)
|
||||
if err != nil {
|
||||
t.Fatalf("GetContent() error = %v", err)
|
||||
}
|
||||
|
||||
if len(content) == 0 {
|
||||
t.Fatal("expected non-empty content")
|
||||
}
|
||||
}
|
||||
206
apps/server/internal/sync/store.go
Normal file
206
apps/server/internal/sync/store.go
Normal file
@@ -0,0 +1,206 @@
|
||||
package sync
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Repository provides database access for sync operations.
|
||||
type Repository struct {
|
||||
db *sql.DB
|
||||
}
|
||||
|
||||
func NewRepository(db *sql.DB) *Repository {
|
||||
return &Repository{db: db}
|
||||
}
|
||||
|
||||
// APIKeyRecord represents a stored API key.
|
||||
type APIKeyRecord struct {
|
||||
ID string `json:"id"`
|
||||
UserID string `json:"userId"`
|
||||
Name string `json:"name"`
|
||||
KeyHash string `json:"keyHash"`
|
||||
Scopes string `json:"scopes"`
|
||||
CreatedAt time.Time `json:"createdAt"`
|
||||
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
|
||||
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
|
||||
}
|
||||
|
||||
// CreateSnapshot persists a new snapshot and returns it with an ID.
|
||||
func (r *Repository) CreateSnapshot(ctx context.Context, deviceID, userID string, files []FileEntry) (*Snapshot, error) {
|
||||
id := generateID("snap", deviceID)
|
||||
now := time.Now().UTC()
|
||||
|
||||
tx, err := r.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO sync_snapshots (id, device_id, user_id, created_at)
|
||||
VALUES (?, ?, ?, ?)
|
||||
`, id, deviceID, userID, now.Format(time.RFC3339)); err != nil {
|
||||
return nil, fmt.Errorf("insert snapshot: %w", err)
|
||||
}
|
||||
|
||||
for _, f := range files {
|
||||
if _, err := tx.ExecContext(ctx, `
|
||||
INSERT INTO sync_files (snapshot_id, path, hash, size_bytes, modified_at)
|
||||
VALUES (?, ?, ?, ?, ?)
|
||||
`, id, f.Path, f.Hash, f.Size, f.Modified.Format(time.RFC3339)); err != nil {
|
||||
return nil, fmt.Errorf("insert sync file %s: %w", f.Path, err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("commit snapshot: %w", err)
|
||||
}
|
||||
|
||||
return &Snapshot{
|
||||
ID: id,
|
||||
DeviceID: deviceID,
|
||||
CreatedAt: now,
|
||||
Files: files,
|
||||
}, nil
|
||||
}
|
||||
|
||||
// GetSnapshot retrieves a snapshot by ID.
|
||||
func (r *Repository) GetSnapshot(ctx context.Context, snapshotID string) (*Snapshot, error) {
|
||||
var snap Snapshot
|
||||
var created string
|
||||
var userID sql.NullString
|
||||
|
||||
err := r.db.QueryRowContext(ctx, `
|
||||
SELECT id, device_id, user_id, created_at
|
||||
FROM sync_snapshots
|
||||
WHERE id = ?
|
||||
`, snapshotID).Scan(&snap.ID, &snap.DeviceID, &userID, &created)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
snap.CreatedAt, err = time.Parse(time.RFC3339, created)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse created_at: %w", err)
|
||||
}
|
||||
if userID.Valid {
|
||||
snap.UserID = userID.String
|
||||
}
|
||||
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT path, hash, size_bytes, modified_at
|
||||
FROM sync_files
|
||||
WHERE snapshot_id = ?
|
||||
ORDER BY path ASC
|
||||
`, snapshotID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query sync files: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
for rows.Next() {
|
||||
var f FileEntry
|
||||
var modified string
|
||||
if err := rows.Scan(&f.Path, &f.Hash, &f.Size, &modified); err != nil {
|
||||
return nil, fmt.Errorf("scan sync file: %w", err)
|
||||
}
|
||||
f.Modified, err = time.Parse(time.RFC3339, modified)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse modified_at: %w", err)
|
||||
}
|
||||
snap.Files = append(snap.Files, f)
|
||||
}
|
||||
|
||||
return &snap, rows.Err()
|
||||
}
|
||||
|
||||
// ValidateAPIKey checks if an API key hash is valid and returns the associated user.
|
||||
func (r *Repository) ValidateAPIKey(ctx context.Context, keyHash string) (*APIKeyRecord, error) {
|
||||
var record APIKeyRecord
|
||||
var created, expires, lastUsed string
|
||||
|
||||
err := r.db.QueryRowContext(ctx, `
|
||||
SELECT id, user_id, name, key_hash, scopes, created_at, expires_at, last_used_at
|
||||
FROM api_keys
|
||||
WHERE key_hash = ?
|
||||
`, keyHash).Scan(
|
||||
&record.ID, &record.UserID, &record.Name, &record.KeyHash,
|
||||
&record.Scopes, &created, &expires, &lastUsed,
|
||||
)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
record.CreatedAt, err = time.Parse(time.RFC3339, created)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse created_at: %w", err)
|
||||
}
|
||||
if expires != "" {
|
||||
t, err := time.Parse(time.RFC3339, expires)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse expires_at: %w", err)
|
||||
}
|
||||
if time.Now().UTC().After(t) {
|
||||
return nil, fmt.Errorf("api key expired")
|
||||
}
|
||||
record.ExpiresAt = &t
|
||||
}
|
||||
if lastUsed != "" {
|
||||
t, err := time.Parse(time.RFC3339, lastUsed)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse last_used_at: %w", err)
|
||||
}
|
||||
record.LastUsedAt = &t
|
||||
}
|
||||
|
||||
// Update last_used_at
|
||||
now := time.Now().UTC().Format(time.RFC3339)
|
||||
if _, err := r.db.ExecContext(ctx, `
|
||||
UPDATE api_keys SET last_used_at = ? WHERE id = ?
|
||||
`, now, record.ID); err != nil {
|
||||
return nil, fmt.Errorf("update last_used_at: %w", err)
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// ListLatestFiles returns the most recent file states from the latest snapshot.
|
||||
func (r *Repository) ListLatestFiles(ctx context.Context, deviceID string) ([]FileEntry, error) {
|
||||
rows, err := r.db.QueryContext(ctx, `
|
||||
SELECT sf.path, sf.hash, sf.size_bytes, sf.modified_at
|
||||
FROM sync_files sf
|
||||
JOIN sync_snapshots ss ON ss.id = sf.snapshot_id
|
||||
WHERE ss.device_id = ?
|
||||
AND ss.created_at = (
|
||||
SELECT MAX(created_at) FROM sync_snapshots WHERE device_id = ?
|
||||
)
|
||||
ORDER BY sf.path ASC
|
||||
`, deviceID, deviceID)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("query latest files: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var files []FileEntry
|
||||
for rows.Next() {
|
||||
var f FileEntry
|
||||
var modified string
|
||||
if err := rows.Scan(&f.Path, &f.Hash, &f.Size, &modified); err != nil {
|
||||
return nil, fmt.Errorf("scan file: %w", err)
|
||||
}
|
||||
f.Modified, err = time.Parse(time.RFC3339, modified)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("parse modified: %w", err)
|
||||
}
|
||||
files = append(files, f)
|
||||
}
|
||||
|
||||
return files, rows.Err()
|
||||
}
|
||||
|
||||
func generateID(prefix, suffix string) string {
|
||||
return fmt.Sprintf("%s:%s:%d", prefix, suffix, time.Now().UnixNano())
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>MD Hub Secure App</title>
|
||||
<title>Cairnquire App</title>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
3372
apps/web/package-lock.json
generated
3372
apps/web/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@@ -1,5 +1,5 @@
|
||||
{
|
||||
"name": "md-hub-secure-web",
|
||||
"name": "cairnquire-web",
|
||||
"version": "0.1.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
|
||||
@@ -339,7 +339,10 @@ function WorkspaceView(props: {
|
||||
<section class="column-browser" aria-label="Workspace files">
|
||||
{columns.map((column) => (
|
||||
<div class="browser-column" key={column.prefix || "root"}>
|
||||
<header>{column.title}</header>
|
||||
<header>
|
||||
<Folder size={15} />
|
||||
{column.title}
|
||||
</header>
|
||||
<div class="item-list">
|
||||
{column.items.map((item) => (
|
||||
<button
|
||||
|
||||
@@ -4,7 +4,7 @@ import { App } from "./app";
|
||||
import "./styles.css";
|
||||
|
||||
render(
|
||||
<LocationProvider>
|
||||
<LocationProvider scope="/app">
|
||||
<Router>{[<Route path="/*" component={App} />]}</Router>
|
||||
</LocationProvider>,
|
||||
document.getElementById("app")!,
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { defineConfig } from "vite";
|
||||
import preact from "@preact/preset-vite";
|
||||
|
||||
const serverTarget = "http://localhost:8080";
|
||||
|
||||
export default defineConfig({
|
||||
base: "/app/",
|
||||
plugins: [preact()],
|
||||
@@ -12,7 +14,27 @@ export default defineConfig({
|
||||
port: 5173,
|
||||
proxy: {
|
||||
"/api": {
|
||||
target: "http://localhost:8080",
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/attachments": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/docs": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/health": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/static": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/sw.js": {
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
"/ws": {
|
||||
@@ -20,7 +42,7 @@ export default defineConfig({
|
||||
ws: true,
|
||||
},
|
||||
"^/app$": {
|
||||
target: "http://localhost:8080",
|
||||
target: serverTarget,
|
||||
changeOrigin: true,
|
||||
},
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user