Compare commits

..

10 Commits

Author SHA1 Message Date
MangoPig 2ff7fbd9e7 Merge branch 'Fix/Backend/Posix-Hierarchy-Fix' 2026-06-22 11:14:08 +01:00
MangoPig 8a94d83e7e Fix: align POSIX hierarchy contract 2026-06-22 11:13:25 +01:00
MangoPig 07590f1c4f Merge branch 'Features/Backend/Posix-DB-Projection' 2026-06-21 22:03:43 +01:00
MangoPig 3c7a73853d Feat: add POSIX DB projection 2026-06-21 22:02:59 +01:00
MangoPig 9b4f1ce197 Merge branch 'Features/Backend/Posix-Lite-Persistence' 2026-06-21 21:03:38 +01:00
MangoPig 5735e3008d Feat: add POSIX-lite bootstrap foundation 2026-06-21 21:02:59 +01:00
MangoPig 626ae02df0 Docs: Update TODO roadmap 2026-06-21 15:43:04 +01:00
MangoPig 7f47ca84fa Merge branch 'Features/Frontend/Sidebar-Folder-Creation' 2026-06-21 12:32:27 +01:00
MangoPig eac4fb423e Feat: Add draggable shell trees 2026-06-21 12:31:47 +01:00
MangoPig 14ac0f46de Merge branch 'Fix/Frontend/Projects-Menu-Polish' 2026-06-20 07:56:47 +01:00
22 changed files with 2825 additions and 186 deletions
+2
View File
@@ -27,3 +27,5 @@ tmp/
bin/ bin/
.cgcignore .cgcignore
POSIX/
+52
View File
@@ -0,0 +1,52 @@
package main
import (
"context"
"fmt"
"log"
"os"
"moku-backend/internal/config"
"moku-backend/internal/database"
"moku-backend/internal/posixproj"
)
func main() {
command := "rebuild"
if len(os.Args) > 1 {
command = os.Args[1]
}
switch command {
case "rebuild":
if err := rebuildProjection(context.Background()); err != nil {
log.Fatalf("rebuild POSIX projection: %v", err)
}
default:
log.Fatalf("unsupported posix command %q (supported: rebuild)", command)
}
}
func rebuildProjection(ctx context.Context) error {
cfg := config.Load()
db, err := database.NewPostgres(cfg.PostgresURL)
if err != nil {
return fmt.Errorf("connect database: %w", err)
}
defer db.Close()
summary, err := posixproj.NewProjector(db, cfg.POSIXRoot).RebuildWithSummary(ctx)
if err != nil {
return err
}
fmt.Printf(
"POSIX projection rebuilt from %s\n total nodes: %d\n directories: %d\n files: %d\n",
cfg.POSIXRoot,
summary.TotalNodes,
summary.DirectoryCount,
summary.FileCount,
)
return nil
}
@@ -0,0 +1,45 @@
-- +goose Up
CREATE TYPE posix_node_kind AS ENUM ('directory', 'file');
CREATE TABLE IF NOT EXISTS posix_nodes (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
path TEXT NOT NULL UNIQUE,
parent_path TEXT,
name TEXT NOT NULL,
depth INTEGER NOT NULL,
node_kind posix_node_kind NOT NULL,
logical_type TEXT NOT NULL DEFAULT 'generic',
file_role TEXT,
resource_id TEXT,
resource_name TEXT,
resource_slug TEXT,
installation_id TEXT,
organization_id TEXT,
organization_slug TEXT,
department_slug TEXT,
team_slug TEXT,
project_slug TEXT,
personal_slug TEXT,
content_json JSONB,
size_bytes BIGINT NOT NULL DEFAULT 0,
checksum TEXT,
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
);
CREATE INDEX IF NOT EXISTS idx_posix_nodes_parent_path ON posix_nodes (parent_path);
CREATE INDEX IF NOT EXISTS idx_posix_nodes_logical_type ON posix_nodes (logical_type);
CREATE INDEX IF NOT EXISTS idx_posix_nodes_project_slug ON posix_nodes (project_slug);
CREATE INDEX IF NOT EXISTS idx_posix_nodes_department_slug ON posix_nodes (department_slug);
CREATE INDEX IF NOT EXISTS idx_posix_nodes_team_slug ON posix_nodes (team_slug);
-- +goose Down
DROP INDEX IF EXISTS idx_posix_nodes_team_slug;
DROP INDEX IF EXISTS idx_posix_nodes_department_slug;
DROP INDEX IF EXISTS idx_posix_nodes_project_slug;
DROP INDEX IF EXISTS idx_posix_nodes_logical_type;
DROP INDEX IF EXISTS idx_posix_nodes_parent_path;
DROP TABLE IF EXISTS posix_nodes;
DROP TYPE IF EXISTS posix_node_kind;
+194 -2
View File
@@ -4,13 +4,17 @@ package bootstrap
import ( import (
"context" "context"
"encoding/json"
"errors" "errors"
"fmt" "fmt"
"os"
"path/filepath"
"strings" "strings"
"github.com/jackc/pgx/v5" "github.com/jackc/pgx/v5"
"moku-backend/internal/database" "moku-backend/internal/database"
"moku-backend/internal/posixproj"
) )
const ( const (
@@ -42,6 +46,7 @@ var (
type Service struct { type Service struct {
db *database.DB db *database.DB
posixRoot string
} }
type SaveInstanceInput struct { type SaveInstanceInput struct {
@@ -172,8 +177,8 @@ type namedRecord struct {
Slug string `json:"slug"` Slug string `json:"slug"`
} }
func NewService(db *database.DB) *Service { func NewService(db *database.DB, posixRoot string) *Service {
return &Service{db: db} return &Service{db: db, posixRoot: strings.TrimSpace(posixRoot)}
} }
func (service *Service) SaveInstance(ctx context.Context, input SaveInstanceInput) (InstallationRecord, error) { func (service *Service) SaveInstance(ctx context.Context, input SaveInstanceInput) (InstallationRecord, error) {
@@ -405,6 +410,14 @@ func (service *Service) SaveStructure(ctx context.Context, input SaveStructureIn
return StructureRecord{}, err return StructureRecord{}, err
} }
if err := service.ensureBootstrapPOSIXSkeleton(installation, admin, organization, department, team, project); err != nil {
return StructureRecord{}, err
}
if err := posixproj.NewProjector(service.db, service.posixRoot).Rebuild(ctx); err != nil {
return StructureRecord{}, fmt.Errorf("rebuild POSIX projection: %w", err)
}
return StructureRecord{ return StructureRecord{
Installation: installation, Installation: installation,
Organization: organization, Organization: organization,
@@ -901,3 +914,182 @@ func personalHomeTitle(displayName string) string {
return fmt.Sprintf("%s's Home", trimmedDisplayName) return fmt.Sprintf("%s's Home", trimmedDisplayName)
} }
func (service *Service) ensureBootstrapPOSIXSkeleton(
installation InstallationRecord,
admin AdminSummary,
organization namedRecord,
department namedRecord,
team namedRecord,
project namedRecord,
) error {
rootPath := strings.TrimSpace(service.posixRoot)
if rootPath == "" {
return nil
}
if err := os.MkdirAll(rootPath, 0o755); err != nil {
return fmt.Errorf("create POSIX root: %w", err)
}
if err := writeJSONFile(filepath.Join(rootPath, "settings.json"), map[string]any{
"installation": map[string]any{
"id": installation.ID,
"name": installation.Name,
"mode": installation.Mode,
"access": installation.Access,
"protocol": installation.Protocol,
"host": installation.Host,
"isBootstrapped": installation.IsBootstrapped,
},
"organization": map[string]any{
"id": organization.ID,
"name": organization.Name,
"slug": organization.Slug,
},
}); err != nil {
return fmt.Errorf("write tenant settings.json: %w", err)
}
if err := writeJSONFile(filepath.Join(rootPath, "layout.json"), map[string]any{
"version": 1,
"type": "tenant-layout",
"home": map[string]any{
"defaultProjectSlug": project.Slug,
},
}); err != nil {
return fmt.Errorf("write tenant layout.json: %w", err)
}
if err := os.MkdirAll(filepath.Join(rootPath, "catalog", "packs"), 0o755); err != nil {
return fmt.Errorf("create catalog packs root: %w", err)
}
if err := os.MkdirAll(filepath.Join(rootPath, "catalog", "standalone"), 0o755); err != nil {
return fmt.Errorf("create catalog standalone root: %w", err)
}
departmentPath := filepath.Join(rootPath, "departments", slugDir("department", department.Slug))
teamPath := filepath.Join(departmentPath, "teams", slugDir("team", team.Slug))
projectPath := filepath.Join(rootPath, "projects", slugDir("project", project.Slug))
usersPath := filepath.Join(rootPath, "users")
for _, dirPath := range []string{
departmentPath,
teamPath,
projectPath,
filepath.Join(projectPath, "children"),
filepath.Join(projectPath, "tree"),
filepath.Join(usersPath, "personals"),
} {
if err := os.MkdirAll(dirPath, 0o755); err != nil {
return fmt.Errorf("create POSIX directory %s: %w", dirPath, err)
}
}
if err := writeJSONFile(filepath.Join(departmentPath, "settings.json"), map[string]any{
"id": department.ID,
"name": department.Name,
"slug": department.Slug,
"type": "department",
}); err != nil {
return fmt.Errorf("write department settings.json: %w", err)
}
if err := writeJSONFile(filepath.Join(departmentPath, "users.json"), map[string]any{
"owners": []map[string]string{{
"id": admin.ID,
"email": admin.Email,
"displayName": admin.DisplayName,
}},
}); err != nil {
return fmt.Errorf("write department users.json: %w", err)
}
if err := writeJSONFile(filepath.Join(teamPath, "settings.json"), map[string]any{
"id": team.ID,
"name": team.Name,
"slug": team.Slug,
"type": "team",
}); err != nil {
return fmt.Errorf("write team settings.json: %w", err)
}
if err := writeJSONFile(filepath.Join(teamPath, "users.json"), map[string]any{
"owners": []map[string]string{{
"id": admin.ID,
"email": admin.Email,
"displayName": admin.DisplayName,
}},
}); err != nil {
return fmt.Errorf("write team users.json: %w", err)
}
if err := writeJSONFile(filepath.Join(projectPath, "settings.json"), map[string]any{
"id": project.ID,
"name": project.Name,
"slug": project.Slug,
"type": "project",
}); err != nil {
return fmt.Errorf("write project settings.json: %w", err)
}
if err := writeJSONFile(filepath.Join(projectPath, "home.json"), map[string]any{
"type": "project-home",
"project": project.Slug,
"widgets": []any{},
}); err != nil {
return fmt.Errorf("write project home.json: %w", err)
}
if err := writeJSONFile(filepath.Join(projectPath, "acl.json"), map[string]any{
"version": 1,
"inherits": true,
"rules": []any{},
}); err != nil {
return fmt.Errorf("write project acl.json: %w", err)
}
if err := writeJSONFile(filepath.Join(usersPath, "settings.json"), map[string]any{
"primaryAdminId": admin.ID,
}); err != nil {
return fmt.Errorf("write users settings.json: %w", err)
}
if err := writeJSONFile(filepath.Join(usersPath, "data.json"), map[string]any{
"users": []map[string]string{{
"id": admin.ID,
"email": admin.Email,
"displayName": admin.DisplayName,
}},
}); err != nil {
return fmt.Errorf("write users data.json: %w", err)
}
return nil
}
func slugDir(prefix, slug string) string {
trimmedSlug := strings.TrimSpace(slug)
if trimmedSlug == "" {
return prefix
}
return fmt.Sprintf("%s-%s", prefix, trimmedSlug)
}
func writeJSONFile(path string, payload any) error {
parentDir := filepath.Dir(path)
if err := os.MkdirAll(parentDir, 0o755); err != nil {
return err
}
data, err := json.MarshalIndent(payload, "", " ")
if err != nil {
return err
}
data = append(data, '\n')
return os.WriteFile(path, data, 0o644)
}
+120
View File
@@ -0,0 +1,120 @@
package bootstrap
import (
"encoding/json"
"os"
"path/filepath"
"testing"
)
func TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot(t *testing.T) {
rootPath := filepath.Join(t.TempDir(), "POSIX")
t.Setenv("POSIX_ROOT", rootPath)
if _, err := os.Stat(rootPath); !os.IsNotExist(err) {
t.Fatalf("expected isolated POSIX root to start absent, got err=%v", err)
}
service := NewService(nil, os.Getenv("POSIX_ROOT"))
err := service.ensureBootstrapPOSIXSkeleton(
InstallationRecord{
ID: "installation-1",
Name: "MangoPig",
Mode: "personal",
Access: "local",
Protocol: "http",
Host: "localhost",
IsBootstrapped: true,
},
AdminSummary{
ID: "admin-1",
Email: "ronald@example.com",
DisplayName: "Ronald",
},
namedRecord{ID: "org-1", Name: "Primary Organization", Slug: "primary-organization"},
namedRecord{ID: "dept-1", Name: "Primary Department", Slug: "primary-department"},
namedRecord{ID: "team-1", Name: "Primary Team", Slug: "primary-team"},
namedRecord{ID: "project-1", Name: "Primary Project", Slug: "primary-project"},
)
if err != nil {
t.Fatalf("ensure bootstrap POSIX skeleton: %v", err)
}
requiredPaths := []string{
filepath.Join(rootPath, "settings.json"),
filepath.Join(rootPath, "layout.json"),
filepath.Join(rootPath, "catalog", "packs"),
filepath.Join(rootPath, "catalog", "standalone"),
filepath.Join(rootPath, "departments", "department-primary-department", "settings.json"),
filepath.Join(rootPath, "departments", "department-primary-department", "users.json"),
filepath.Join(rootPath, "departments", "department-primary-department", "teams", "team-primary-team", "settings.json"),
filepath.Join(rootPath, "departments", "department-primary-department", "teams", "team-primary-team", "users.json"),
filepath.Join(rootPath, "projects", "project-primary-project", "settings.json"),
filepath.Join(rootPath, "projects", "project-primary-project", "home.json"),
filepath.Join(rootPath, "projects", "project-primary-project", "acl.json"),
filepath.Join(rootPath, "projects", "project-primary-project", "children"),
filepath.Join(rootPath, "projects", "project-primary-project", "tree"),
filepath.Join(rootPath, "users", "settings.json"),
filepath.Join(rootPath, "users", "data.json"),
filepath.Join(rootPath, "users", "personals"),
}
for _, path := range requiredPaths {
if _, err := os.Stat(path); err != nil {
t.Fatalf("expected path to exist %s: %v", path, err)
}
}
settingsPayload := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "settings.json"))
installationPayload, ok := settingsPayload["installation"].(map[string]any)
if !ok {
t.Fatalf("settings.json missing installation object: %#v", settingsPayload)
}
if installationPayload["name"] != "MangoPig" {
t.Fatalf("expected installation name MangoPig, got %#v", installationPayload["name"])
}
if installationPayload["isBootstrapped"] != true {
t.Fatalf("expected installation to be bootstrapped, got %#v", installationPayload["isBootstrapped"])
}
layoutPayload := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "layout.json"))
homePayload, ok := layoutPayload["home"].(map[string]any)
if !ok {
t.Fatalf("layout.json missing home object: %#v", layoutPayload)
}
if homePayload["defaultProjectSlug"] != "primary-project" {
t.Fatalf("expected default project slug primary-project, got %#v", homePayload["defaultProjectSlug"])
}
projectSettings := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "projects", "project-primary-project", "settings.json"))
if projectSettings["type"] != "project" {
t.Fatalf("expected project settings type project, got %#v", projectSettings["type"])
}
projectACL := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "projects", "project-primary-project", "acl.json"))
if projectACL["inherits"] != true {
t.Fatalf("expected project acl to inherit by default, got %#v", projectACL["inherits"])
}
usersSettings := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "users", "settings.json"))
if usersSettings["primaryAdminId"] != "admin-1" {
t.Fatalf("expected primary admin id admin-1, got %#v", usersSettings["primaryAdminId"])
}
}
func readJSONFileForTest[T any](t *testing.T, path string) T {
t.Helper()
data, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v", path, err)
}
var payload T
if err := json.Unmarshal(data, &payload); err != nil {
t.Fatalf("unmarshal %s: %v", path, err)
}
return payload
}
+2
View File
@@ -17,6 +17,7 @@ type Config struct {
APIPort string APIPort string
PostgresURL string PostgresURL string
ValkeyURL string ValkeyURL string
POSIXRoot string
ShutdownTimeout time.Duration ShutdownTimeout time.Duration
} }
@@ -29,6 +30,7 @@ func Load() *Config {
APIPort: getEnv("BACKEND_API_PORT", "8081"), APIPort: getEnv("BACKEND_API_PORT", "8081"),
PostgresURL: getEnv("DATABASE_URL", "postgres://moku:moku_dev_password@localhost:5432/moku?sslmode=disable"), PostgresURL: getEnv("DATABASE_URL", "postgres://moku:moku_dev_password@localhost:5432/moku?sslmode=disable"),
ValkeyURL: getEnv("VALKEY_URL", "redis://localhost:6379/0"), ValkeyURL: getEnv("VALKEY_URL", "redis://localhost:6379/0"),
POSIXRoot: getEnv("POSIX_ROOT", "../POSIX"),
ShutdownTimeout: getDurationEnv("BACKEND_SHUTDOWN_TIMEOUT", 10*time.Second), ShutdownTimeout: getDurationEnv("BACKEND_SHUTDOWN_TIMEOUT", 10*time.Second),
} }
} }
@@ -341,7 +341,7 @@ func (routes apiRoutes) handleBootstrapStructureStep(w http.ResponseWriter, r *h
} }
func (routes apiRoutes) bootstrapService() *bootstrapservice.Service { func (routes apiRoutes) bootstrapService() *bootstrapservice.Service {
return bootstrapservice.NewService(routes.cfg.Database) return bootstrapservice.NewService(routes.cfg.Database, routes.cfg.Config.POSIXRoot)
} }
func (routes apiRoutes) writeBootstrapStepResponse(w http.ResponseWriter, status int, step string, payload any) { func (routes apiRoutes) writeBootstrapStepResponse(w http.ResponseWriter, status int, step string, payload any) {
+553
View File
@@ -0,0 +1,553 @@
package posixproj
import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"io/fs"
"os"
"path/filepath"
"strings"
"moku-backend/internal/database"
)
const rootProjectionPath = "/"
type Projector struct {
db *database.DB
root string
}
type RebuildSummary struct {
TotalNodes int
DirectoryCount int
FileCount int
}
type NodeKind string
const (
NodeKindDirectory NodeKind = "directory"
NodeKindFile NodeKind = "file"
)
type Scope struct {
InstallationID string
OrganizationID string
OrganizationSlug string
DepartmentSlug string
TeamSlug string
ProjectSlug string
PersonalSlug string
}
type Node struct {
Path string
ParentPath *string
Name string
Depth int
NodeKind NodeKind
LogicalType string
FileRole string
ResourceID string
ResourceName string
ResourceSlug string
InstallationID string
OrganizationID string
OrganizationSlug string
DepartmentSlug string
TeamSlug string
ProjectSlug string
PersonalSlug string
ContentJSON []byte
SizeBytes int64
Checksum string
}
func NewProjector(db *database.DB, root string) *Projector {
return &Projector{db: db, root: strings.TrimSpace(root)}
}
func (projector *Projector) Rebuild(ctx context.Context) error {
_, err := projector.RebuildWithSummary(ctx)
return err
}
func (projector *Projector) RebuildWithSummary(ctx context.Context) (RebuildSummary, error) {
if projector == nil || projector.db == nil || projector.db.Pool == nil {
return RebuildSummary{}, nil
}
nodes, err := ScanRoot(projector.root)
if err != nil {
return RebuildSummary{}, err
}
summary := summarizeNodes(nodes)
tx, err := projector.db.Pool.Begin(ctx)
if err != nil {
return RebuildSummary{}, err
}
defer func() {
_ = tx.Rollback(ctx)
}()
if _, err := tx.Exec(ctx, `DELETE FROM posix_nodes;`); err != nil {
return RebuildSummary{}, fmt.Errorf("clear posix_nodes: %w", err)
}
for _, node := range nodes {
if _, err := tx.Exec(ctx, `
INSERT INTO posix_nodes (
path,
parent_path,
name,
depth,
node_kind,
logical_type,
file_role,
resource_id,
resource_name,
resource_slug,
installation_id,
organization_id,
organization_slug,
department_slug,
team_slug,
project_slug,
personal_slug,
content_json,
size_bytes,
checksum
) VALUES (
$1, $2, $3, $4, $5::posix_node_kind, $6, $7, $8, $9, $10,
$11, $12, $13, $14, $15, $16, $17, $18::jsonb, $19, $20
);
`,
node.Path,
node.ParentPath,
node.Name,
node.Depth,
string(node.NodeKind),
node.LogicalType,
node.FileRole,
node.ResourceID,
node.ResourceName,
node.ResourceSlug,
node.InstallationID,
node.OrganizationID,
node.OrganizationSlug,
node.DepartmentSlug,
node.TeamSlug,
node.ProjectSlug,
node.PersonalSlug,
node.ContentJSON,
node.SizeBytes,
node.Checksum,
); err != nil {
return RebuildSummary{}, fmt.Errorf("insert posix node %s: %w", node.Path, err)
}
}
if err := tx.Commit(ctx); err != nil {
return RebuildSummary{}, err
}
return summary, nil
}
func ScanRoot(root string) ([]Node, error) {
rootPath := strings.TrimSpace(root)
if rootPath == "" {
return nil, nil
}
info, err := os.Stat(rootPath)
if err != nil {
return nil, fmt.Errorf("stat POSIX root: %w", err)
}
if !info.IsDir() {
return nil, fmt.Errorf("POSIX root is not a directory: %s", rootPath)
}
rootScope, err := loadRootScope(rootPath)
if err != nil {
return nil, err
}
nodes := []Node{{
Path: rootProjectionPath,
ParentPath: nil,
Name: filepath.Base(rootPath),
Depth: 0,
NodeKind: NodeKindDirectory,
LogicalType: "tenant_root",
InstallationID: rootScope.InstallationID,
OrganizationID: rootScope.OrganizationID,
OrganizationSlug: rootScope.OrganizationSlug,
}}
err = filepath.WalkDir(rootPath, func(path string, entry fs.DirEntry, walkErr error) error {
if walkErr != nil {
return walkErr
}
if path == rootPath {
return nil
}
relPath, err := filepath.Rel(rootPath, path)
if err != nil {
return err
}
relPath = filepath.ToSlash(relPath)
if relPath == "." {
return nil
}
node, err := buildNode(rootPath, relPath, entry, rootScope)
if err != nil {
return err
}
nodes = append(nodes, node)
return nil
})
if err != nil {
return nil, fmt.Errorf("scan POSIX root: %w", err)
}
return nodes, nil
}
func loadRootScope(rootPath string) (Scope, error) {
settingsPath := filepath.Join(rootPath, "settings.json")
content, err := os.ReadFile(settingsPath)
if err != nil {
if errorsIsNotExist(err) {
return Scope{}, nil
}
return Scope{}, fmt.Errorf("read root settings.json: %w", err)
}
var payload map[string]any
if err := json.Unmarshal(content, &payload); err != nil {
return Scope{}, fmt.Errorf("decode root settings.json: %w", err)
}
installation, _ := payload["installation"].(map[string]any)
organization, _ := payload["organization"].(map[string]any)
return Scope{
InstallationID: stringValue(installation["id"]),
OrganizationID: stringValue(organization["id"]),
OrganizationSlug: stringValue(organization["slug"]),
}, nil
}
func buildNode(rootPath, relPath string, entry fs.DirEntry, rootScope Scope) (Node, error) {
scope := deriveScope(relPath, rootScope)
parentPath := projectionParentPath(relPath)
logicalType, fileRole := classifyPath(relPath, entry.IsDir())
node := Node{
Path: relPath,
ParentPath: parentPath,
Name: entry.Name(),
Depth: strings.Count(relPath, "/") + 1,
NodeKind: NodeKindDirectory,
LogicalType: logicalType,
FileRole: fileRole,
InstallationID: scope.InstallationID,
OrganizationID: scope.OrganizationID,
OrganizationSlug: scope.OrganizationSlug,
DepartmentSlug: scope.DepartmentSlug,
TeamSlug: scope.TeamSlug,
ProjectSlug: scope.ProjectSlug,
PersonalSlug: scope.PersonalSlug,
}
if entry.IsDir() {
return node, nil
}
absPath := filepath.Join(rootPath, filepath.FromSlash(relPath))
content, err := os.ReadFile(absPath)
if err != nil {
return Node{}, fmt.Errorf("read POSIX file %s: %w", relPath, err)
}
hash := sha256.Sum256(content)
node.NodeKind = NodeKindFile
node.SizeBytes = int64(len(content))
node.Checksum = hex.EncodeToString(hash[:])
if strings.EqualFold(filepath.Ext(entry.Name()), ".json") {
var payload map[string]any
if err := json.Unmarshal(content, &payload); err == nil {
jsonContent, err := json.Marshal(payload)
if err != nil {
return Node{}, fmt.Errorf("remarshal POSIX file %s: %w", relPath, err)
}
node.ContentJSON = jsonContent
node.ResourceID = stringValue(payload["id"])
node.ResourceName = stringValue(payload["name"])
node.ResourceSlug = stringValue(payload["slug"])
if node.ResourceID == "" && fileRole == "settings" && logicalType == "tenant" {
installation, _ := payload["installation"].(map[string]any)
organization, _ := payload["organization"].(map[string]any)
node.ResourceID = stringValue(installation["id"])
node.ResourceName = stringValue(installation["name"])
node.InstallationID = stringValue(installation["id"])
node.OrganizationID = stringValue(organization["id"])
node.OrganizationSlug = firstNonEmpty(node.OrganizationSlug, stringValue(organization["slug"]))
}
if node.ResourceID == "" && fileRole == "users" {
node.ResourceName = firstNonEmpty(node.ResourceName, parentEntityName(logicalType, scope))
}
}
}
if node.ResourceSlug == "" {
node.ResourceSlug = inferredResourceSlug(logicalType, scope)
}
return node, nil
}
func deriveScope(relPath string, rootScope Scope) Scope {
scope := rootScope
parts := strings.Split(relPath, "/")
for _, part := range parts {
switch {
case strings.HasPrefix(part, "department-"):
scope.DepartmentSlug = strings.TrimPrefix(part, "department-")
case strings.HasPrefix(part, "team-"):
scope.TeamSlug = strings.TrimPrefix(part, "team-")
case strings.HasPrefix(part, "project-"):
scope.ProjectSlug = strings.TrimPrefix(part, "project-")
case strings.HasPrefix(part, "personal-"):
scope.PersonalSlug = strings.TrimPrefix(part, "personal-")
}
}
return scope
}
func classifyPath(relPath string, isDir bool) (logicalType, fileRole string) {
parts := strings.Split(relPath, "/")
name := parts[len(parts)-1]
if !isDir {
fileRole = strings.TrimSuffix(name, filepath.Ext(name))
}
hasChildrenAncestor := pathContainsSegment(parts, "children")
hasTreeAncestor := pathContainsSegment(parts, "tree")
parentName := ""
if len(parts) >= 2 {
parentName = parts[len(parts)-2]
}
switch {
case relPath == "settings.json":
return "tenant", "settings"
case relPath == "layout.json":
return "tenant", "layout"
case len(parts) >= 1 && parts[0] == "catalog":
if isDir {
if len(parts) == 1 {
return "catalog", ""
}
if len(parts) >= 2 && parts[1] == "packs" {
if len(parts) == 2 {
return "catalog_packs", ""
}
if len(parts) == 3 {
return "catalog_pack", ""
}
if len(parts) >= 4 && parts[3] == "entries" {
return "catalog_pack_entries", ""
}
return "catalog_entry", ""
}
if len(parts) >= 2 && parts[1] == "standalone" {
if len(parts) == 2 {
return "catalog_standalone", ""
}
return "catalog_entry", ""
}
}
return "catalog", fileRole
case len(parts) >= 2 && parts[0] == "departments" && strings.HasPrefix(parts[1], "department-"):
if isDir {
if len(parts) == 2 {
return "department", ""
}
if len(parts) == 3 && parts[2] == "teams" {
return "department_teams", ""
}
if len(parts) >= 4 && strings.HasPrefix(parts[3], "team-") {
return "team", ""
}
}
if len(parts) >= 4 && strings.HasPrefix(parts[3], "team-") {
return "team", fileRole
}
return "department", fileRole
case len(parts) >= 2 && parts[0] == "projects" && strings.HasPrefix(parts[1], "project-"):
if isDir {
if strings.HasPrefix(name, "project-") {
return "project", ""
}
if name == "children" {
return "project_children", ""
}
if name == "tree" {
return "project_tree", ""
}
if hasChildrenAncestor && strings.HasPrefix(name, "folder-") {
return "hierarchy_folder", ""
}
if hasTreeAncestor && strings.HasPrefix(name, "folder-") {
return "folder", ""
}
if hasTreeAncestor && strings.HasPrefix(name, "item-") {
return "item", ""
}
}
if hasChildrenAncestor && strings.HasPrefix(parentName, "folder-") {
return "hierarchy_folder", fileRole
}
if hasTreeAncestor {
if strings.HasPrefix(parentName, "item-") {
return "item", fileRole
}
if strings.HasPrefix(parentName, "folder-") {
return "folder", fileRole
}
}
return "project", fileRole
case len(parts) >= 1 && parts[0] == "users":
if isDir {
if len(parts) == 1 {
return "users", ""
}
if len(parts) == 2 && parts[1] == "personals" {
return "personals", ""
}
if len(parts) >= 3 && parts[1] == "personals" && strings.HasPrefix(parts[2], "personal-") {
return "personal", ""
}
if strings.Contains(relPath, "/tree/") || strings.HasSuffix(relPath, "/tree") {
if strings.HasPrefix(name, "folder-") {
return "folder", ""
}
if strings.HasPrefix(name, "item-") {
return "item", ""
}
}
}
if len(parts) >= 3 && parts[1] == "personals" && strings.HasPrefix(parts[2], "personal-") {
if strings.Contains(relPath, "/tree/") {
if strings.HasPrefix(parts[len(parts)-2], "item-") {
return "item", fileRole
}
if strings.HasPrefix(parts[len(parts)-2], "folder-") {
return "folder", fileRole
}
}
return "personal", fileRole
}
return "users", fileRole
default:
if isDir {
return "directory", ""
}
return "file", fileRole
}
}
func pathContainsSegment(parts []string, target string) bool {
for _, part := range parts {
if part == target {
return true
}
}
return false
}
func projectionParentPath(relPath string) *string {
if relPath == "" || relPath == rootProjectionPath {
return nil
}
parent := filepath.ToSlash(filepath.Dir(relPath))
if parent == "." || parent == "" {
root := rootProjectionPath
return &root
}
return &parent
}
func inferredResourceSlug(logicalType string, scope Scope) string {
switch logicalType {
case "department":
return scope.DepartmentSlug
case "team":
return scope.TeamSlug
case "project":
return scope.ProjectSlug
case "personal":
return scope.PersonalSlug
default:
return ""
}
}
func parentEntityName(logicalType string, scope Scope) string {
switch logicalType {
case "department":
return scope.DepartmentSlug
case "team":
return scope.TeamSlug
case "project":
return scope.ProjectSlug
case "personal":
return scope.PersonalSlug
default:
return ""
}
}
func stringValue(value any) string {
stringValue, _ := value.(string)
return strings.TrimSpace(stringValue)
}
func firstNonEmpty(values ...string) string {
for _, value := range values {
trimmed := strings.TrimSpace(value)
if trimmed != "" {
return trimmed
}
}
return ""
}
func summarizeNodes(nodes []Node) RebuildSummary {
summary := RebuildSummary{TotalNodes: len(nodes)}
for _, node := range nodes {
switch node.NodeKind {
case NodeKindDirectory:
summary.DirectoryCount++
case NodeKindFile:
summary.FileCount++
}
}
return summary
}
func errorsIsNotExist(err error) bool {
return err != nil && os.IsNotExist(err)
}
@@ -0,0 +1,226 @@
package posixproj
import (
"encoding/json"
"os"
"path/filepath"
"testing"
)
func TestScanRootBuildsProjectedNodesFromBootstrapShape(t *testing.T) {
root := filepath.Join(t.TempDir(), "POSIX")
mustMkdirAll(t, filepath.Join(root, "catalog", "packs"))
mustMkdirAll(t, filepath.Join(root, "catalog", "standalone"))
mustMkdirAll(t, filepath.Join(root, "departments", "department-primary-department", "teams", "team-primary-team"))
mustMkdirAll(t, filepath.Join(root, "projects", "project-primary-project", "children", "folder-design", "children", "project-web", "children"))
mustMkdirAll(t, filepath.Join(root, "projects", "project-primary-project", "children", "folder-design", "children", "project-web", "tree"))
mustMkdirAll(t, filepath.Join(root, "projects", "project-primary-project", "tree"))
mustMkdirAll(t, filepath.Join(root, "projects", "project-primary-project", "tree", "folder-docs", "item-roadmap"))
mustMkdirAll(t, filepath.Join(root, "users", "personals"))
mustWriteJSON(t, filepath.Join(root, "settings.json"), map[string]any{
"installation": map[string]any{
"id": "installation-1",
"name": "MangoPig",
"isBootstrapped": true,
},
"organization": map[string]any{
"id": "org-1",
"name": "Primary Organization",
"slug": "primary-organization",
},
})
mustWriteJSON(t, filepath.Join(root, "layout.json"), map[string]any{
"type": "tenant-layout",
"home": map[string]any{"defaultProjectSlug": "primary-project"},
})
mustWriteJSON(t, filepath.Join(root, "departments", "department-primary-department", "settings.json"), map[string]any{
"id": "dept-1",
"name": "Primary Department",
"slug": "primary-department",
"type": "department",
})
mustWriteJSON(t, filepath.Join(root, "departments", "department-primary-department", "users.json"), map[string]any{
"users": []map[string]any{{"id": "admin-1"}},
})
mustWriteJSON(t, filepath.Join(root, "departments", "department-primary-department", "teams", "team-primary-team", "settings.json"), map[string]any{
"id": "team-1",
"name": "Primary Team",
"slug": "primary-team",
"type": "team",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "settings.json"), map[string]any{
"id": "project-1",
"name": "Primary Project",
"slug": "primary-project",
"type": "project",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "home.json"), map[string]any{
"type": "project-home",
"project": "primary-project",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "acl.json"), map[string]any{
"inherits": true,
"rules": []any{},
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "children", "folder-design", "folder.json"), map[string]any{
"name": "Design",
"slug": "design",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "children", "folder-design", "acl.json"), map[string]any{
"inherits": true,
"rules": []any{},
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "children", "folder-design", "children", "project-web", "settings.json"), map[string]any{
"id": "project-2",
"name": "Web Project",
"slug": "web",
"type": "project",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "children", "folder-design", "children", "project-web", "home.json"), map[string]any{
"type": "project-home",
"project": "web",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "children", "folder-design", "children", "project-web", "acl.json"), map[string]any{
"inherits": true,
"rules": []any{},
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "tree", "folder-docs", "folder.json"), map[string]any{
"name": "Docs",
"slug": "docs",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "tree", "folder-docs", "item-roadmap", "item.json"), map[string]any{
"id": "item-1",
"name": "Roadmap",
"slug": "roadmap",
"type": "board",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "tree", "folder-docs", "item-roadmap", "schema.json"), map[string]any{
"type": "object",
})
mustWriteJSON(t, filepath.Join(root, "projects", "project-primary-project", "tree", "folder-docs", "item-roadmap", "data.json"), map[string]any{
"title": "Roadmap",
})
mustWriteJSON(t, filepath.Join(root, "users", "settings.json"), map[string]any{
"primaryAdminId": "admin-1",
})
mustWriteJSON(t, filepath.Join(root, "users", "data.json"), map[string]any{
"users": []map[string]any{{"id": "admin-1", "email": "ronald@example.com"}},
})
nodes, err := ScanRoot(root)
if err != nil {
t.Fatalf("ScanRoot() error = %v", err)
}
index := make(map[string]Node, len(nodes))
for _, node := range nodes {
index[node.Path] = node
}
rootNode, ok := index[rootProjectionPath]
if !ok {
t.Fatalf("expected synthetic root node")
}
if rootNode.LogicalType != "tenant_root" {
t.Fatalf("expected root logical type tenant_root, got %q", rootNode.LogicalType)
}
if rootNode.OrganizationSlug != "primary-organization" {
t.Fatalf("expected root organization slug primary-organization, got %q", rootNode.OrganizationSlug)
}
tenantSettings := index["settings.json"]
if tenantSettings.LogicalType != "tenant" || tenantSettings.FileRole != "settings" {
t.Fatalf("unexpected tenant settings classification: %#v", tenantSettings)
}
if tenantSettings.InstallationID != "installation-1" {
t.Fatalf("expected installation id installation-1, got %q", tenantSettings.InstallationID)
}
deptSettings := index["departments/department-primary-department/settings.json"]
if deptSettings.DepartmentSlug != "primary-department" {
t.Fatalf("expected department slug primary-department, got %q", deptSettings.DepartmentSlug)
}
if deptSettings.ResourceID != "dept-1" {
t.Fatalf("expected department resource id dept-1, got %q", deptSettings.ResourceID)
}
teamSettings := index["departments/department-primary-department/teams/team-primary-team/settings.json"]
if teamSettings.TeamSlug != "primary-team" {
t.Fatalf("expected team slug primary-team, got %q", teamSettings.TeamSlug)
}
projectSettings := index["projects/project-primary-project/settings.json"]
if projectSettings.ProjectSlug != "primary-project" {
t.Fatalf("expected project slug primary-project, got %q", projectSettings.ProjectSlug)
}
if projectSettings.ResourceName != "Primary Project" {
t.Fatalf("expected project resource name Primary Project, got %q", projectSettings.ResourceName)
}
projectTree := index["projects/project-primary-project/tree"]
if projectTree.LogicalType != "project_tree" || projectTree.NodeKind != NodeKindDirectory {
t.Fatalf("unexpected project tree node: %#v", projectTree)
}
projectChildren := index["projects/project-primary-project/children"]
if projectChildren.LogicalType != "project_children" || projectChildren.NodeKind != NodeKindDirectory {
t.Fatalf("unexpected project children node: %#v", projectChildren)
}
hierarchyFolder := index["projects/project-primary-project/children/folder-design"]
if hierarchyFolder.LogicalType != "hierarchy_folder" || hierarchyFolder.ProjectSlug != "primary-project" {
t.Fatalf("unexpected hierarchy folder node: %#v", hierarchyFolder)
}
hierarchyFolderACL := index["projects/project-primary-project/children/folder-design/acl.json"]
if hierarchyFolderACL.LogicalType != "hierarchy_folder" || hierarchyFolderACL.FileRole != "acl" {
t.Fatalf("unexpected hierarchy folder acl classification: %#v", hierarchyFolderACL)
}
childProjectSettings := index["projects/project-primary-project/children/folder-design/children/project-web/settings.json"]
if childProjectSettings.LogicalType != "project" || childProjectSettings.ProjectSlug != "web" {
t.Fatalf("unexpected child project classification: %#v", childProjectSettings)
}
treeFolder := index["projects/project-primary-project/tree/folder-docs"]
if treeFolder.LogicalType != "folder" || treeFolder.ProjectSlug != "primary-project" {
t.Fatalf("unexpected tree folder node: %#v", treeFolder)
}
treeItem := index["projects/project-primary-project/tree/folder-docs/item-roadmap/item.json"]
if treeItem.LogicalType != "item" || treeItem.FileRole != "item" {
t.Fatalf("unexpected tree item classification: %#v", treeItem)
}
if treeItem.ResourceSlug != "roadmap" {
t.Fatalf("expected tree item resource slug roadmap, got %#v", treeItem.ResourceSlug)
}
usersData := index["users/data.json"]
if usersData.LogicalType != "users" || usersData.FileRole != "data" {
t.Fatalf("unexpected users data classification: %#v", usersData)
}
if usersData.Checksum == "" || usersData.SizeBytes == 0 {
t.Fatalf("expected users/data.json checksum and size to be populated: %#v", usersData)
}
}
func mustMkdirAll(t *testing.T, path string) {
t.Helper()
if err := os.MkdirAll(path, 0o755); err != nil {
t.Fatalf("MkdirAll(%q) error = %v", path, err)
}
}
func mustWriteJSON(t *testing.T, path string, payload any) {
t.Helper()
bytes, err := json.MarshalIndent(payload, "", " ")
if err != nil {
t.Fatalf("MarshalIndent(%q) error = %v", path, err)
}
bytes = append(bytes, '\n')
if err := os.WriteFile(path, bytes, 0o644); err != nil {
t.Fatalf("WriteFile(%q) error = %v", path, err)
}
}
+9 -5
View File
@@ -9,18 +9,22 @@ migrate-up:
migrate-down: migrate-down:
cd '{{backend_dir}}' && go run ./cmd/migrate down cd '{{backend_dir}}' && go run ./cmd/migrate down
# Reset all embedded database migrations and reapply from scratch. # Reset all embedded database migrations.
migrate-reset: migrate-reset:
cd '{{backend_dir}}' && go run ./cmd/migrate reset cd '{{backend_dir}}' && go run ./cmd/migrate reset
# Reset embedded database migrations and apply them again from scratch.
migrate-rebuild:
cd '{{backend_dir}}' && go run ./cmd/migrate reset && go run ./cmd/migrate up
# Show the embedded database migration status. # Show the embedded database migration status.
migrate-status: migrate-status:
cd '{{backend_dir}}' && go run ./cmd/migrate status cd '{{backend_dir}}' && go run ./cmd/migrate status
# Rebuild the POSIX-to-DB projection from the current POSIX root.
posix-rebuild:
cd '{{backend_dir}}' && go run ./cmd/posix rebuild
# Format backend Go source files. # Format backend Go source files.
fmt: fmt:
cd '{{backend_dir}}' && gofmt -w ./cmd ./db ./internal cd '{{backend_dir}}' && gofmt -w ./cmd ./db ./internal
# Run backend test suite.
test:
cd '{{backend_dir}}' && go test ./...
+11
View File
@@ -0,0 +1,11 @@
project_root := justfile_directory()
backend_dir := project_root + "/Backend"
# Run the full backend test suite.
[default]
all:
cd '{{backend_dir}}' && go test ./...
# Run the isolated POSIX bootstrap smoke test.
posix-bootstrap:
cd '{{backend_dir}}' && go test ./internal/bootstrap -run TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot -count=1 -v
+1
View File
@@ -0,0 +1 @@
mod backend
+2
View File
@@ -6,6 +6,7 @@ x-backend-service: &backend-service
environment: environment:
DATABASE_URL: postgres://moku:moku_dev_password@postgres:5432/moku?sslmode=disable DATABASE_URL: postgres://moku:moku_dev_password@postgres:5432/moku?sslmode=disable
VALKEY_URL: redis://valkey:6379/0 VALKEY_URL: redis://valkey:6379/0
POSIX_ROOT: /posix
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
@@ -13,6 +14,7 @@ x-backend-service: &backend-service
condition: service_healthy condition: service_healthy
volumes: volumes:
- ../Backend:/app - ../Backend:/app
- ../POSIX:/posix
- moku_work_backend_go_pkg:/go/pkg/mod - moku_work_backend_go_pkg:/go/pkg/mod
- moku_work_backend_go_build:/root/.cache/go-build - moku_work_backend_go_build:/root/.cache/go-build
+3
View File
@@ -5,11 +5,14 @@ x-backend-service: &backend-service
environment: environment:
DATABASE_URL: postgres://moku:moku_dev_password@postgres:5432/moku?sslmode=disable DATABASE_URL: postgres://moku:moku_dev_password@postgres:5432/moku?sslmode=disable
VALKEY_URL: redis://valkey:6379/0 VALKEY_URL: redis://valkey:6379/0
POSIX_ROOT: /posix
depends_on: depends_on:
postgres: postgres:
condition: service_healthy condition: service_healthy
valkey: valkey:
condition: service_healthy condition: service_healthy
volumes:
- ../POSIX:/posix
services: services:
postgres: postgres:
+75
View File
@@ -0,0 +1,75 @@
# POSIX Structure
[Filetree Link](https://tree.nathanfriend.com/?s=(%27optiUs!(%27fancy!Yue~fullPath!fbq~YailingSlash!Yue~rootDot!fbq)~R(%27R%27PJ%20or%20OrganizatiU%20%7Bqrver%7DM*46layout6cNlog7packs7*pack37A2*enYies75W5A_standbUe7WA6HwH30LZ2teamw5teamGL5Z6FwF30LKTC058T5C7XFG5LXKXTXC7XI7I05QG5BN2*8QG5BN6Z04_dN_pJw*pJGlayout2L*KI70%27)~vEiU!%271%27)*%20%200M52_*3-%3Cslug%3E4qttings5**69M*7%2F08VG*V259.jsUA5manifestBQ25*schema25*dCchildrenEersFprojectG305HdepartmentI*YeeJEUbKhome2L*42M%5CnNataQitemRsource!Tacl2UonVfolderW*app37X55YtrZusE_90balqsews0%01wqb_ZYXWVUTRQNMLKJIHGFECBA987654320*)
``` markdown
Personal or Organization (server)/
├── settings.json
├── layout.json
├── catalog/
│ ├── packs/
│ │ └── pack-<slug>/
│ │ ├── manifest.json
│ │ └── entries/
│ │ └── app-<slug>/
│ │ └── manifest.json
│ └── standalone/
│ └── app-<slug>/
│ └── manifest.json
├── departments/
│ └── department-<slug>/
│ ├── settings.json
│ ├── users.json
│ └── teams/
│ └── team-<slug>/
│ ├── settings.json
│ └── users.json
├── projects/
│ └── project-<slug>/
│ ├── settings.json
│ ├── home.json
│ ├── acl.json
│ ├── children/
│ │ └── folder-<slug>/
│ │ ├── folder.json
│ │ ├── acl.json
│ │ └── children/
│ │ └── project-<slug>/
│ │ ├── settings.json
│ │ ├── home.json
│ │ ├── acl.json
│ │ ├── children/
│ │ └── tree/
│ └── tree/
│ ├── item-<slug>/
│ │ ├── item.json
│ │ ├── schema.json
│ │ └── data.json
│ └── folder-<slug>/
│ ├── folder.json
│ └── item-<slug>/
│ ├── item.json
│ ├── schema.json
│ └── data.json
└── users/
├── settings.json
├── data.json
└── personals/
└── personal-<slug>/
├── layout.json
├── settings.json
├── home.json
└── tree/
```
## File Responsibilities
- `settings.json` — Metadata and presentation config for the thing, such as display name, icon, description, and simple settings.
- `layout.json` — Layout configuration for the current server or personal space.
- `home.json` — Home surface configuration, such as widgets, sections, and how they are arranged.
- `folder.json` — Metadata for a folder node in a tree.
- `item.json` — Instance metadata for a created item, including what it is and how it should behave.
- `schema.json` — The structure expected by that item's data.
- `data.json` — The actual content or state data for that item.
- `manifest.json` — Catalog definition metadata, including versioning, description, and capabilities for reusable apps or entries.
- `users.json` — User membership or assignment data for departments and teams.
+112 -50
View File
@@ -4,87 +4,149 @@
### Version 0.1.0 ### Version 0.1.0
**Goal:** Barebone frontend with a real backend core. **Goal:** Finish the base application shell, auth, and platform foundations.
#### Architecture #### Architecture and Delivery
- [ ] Project-Structure - [x] Project-Structure
- [ ] Stack-Decisions - [x] Stack-Decisions
- [ ] Proxy - [x] Proxy
- [ ] Local-Prod-NGINX-Proxy - [x] Local-Dev-Vite-Proxy
- [ ] Static-Frontend-Serving - [x] Local-Prod-NGINX-Proxy
- [ ] First-Request-Web-Loader - [x] First-Request-Web-Loader
- [ ] Bootstrap-Document - [x] Bootstrap-Document
- [ ] Route-Intent-Handoff - [x] Route-Intent-Handoff
- [ ] Tiny-First-Paint-Budget - [x] Tiny-First-Paint-Budget
- [ ] Dev-and-Prod-Builds - [x] Dev-and-Prod-Builds
- [x] Local-Dev-Just-Commands - [x] Local-Dev-Just-Commands
- [x] Local-Dev-Docker-Compose - [x] Local-Dev-Docker-Compose
- [ ] Local-Prod-Just-Commands - [x] Local-Prod-Just-Commands
- [ ] Local-Prod-Docker-Compose - [x] Local-Prod-Docker-Compose
- [ ] Frontend-Production-Dockerfile - [x] Frontend-Production-Dockerfile
- [ ] Frontend-docker-bake - [x] Frontend-docker-bake
#### Backend #### Backend — Done Foundations
- [x] Bootstrap-Persistence
- [x] Installation-Step
- [x] Mode-Step
- [x] Admin-Step
- [x] Structure-Step
- [x] Bootstrap-State-Authority
- [x] Development-Bootstrap-Reset
- [x] Base-Schema
- [x] Installations
- [x] Users
- [x] User-Homes
- [x] Organizations
- [x] Departments
- [x] Teams
- [x] Projects
- [x] Workspaces
- [x] Membership-Tables
- [x] App-Shell-Read-API
- [x] App-Shell-State-Endpoint
- [x] Bootstrap-Read-Endpoints
- [x] Shell-Tree-Hydration
- [x] Web-Route-Scaffolds
- [x] Session-Endpoint-Scaffold
- [x] Bootstrap-Endpoint-Scaffold
- [x] Current-User-Endpoint-Scaffold
#### Backend — Remaining for 0.1.0
- [ ] Auth - [ ] Auth
- [ ] Session-Flow - [ ] Session-Flow
- [ ] Login-Logout-Foundation - [ ] Login-Logout-Foundation
- [ ] Authentication - [ ] Authentication
- [ ] User - [ ] Current-User-Implementation
- [ ] Base-Model - [ ] POSIX-Lite-File-Persistence-Foundation
- [ ] Mounted-Storage-Root-Config
- [ ] Project-Folder-Creation-On-Backend
- [ ] moku.project.json
- [ ] Item-Folder-Creation
- [ ] item.json
- [ ] schema.json
- [ ] data.json
- [ ] DB-To-Files-Write-Flow
- [ ] User-and-Workspace-Domain-Readiness
- [ ] Base-Workspace - [ ] Base-Workspace
- [ ] Folders-and-Subfolders
- [ ] Boards - [ ] Boards
- [ ] Dashboard - [ ] Dashboard
- [ ] Organization
- [ ] Base-Model
- [ ] Access-Rules-and-Membership
- [ ] Workspace
- [ ] Folders-and-Subfolders
- [ ] API - [ ] API
- [ ] Real-Organizations-Read-Endpoint
- [ ] Real-Workspaces-Read-Endpoint
- [ ] Tree-Mutation-Endpoints
- [ ] Project-Creation-Endpoint
#### Frontend #### Frontend — Done Foundations
- [x] Foundation - [x] Foundation
- [x] Typography - [x] Typography
- [x] Icons - [x] Icons
- [ ] App Shell - [x] App-Shell
- [x] Left-Rail
- [x] Top-Bar
- [x] Server-Dock
- [x] Department-Selector
- [x] Theme-Toggle
- [x] Notifications-Menu
- [x] Profile-Menu
- [x] Responsive-Shell
- [x] Collapsible-Shell
- [x] Mobile-Bottom-Nav
- [x] Mobile-Workspace-Browser
- [x] Mobile-Workspace-Views
- [x] Context-Menus
- [x] Workspace-Context-Menu
- [x] Project-Context-Menu
- [x] Bootstrap-Workspace-Home
- [x] Bootstrap-Wizard
- [x] Bootstrap-Step-Submission
- [x] App-Shell-Reload-After-Bootstrap
- [x] Project-Menu
- [x] Folders-and-Subfolders
- [x] Rooted-From-Department
- [x] Long-Press-Drag-and-Drop
- [x] Workspace-Tree
- [x] Folders-and-Subfolders
- [x] Long-Press-Drag-and-Drop
- [x] App-Shell-Hydration
#### Frontend — Remaining for 0.1.0
- [ ] Primitives - [ ] Primitives
- [ ] Button - [ ] Button
- [ ] IconButton - [ ] IconButton
- [ ] Input - [ ] Input
- [ ] Surface - [ ] Surface
- [ ] Nav-Bar
- [ ] Workspace-Switching - [ ] Workspace-Switching
- [ ] Workspace-Home - [ ] Real-Workspace-Home
- [ ] Real-Workspace-Tree-Hydration
- [ ] Create-Project-Flow
- [ ] Persist-Tree-Mutations
- [ ] Connect-Tree-Interactions-To-Backend-Data
### Version 0.2.0 ### Version 0.2.0
**Goal:** First real work surface. **Goal:** Build the plugin app system on top of the base platform. And core app plugins like calendar, board, docs and text channels
- [ ] Table
- [ ] CVA
- [ ] Storyboard
- [ ] Theme-System
- [ ] Theme-Registry
- [ ] Built-In-Theme-Presets
- [ ] Active-Theme-Persistence
- [ ] Theme-Switcher
- [ ] Theme-JSON-Upload
- [ ] Theme-JSON-Import-Validation
- [ ] Community-Theme-Readiness
### Version 0.3.0 ### Version 0.3.0
**Goal:** Documents and system hardening. **Goal:** Communications and Collaboration (Email System, Reminder System, and Live Collaboration on Documents)
- [ ] Document
- [ ] Accessibility-Rules
- [ ] Motion-Foundation
### Version 0.4.0 ### Version 0.4.0
- [ ] Gantt-Board **Goal:** Introduce the POSIX-based file system drive direction with OnlyOffice + S3 blob storage + Per File Versioning
- [ ] Calendar
- [ ] Timeline ### Version 0.5.0
**Goal:** File Sharing and Per File Permissions
### Version 0.6.0
**Goal:** Git as a core plugin
### Version 0.7.0
**Goal:** Full Automation System (Extensive)
+1
View File
@@ -10,6 +10,7 @@ BACKEND_SHUTDOWN_TIMEOUT=10s
DATABASE_URL=postgres://moku:moku_dev_password@localhost:5432/moku?sslmode=disable DATABASE_URL=postgres://moku:moku_dev_password@localhost:5432/moku?sslmode=disable
VALKEY_URL=redis://localhost:6379/0 VALKEY_URL=redis://localhost:6379/0
POSIX_ROOT=../POSIX
VITE_API_BASE_URL=/v1 VITE_API_BASE_URL=/v1
@@ -9,6 +9,15 @@
justify-items: center; justify-items: center;
} }
.rootDragMode {
user-select: none;
cursor: grabbing;
}
.rootDragMode .treeItem {
cursor: grabbing;
}
.trigger { .trigger {
width: 100%; width: 100%;
min-width: 0; min-width: 0;
@@ -197,6 +206,43 @@
padding: 0; padding: 0;
} }
.treeEmptySlot {
min-height: calc(var(--control-size-lg) - var(--space-2));
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
border-radius: var(--radius-lg);
border: 1px dashed color-mix(in srgb, var(--color-border) 38%, transparent);
opacity: 0.35;
}
.treeInputRow {
width: 100%;
min-width: 0;
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
min-height: calc(var(--control-size-lg) - var(--space-2));
padding: var(--space-2) var(--space-3);
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
border: 1px solid color-mix(in srgb, var(--color-border) 42%, transparent);
border-radius: var(--radius-lg);
background: color-mix(in srgb, var(--color-surface) 94%, transparent);
}
.treeInput {
width: 100%;
min-width: 0;
border: 0;
background: transparent;
color: var(--color-text);
font: inherit;
outline: none;
}
.treeInput::placeholder {
color: var(--color-text-muted);
}
.treeItem { .treeItem {
width: 100%; width: 100%;
min-width: 0; min-width: 0;
@@ -215,20 +261,43 @@
background 160ms var(--easing-standard), background 160ms var(--easing-standard),
color 160ms var(--easing-standard), color 160ms var(--easing-standard),
border-color 160ms var(--easing-standard), border-color 160ms var(--easing-standard),
box-shadow 160ms var(--easing-standard),
transform 180ms var(--easing-standard); transform 180ms var(--easing-standard);
text-align: left; text-align: left;
} }
.treeItem:hover, .treeItem:hover,
.treeItem:focus-visible { .treeItem:focus-visible {
background: var(--color-surface-hover); background: color-mix(in srgb, var(--color-surface-hover) 80%, var(--color-accent-soft) 20%);
color: var(--color-text); color: var(--color-text);
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
} }
.treeItemFolder { .treeItemFolder {
color: var(--color-text); color: var(--color-text);
} }
.treeItemDragging {
opacity: 0.45;
transform: scale(0.985);
box-shadow: none;
}
.treeItemDropBefore {
box-shadow: inset 0 2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
}
.treeItemDropAfter {
box-shadow: inset 0 -2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
}
.treeItemDropInside {
border-color: color-mix(in srgb, var(--color-accent-strong) 55%, transparent);
background: color-mix(in srgb, var(--color-accent-soft) 36%, var(--color-surface));
color: var(--color-text);
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
}
.folderChevron { .folderChevron {
color: var(--color-text-muted); color: var(--color-text-muted);
transition: transform 160ms var(--easing-standard); transition: transform 160ms var(--easing-standard);
@@ -1,6 +1,6 @@
// Path: Frontend/src/components/shell/ProjectSelector/ProjectSelector.tsx // Path: Frontend/src/components/shell/ProjectSelector/ProjectSelector.tsx
import { For, Show, createEffect, createMemo, createSignal, onCleanup, onMount, type JSX } from "solid-js"; import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
import { ChevronDown, ChevronRight, Folder, LayoutGrid } from "../../../lib/icons"; import { ChevronDown, ChevronRight, Folder, LayoutGrid } from "../../../lib/icons";
import { ProjectContextMenu } from "../ProjectContextMenu/ProjectContextMenu"; import { ProjectContextMenu } from "../ProjectContextMenu/ProjectContextMenu";
import { useAppShellData } from "../data/app-shell.context"; import { useAppShellData } from "../data/app-shell.context";
@@ -21,38 +21,503 @@ type ProjectSelectorProps = {
onClose: () => void; onClose: () => void;
}; };
type ProjectFolderNode = {
kind: "folder";
id: string;
label: string;
meta?: string;
children: ProjectTreeNode[];
};
type ProjectLeafNode = {
kind: "project";
item: ProjectItem;
};
type ProjectTreeNode = ProjectFolderNode | ProjectLeafNode;
type PendingProjectFolderDraft = {
parentId: string | null;
depth: number;
};
type ProjectDragTarget = {
parentId: string | null;
index: number;
intent: "before" | "after" | "inside";
targetNodeId?: string;
};
type ProjectDragState = {
draggedNodeId: string;
dropTarget: ProjectDragTarget | null;
};
type ProjectNodeLocation = {
parentId: string | null;
index: number;
node: ProjectTreeNode;
};
const LONG_PRESS_MS = 320;
const createProjectFolderId = (): string => `project-folder-${Math.random().toString(36).slice(2, 10)}`;
const getProjectTreeNodeId = (node: ProjectTreeNode): string =>
node.kind === "folder" ? node.id : node.item.id;
const buildProjectTree = (items: readonly ProjectItem[]): ProjectTreeNode[] =>
items.map((item) => ({
kind: "project",
item,
}));
const cloneProjectTreeNode = (node: ProjectTreeNode): ProjectTreeNode => {
if (node.kind === "project") {
return {
kind: "project",
item: { ...node.item },
};
}
return {
kind: "folder",
id: node.id,
label: node.label,
meta: node.meta,
children: node.children.map(cloneProjectTreeNode),
};
};
const insertProjectFolderNode = (
nodes: readonly ProjectTreeNode[],
parentId: string | null,
folder: ProjectFolderNode,
): ProjectTreeNode[] => {
if (parentId === null) {
return [...nodes, folder];
}
return nodes.map((node) => {
if (node.kind !== "folder") {
return node;
}
if (node.id === parentId) {
return {
...node,
children: [...node.children, folder],
};
}
return {
...node,
children: insertProjectFolderNode(node.children, parentId, folder),
};
});
};
const findProjectNodeLocation = (
nodes: readonly ProjectTreeNode[],
nodeId: string,
parentId: string | null = null,
): ProjectNodeLocation | null => {
for (let index = 0; index < nodes.length; index += 1) {
const node = nodes[index];
if (getProjectTreeNodeId(node) === nodeId) {
return { parentId, index, node };
}
if (node.kind === "folder") {
const nestedLocation = findProjectNodeLocation(node.children, nodeId, node.id);
if (nestedLocation) {
return nestedLocation;
}
}
}
return null;
};
const findProjectNodeDepth = (nodes: readonly ProjectTreeNode[], nodeId: string, depth = 0): number | null => {
for (const node of nodes) {
if (getProjectTreeNodeId(node) === nodeId) {
return depth;
}
if (node.kind === "folder") {
const nestedDepth = findProjectNodeDepth(node.children, nodeId, depth + 1);
if (nestedDepth !== null) {
return nestedDepth;
}
}
}
return null;
};
const projectTreeContainsNode = (nodes: readonly ProjectTreeNode[], nodeId: string): boolean => {
for (const node of nodes) {
if (getProjectTreeNodeId(node) === nodeId) {
return true;
}
if (node.kind === "folder" && projectTreeContainsNode(node.children, nodeId)) {
return true;
}
}
return false;
};
const removeProjectTreeNode = (
nodes: readonly ProjectTreeNode[],
nodeId: string,
): { nodes: ProjectTreeNode[]; removed: ProjectTreeNode | null } => {
const nextNodes: ProjectTreeNode[] = [];
let removed: ProjectTreeNode | null = null;
for (const node of nodes) {
if (getProjectTreeNodeId(node) === nodeId) {
removed = node;
continue;
}
if (node.kind === "folder") {
const result = removeProjectTreeNode(node.children, nodeId);
if (result.removed) {
removed = result.removed;
nextNodes.push({
...node,
children: result.nodes,
});
continue;
}
}
nextNodes.push(node);
}
return { nodes: nextNodes, removed };
};
const insertProjectTreeNode = (
nodes: readonly ProjectTreeNode[],
parentId: string | null,
index: number,
nodeToInsert: ProjectTreeNode,
): ProjectTreeNode[] => {
if (parentId === null) {
const nextNodes = [...nodes];
nextNodes.splice(Math.max(0, Math.min(index, nextNodes.length)), 0, nodeToInsert);
return nextNodes;
}
return nodes.map((node) => {
if (node.kind !== "folder") {
return node;
}
if (node.id === parentId) {
const nextChildren = [...node.children];
nextChildren.splice(Math.max(0, Math.min(index, nextChildren.length)), 0, nodeToInsert);
return {
...node,
children: nextChildren,
};
}
return {
...node,
children: insertProjectTreeNode(node.children, parentId, index, nodeToInsert),
};
});
};
const moveProjectTreeNode = (
nodes: readonly ProjectTreeNode[],
draggedNodeId: string,
dropTarget: ProjectDragTarget,
): ProjectTreeNode[] => {
const location = findProjectNodeLocation(nodes, draggedNodeId);
if (!location) {
return [...nodes];
}
if (
location.node.kind === "folder" &&
dropTarget.parentId !== null &&
(projectTreeContainsNode(location.node.children, dropTarget.parentId) || dropTarget.parentId === location.node.id)
) {
return [...nodes];
}
let normalizedIndex = dropTarget.index;
if (dropTarget.parentId === location.parentId && dropTarget.index > location.index) {
normalizedIndex -= 1;
}
if (dropTarget.parentId === location.parentId && normalizedIndex === location.index) {
return [...nodes];
}
const removalResult = removeProjectTreeNode(nodes, draggedNodeId);
if (!removalResult.removed) {
return [...nodes];
}
return insertProjectTreeNode(removalResult.nodes, dropTarget.parentId, normalizedIndex, removalResult.removed);
};
const ProjectFolderDraftRow = (props: {
depth: number;
value: string;
onInput: (value: string) => void;
onSubmit: () => void;
onCancel: () => void;
}): JSX.Element => {
let inputRef: HTMLInputElement | undefined;
queueMicrotask(() => inputRef?.focus());
return (
<li>
<div class={styles.treeInputRow} style={{ "--tree-depth": String(props.depth) }}>
<Folder class={styles.icon} size={18} strokeWidth={2} />
<input
ref={inputRef}
type="text"
class={styles.treeInput}
value={props.value}
placeholder="Folder name"
onInput={(event): void => props.onInput(event.currentTarget.value)}
onBlur={props.onSubmit}
onKeyDown={(event): void => {
if (event.key === "Enter") {
event.preventDefault();
event.currentTarget.blur();
return;
}
if (event.key === "Escape") {
event.preventDefault();
props.onCancel();
event.currentTarget.blur();
}
}}
/>
</div>
</li>
);
};
const ProjectFolderBranch = (props: {
nodes: readonly ProjectTreeNode[];
depth: number;
parentId: string | null;
selectedProjectId: string;
isFolderCollapsed: (folderId: string) => boolean;
onToggleFolder: (folderId: string) => void;
onSelectProject: (projectId: string) => void;
onOpenFolderMenu: (event: MouseEvent, folder: ProjectFolderNode) => void;
onOpenProjectMenu: (event: MouseEvent, item: ProjectItem) => void;
onNodePointerDown: (event: PointerEvent, nodeId: string) => void;
onNodePointerMove: (event: PointerEvent, parentId: string | null, index: number, node: ProjectTreeNode) => void;
pendingFolderDraft: PendingProjectFolderDraft | null;
pendingFolderName: string;
onPendingFolderNameChange: (value: string) => void;
onSubmitPendingFolder: () => void;
onCancelPendingFolder: () => void;
dragState: ProjectDragState | null;
}): JSX.Element => (
<ul class={styles.treeList} role="list">
<Show when={props.nodes.length === 0 && props.pendingFolderDraft?.parentId !== props.parentId}>
<li>
<div class={styles.treeEmptySlot} style={{ "--tree-depth": String(props.depth) }} />
</li>
</Show>
<For each={props.nodes}>
{(node, indexAccessor): JSX.Element => {
const nodeId = (): string => getProjectTreeNodeId(node);
const isDraggedNode = (): boolean => props.dragState?.draggedNodeId === nodeId();
const dropIntent = (): ProjectDragTarget["intent"] | null => {
if (props.dragState?.dropTarget?.targetNodeId !== nodeId()) {
return null;
}
return props.dragState.dropTarget.intent;
};
if (node.kind === "folder") {
const isCollapsed = (): boolean => props.isFolderCollapsed(node.id);
return (
<li>
<button
type="button"
classList={{
[styles.treeItem]: true,
[styles.treeItemFolder]: true,
[styles.treeItemDragging]: isDraggedNode(),
[styles.treeItemDropBefore]: dropIntent() === "before",
[styles.treeItemDropAfter]: dropIntent() === "after",
[styles.treeItemDropInside]: dropIntent() === "inside",
}}
style={{ "--tree-depth": String(props.depth) }}
aria-expanded={!isCollapsed()}
onClick={() => {
if (props.dragState || suppressNextTreeClick()) {
return;
}
props.onToggleFolder(node.id);
}}
onContextMenu={(event): void => props.onOpenFolderMenu(event, node)}
onPointerDown={(event): void => props.onNodePointerDown(event, node.id)}
onPointerMove={(event): void =>
props.onNodePointerMove(event, props.parentId, indexAccessor(), node)
}
onPointerEnter={(event): void =>
props.onNodePointerMove(event, props.parentId, indexAccessor(), node)
}
>
<ChevronRight
classList={{
[styles.folderChevron]: true,
[styles.folderChevronOpen]: !isCollapsed(),
}}
size={16}
strokeWidth={2}
/>
<Folder class={styles.icon} size={18} strokeWidth={2} />
<span class={styles.label}>{node.label}</span>
<Show when={node.meta}>
<span class={styles.itemMeta}>{node.meta}</span>
</Show>
</button>
<Show when={!isCollapsed() && (node.children.length > 0 || props.pendingFolderDraft?.parentId === node.id)}>
<ProjectFolderBranch
nodes={node.children}
depth={props.depth + 1}
parentId={node.id}
selectedProjectId={props.selectedProjectId}
isFolderCollapsed={props.isFolderCollapsed}
onToggleFolder={props.onToggleFolder}
onSelectProject={props.onSelectProject}
onOpenFolderMenu={props.onOpenFolderMenu}
onOpenProjectMenu={props.onOpenProjectMenu}
onNodePointerDown={props.onNodePointerDown}
onNodePointerMove={props.onNodePointerMove}
pendingFolderDraft={props.pendingFolderDraft}
pendingFolderName={props.pendingFolderName}
onPendingFolderNameChange={props.onPendingFolderNameChange}
onSubmitPendingFolder={props.onSubmitPendingFolder}
onCancelPendingFolder={props.onCancelPendingFolder}
dragState={props.dragState}
/>
</Show>
</li>
);
}
return (
<li>
<button
type="button"
classList={{
[styles.treeItem]: true,
[styles.treeItemActive]: props.selectedProjectId === node.item.id,
[styles.treeItemDragging]: isDraggedNode(),
[styles.treeItemDropBefore]: dropIntent() === "before",
[styles.treeItemDropAfter]: dropIntent() === "after",
}}
style={{ "--tree-depth": String(props.depth) }}
onClick={(): void => {
if (props.dragState || suppressNextTreeClick()) {
return;
}
props.onSelectProject(node.item.id);
}}
onContextMenu={(event): void => props.onOpenProjectMenu(event, node.item)}
onPointerDown={(event): void => props.onNodePointerDown(event, node.item.id)}
onPointerMove={(event): void =>
props.onNodePointerMove(event, props.parentId, indexAccessor(), node)
}
onPointerEnter={(event): void =>
props.onNodePointerMove(event, props.parentId, indexAccessor(), node)
}
>
<LayoutGrid class={styles.icon} size={18} strokeWidth={2} />
<span class={styles.label}>{node.item.name}</span>
<Show when={node.item.meta}>
<span class={styles.itemMeta}>{node.item.meta}</span>
</Show>
</button>
</li>
);
}}
</For>
<Show when={props.pendingFolderDraft?.parentId === props.parentId}>
<ProjectFolderDraftRow
depth={props.pendingFolderDraft?.depth ?? props.depth}
value={props.pendingFolderName}
onInput={props.onPendingFolderNameChange}
onSubmit={props.onSubmitPendingFolder}
onCancel={props.onCancelPendingFolder}
/>
</Show>
</ul>
);
export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => { export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
const appShellData = useAppShellData(); const appShellData = useAppShellData();
const [selectedProject, setSelectedProject] = createSignal(appShellData.activeProject()); const [selectedProject, setSelectedProject] = createSignal(appShellData.activeProject());
const [drawerTop, setDrawerTop] = createSignal<number>(0); const [drawerTop, setDrawerTop] = createSignal<number>(0);
const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]); const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]);
const [projectTreeNodes, setProjectTreeNodes] = createSignal<ProjectTreeNode[]>(
buildProjectTree(appShellData.projectItems()),
);
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingProjectFolderDraft | null>(null);
const [pendingFolderName, setPendingFolderName] = createSignal("");
const [dragState, setDragState] = createSignal<ProjectDragState | null>(null);
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
let rootRef: HTMLDivElement | undefined; let rootRef: HTMLDivElement | undefined;
let triggerRef: HTMLButtonElement | undefined; let triggerRef: HTMLButtonElement | undefined;
let contextMenuRef: HTMLDivElement | undefined; let contextMenuRef: HTMLDivElement | undefined;
let longPressTimer: number | undefined;
let suppressClickTimer: number | undefined;
const contextMenu = createProjectContextMenuController(); const contextMenu = createProjectContextMenuController();
const projectFolders = createMemo(() => { const clearLongPressTimer = (): void => {
const sections = new Map<string, ProjectItem[]>(); if (longPressTimer !== undefined) {
window.clearTimeout(longPressTimer);
longPressTimer = undefined;
}
};
for (const item of appShellData.projectItems()) { const suppressTreeClickTemporarily = (): void => {
const key = item.parentLabel || item.groupLabel || "Projects"; setSuppressNextTreeClick(true);
const existing = sections.get(key);
if (existing) { if (suppressClickTimer !== undefined) {
existing.push(item); window.clearTimeout(suppressClickTimer);
continue;
} }
sections.set(key, [item]); suppressClickTimer = window.setTimeout(() => {
} setSuppressNextTreeClick(false);
suppressClickTimer = undefined;
return Array.from(sections.entries()).map(([label, items]) => ({ }, 80);
id: label.toLowerCase().replace(/\s+/g, "-"), };
label,
meta: items[0]?.groupLabel && items[0].groupLabel !== label ? items[0].groupLabel : undefined,
items,
}));
});
const isFolderCollapsed = (folderId: string): boolean => collapsedFolderIds().includes(folderId); const isFolderCollapsed = (folderId: string): boolean => collapsedFolderIds().includes(folderId);
@@ -66,6 +531,14 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
setSelectedProject(appShellData.activeProject()); setSelectedProject(appShellData.activeProject());
}); });
createEffect(() => {
setProjectTreeNodes(buildProjectTree(appShellData.projectItems()));
setCollapsedFolderIds([]);
setPendingFolderDraft(null);
setPendingFolderName("");
setDragState(null);
});
onMount(() => { onMount(() => {
if (triggerRef) { if (triggerRef) {
const updateDrawerTop = (): void => { const updateDrawerTop = (): void => {
@@ -109,8 +582,39 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
props.onClose(); props.onClose();
}; };
const handlePointerUp = (): void => {
clearLongPressTimer();
const nextDragState = dragState();
if (!nextDragState?.dropTarget) {
if (nextDragState) {
suppressTreeClickTemporarily();
}
setDragState(null);
return;
}
suppressTreeClickTemporarily();
setProjectTreeNodes((current) =>
moveProjectTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget),
);
setDragState(null);
};
const handleEscape = (event: KeyboardEvent): void => { const handleEscape = (event: KeyboardEvent): void => {
if (event.key !== "Escape" || !props.isOpen) { if (event.key !== "Escape") {
return;
}
clearLongPressTimer();
if (dragState()) {
setDragState(null);
return;
}
if (!props.isOpen) {
return; return;
} }
@@ -119,10 +623,18 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
}; };
document.addEventListener("pointerdown", handlePointerDown); document.addEventListener("pointerdown", handlePointerDown);
window.addEventListener("pointerup", handlePointerUp);
window.addEventListener("pointercancel", handlePointerUp);
window.addEventListener("keydown", handleEscape); window.addEventListener("keydown", handleEscape);
onCleanup(() => { onCleanup(() => {
clearLongPressTimer();
if (suppressClickTimer !== undefined) {
window.clearTimeout(suppressClickTimer);
}
document.removeEventListener("pointerdown", handlePointerDown); document.removeEventListener("pointerdown", handlePointerDown);
window.removeEventListener("pointerup", handlePointerUp);
window.removeEventListener("pointercancel", handlePointerUp);
window.removeEventListener("keydown", handleEscape); window.removeEventListener("keydown", handleEscape);
}); });
}); });
@@ -137,18 +649,74 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
}; };
const selectProject = (projectId: string): void => { const selectProject = (projectId: string): void => {
const nextProject = appShellData.projectItems().find((item): boolean => item.id === projectId); const location = findProjectNodeLocation(projectTreeNodes(), projectId);
if (!nextProject) { if (!location || location.node.kind !== "project") {
return; return;
} }
setSelectedProject({ id: nextProject.id, name: nextProject.name }); setSelectedProject({ id: location.node.item.id, name: location.node.item.name });
props.onClose(); props.onClose();
}; };
const handleContextActionSelect = (_action: { id: string; label: string }, _target: ProjectMenuTarget): void => { const beginFolderDraft = (parentId: string | null, depth: number): void => {
// Initial implementation keeps the project menu aligned with workspace-menu IA. if (parentId) {
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
}
setPendingFolderName("");
setPendingFolderDraft({ parentId, depth });
};
const submitPendingFolder = (): void => {
const name = pendingFolderName().trim();
const draft = pendingFolderDraft();
if (!draft) {
return;
}
if (!name) {
setPendingFolderDraft(null);
setPendingFolderName("");
return;
}
setProjectTreeNodes((current) =>
insertProjectFolderNode(current, draft.parentId, {
kind: "folder",
id: createProjectFolderId(),
label: name,
children: [],
}),
);
setPendingFolderDraft(null);
setPendingFolderName("");
};
const cancelPendingFolder = (): void => {
setPendingFolderDraft(null);
setPendingFolderName("");
};
const handleContextActionSelect = (action: { id: string; label: string }, target: ProjectMenuTarget): void => {
if (action.id !== "new-folder") {
return;
}
switch (target.kind) {
case "surface":
beginFolderDraft(null, 0);
return;
case "folder":
beginFolderDraft(target.id, (findProjectNodeDepth(projectTreeNodes(), target.id) ?? 0) + 1);
return;
case "project": {
const parentId = findProjectNodeLocation(projectTreeNodes(), target.id)?.parentId ?? null;
beginFolderDraft(parentId, parentId ? (findProjectNodeDepth(projectTreeNodes(), parentId) ?? 0) + 1 : 0);
return;
}
}
}; };
const handleSurfaceContextMenu = (event: MouseEvent): void => { const handleSurfaceContextMenu = (event: MouseEvent): void => {
@@ -156,12 +724,83 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
contextMenu.openMenu(event, createProjectSurfaceTarget("Projects")); contextMenu.openMenu(event, createProjectSurfaceTarget("Projects"));
}; };
const handleNodePointerDown = (event: PointerEvent, nodeId: string): void => {
if (event.button !== 0 || pendingFolderDraft()) {
return;
}
clearLongPressTimer();
longPressTimer = window.setTimeout(() => {
suppressTreeClickTemporarily();
setDragState({ draggedNodeId: nodeId, dropTarget: null });
}, LONG_PRESS_MS);
};
const handleNodePointerMove = (
event: PointerEvent,
parentId: string | null,
index: number,
node: ProjectTreeNode,
): void => {
const nextDragState = dragState();
if (!nextDragState) {
return;
}
if (nextDragState.draggedNodeId === getProjectTreeNodeId(node)) {
return;
}
const bounds = event.currentTarget.getBoundingClientRect();
const relativeY = bounds.height <= 0 ? 0.5 : (event.clientY - bounds.top) / bounds.height;
let nextTarget: ProjectDragTarget;
if (node.kind === "folder") {
if (relativeY < 0.28) {
nextTarget = {
parentId,
index,
intent: "before",
targetNodeId: node.id,
};
} else if (relativeY > 0.72) {
nextTarget = {
parentId,
index: index + 1,
intent: "after",
targetNodeId: node.id,
};
} else {
nextTarget = {
parentId: node.id,
index: node.children.length,
intent: "inside",
targetNodeId: node.id,
};
}
} else {
nextTarget = {
parentId,
index: relativeY < 0.5 ? index : index + 1,
intent: relativeY < 0.5 ? "before" : "after",
targetNodeId: node.item.id,
};
}
setDragState({
...nextDragState,
dropTarget: nextTarget,
});
};
return ( return (
<div <div
ref={rootRef} ref={rootRef}
classList={{ classList={{
[styles.root]: true, [styles.root]: true,
[styles.rootCompact]: !!props.compact, [styles.rootCompact]: !!props.compact,
[styles.rootDragMode]: !!dragState(),
}} }}
style={{ style={{
"--project-drawer-top": `${drawerTop()}px`, "--project-drawer-top": `${drawerTop()}px`,
@@ -226,79 +865,31 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
<div class={styles.treeSectionLabel}>Projects</div> <div class={styles.treeSectionLabel}>Projects</div>
</Show> </Show>
<ul class={styles.treeList} role="list"> <ProjectFolderBranch
<For each={projectFolders()}> nodes={projectTreeNodes()}
{(folder): JSX.Element => { depth={0}
const isCollapsed = (): boolean => isFolderCollapsed(folder.id); parentId={null}
selectedProjectId={selectedProject().id}
return ( isFolderCollapsed={isFolderCollapsed}
<li> onToggleFolder={toggleFolder}
<button onSelectProject={selectProject}
type="button" onOpenFolderMenu={(event, folder): void => {
classList={{
[styles.treeItem]: true,
[styles.treeItemFolder]: true,
}}
aria-expanded={!isCollapsed()}
onClick={() => toggleFolder(folder.id)}
onContextMenu={(event): void => {
event.stopPropagation(); event.stopPropagation();
contextMenu.openMenu(event, createProjectFolderTarget(folder.id, folder.label)); contextMenu.openMenu(event, createProjectFolderTarget(folder.id, folder.label));
}} }}
> onOpenProjectMenu={(event, item): void => {
<ChevronRight
classList={{
[styles.folderChevron]: true,
[styles.folderChevronOpen]: !isCollapsed(),
}}
size={16}
strokeWidth={2}
/>
<Folder class={styles.icon} size={18} strokeWidth={2} />
<span class={styles.label}>{folder.label}</span>
<Show when={folder.meta}>
<span class={styles.itemMeta}>{folder.meta}</span>
</Show>
</button>
<Show when={!isCollapsed()}>
<ul class={styles.treeList} role="list">
<For each={folder.items}>
{(item): JSX.Element => {
const isSelected = (): boolean => selectedProject().id === item.id;
return (
<li>
<button
type="button"
classList={{
[styles.treeItem]: true,
[styles.treeItemActive]: isSelected(),
}}
style={{ "--tree-depth": "1" }}
onClick={(): void => selectProject(item.id)}
onContextMenu={(event): void => {
event.stopPropagation(); event.stopPropagation();
contextMenu.openMenu(event, createProjectTarget(item)); contextMenu.openMenu(event, createProjectTarget(item));
}} }}
> onNodePointerDown={handleNodePointerDown}
<LayoutGrid class={styles.icon} size={18} strokeWidth={2} /> onNodePointerMove={handleNodePointerMove}
<span class={styles.label}>{item.name}</span> pendingFolderDraft={pendingFolderDraft()}
<Show when={item.meta}> pendingFolderName={pendingFolderName()}
<span class={styles.itemMeta}>{item.meta}</span> onPendingFolderNameChange={setPendingFolderName}
</Show> onSubmitPendingFolder={submitPendingFolder}
</button> onCancelPendingFolder={cancelPendingFolder}
</li> dragState={dragState()}
); />
}}
</For>
</ul>
</Show>
</li>
);
}}
</For>
</ul>
</div> </div>
</div> </div>
</> </>
@@ -12,6 +12,15 @@
isolation: isolate; isolation: isolate;
} }
.sidebarDragMode {
user-select: none;
cursor: grabbing;
}
.sidebarDragMode .treeItem {
cursor: grabbing;
}
.header { .header {
display: grid; display: grid;
gap: var(--space-3); gap: var(--space-3);
@@ -123,6 +132,43 @@
padding: 0; padding: 0;
} }
.treeEmptySlot {
min-height: calc(var(--control-size-lg) - var(--space-2));
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
border-radius: var(--radius-lg);
border: 1px dashed color-mix(in srgb, var(--color-border) 38%, transparent);
opacity: 0.35;
}
.treeInputRow {
width: 100%;
min-width: 0;
display: grid;
grid-template-columns: auto minmax(0, 1fr);
align-items: center;
gap: var(--space-2);
min-height: calc(var(--control-size-lg) - var(--space-2));
padding: var(--space-2) var(--space-3);
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
border: 1px solid color-mix(in srgb, var(--color-border) 42%, transparent);
border-radius: var(--radius-lg);
background: color-mix(in srgb, var(--color-surface) 94%, transparent);
}
.treeInput {
width: 100%;
min-width: 0;
border: 0;
background: transparent;
color: var(--color-text);
font: inherit;
outline: none;
}
.treeInput::placeholder {
color: var(--color-text-muted);
}
.navItem { .navItem {
width: 100%; width: 100%;
min-width: 0; min-width: 0;
@@ -141,7 +187,7 @@
width: 100%; width: 100%;
min-width: 0; min-width: 0;
display: grid; display: grid;
grid-template-columns: auto minmax(0, 1fr) auto; grid-template-columns: auto auto minmax(0, 1fr) auto;
align-items: center; align-items: center;
gap: var(--space-2); gap: var(--space-2);
min-height: calc(var(--control-size-lg) - var(--space-2)); min-height: calc(var(--control-size-lg) - var(--space-2));
@@ -156,19 +202,51 @@
background 160ms var(--easing-standard), background 160ms var(--easing-standard),
color 160ms var(--easing-standard), color 160ms var(--easing-standard),
border-color 160ms var(--easing-standard), border-color 160ms var(--easing-standard),
box-shadow 160ms var(--easing-standard),
transform 180ms var(--easing-standard); transform 180ms var(--easing-standard);
} }
.treeItem:hover, .treeItem:hover,
.treeItem:focus-visible { .treeItem:focus-visible {
background: var(--color-surface-hover); background: color-mix(in srgb, var(--color-surface-hover) 80%, var(--color-accent-soft) 20%);
color: var(--color-text); color: var(--color-text);
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
} }
.treeItemFolder { .treeItemFolder {
color: var(--color-text); color: var(--color-text);
} }
.treeItemDragging {
opacity: 0.45;
transform: scale(0.985);
box-shadow: none;
}
.treeItemDropBefore {
box-shadow: inset 0 2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
}
.treeItemDropAfter {
box-shadow: inset 0 -2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
}
.treeItemDropInside {
border-color: color-mix(in srgb, var(--color-accent-strong) 55%, transparent);
background: color-mix(in srgb, var(--color-accent-soft) 36%, var(--color-surface));
color: var(--color-text);
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
}
.folderChevron {
color: var(--color-text-muted);
transition: transform 160ms var(--easing-standard);
}
.folderChevronOpen {
transform: rotate(90deg);
}
.treeItemActive { .treeItemActive {
border-color: var(--color-border); border-color: var(--color-border);
background: var(--color-surface); background: var(--color-surface);
@@ -1,7 +1,7 @@
// Path: Frontend/src/components/shell/WorkspaceSidebar/WorkspaceSidebar.tsx // Path: Frontend/src/components/shell/WorkspaceSidebar/WorkspaceSidebar.tsx
import { For, Show, createMemo, createSignal, type JSX } from "solid-js"; import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
import { ChevronLeft, ChevronRight } from "../../../lib/icons"; import { ChevronLeft, ChevronRight, Folder } from "../../../lib/icons";
import { useAppShellData } from "../data/app-shell.context"; import { useAppShellData } from "../data/app-shell.context";
import { ProjectSelector } from "../ProjectSelector/ProjectSelector"; import { ProjectSelector } from "../ProjectSelector/ProjectSelector";
import { import {
@@ -26,12 +26,276 @@ type WorkspaceSidebarProps = {
onToggleRailCollapse: () => void; onToggleRailCollapse: () => void;
}; };
type PendingWorkspaceFolderDraft = {
parentId: string | null;
depth: number;
};
type WorkspaceDragTarget = {
parentId: string | null;
index: number;
intent: "before" | "after" | "inside";
targetNodeId?: string;
};
type WorkspaceDragState = {
draggedNodeId: string;
dropTarget: WorkspaceDragTarget | null;
};
type WorkspaceNodeLocation = {
parentId: string | null;
index: number;
node: WorkspaceTreeNode;
};
const LONG_PRESS_MS = 320;
const createWorkspaceFolderId = (): string => `folder-${Math.random().toString(36).slice(2, 10)}`;
const getWorkspaceTreeNodeId = (node: WorkspaceTreeNode): string => node.id;
const insertWorkspaceFolderNode = (
nodes: readonly WorkspaceTreeNode[],
parentId: string | null,
folder: WorkspaceTreeNode,
): readonly WorkspaceTreeNode[] => {
if (parentId === null) {
return [...nodes, folder];
}
return nodes.map((node) => {
if (node.kind !== "folder") {
return node;
}
if (node.id === parentId) {
return {
...node,
children: [...(node.children ?? []), folder],
};
}
return {
...node,
children: node.children ? insertWorkspaceFolderNode(node.children, parentId, folder) : node.children,
};
});
};
const findWorkspaceFolderDepth = (nodes: readonly WorkspaceTreeNode[], folderId: string, depth = 0): number | null => {
for (const node of nodes) {
if (node.kind !== "folder") {
continue;
}
if (node.id === folderId) {
return depth;
}
const nestedDepth = node.children ? findWorkspaceFolderDepth(node.children, folderId, depth + 1) : null;
if (nestedDepth !== null) {
return nestedDepth;
}
}
return null;
};
const findWorkspaceNodeLocation = (
nodes: readonly WorkspaceTreeNode[],
nodeId: string,
parentId: string | null = null,
): WorkspaceNodeLocation | null => {
for (let index = 0; index < nodes.length; index += 1) {
const node = nodes[index];
if (node.id === nodeId) {
return { parentId, index, node };
}
if (node.kind === "folder" && node.children) {
const nestedLocation = findWorkspaceNodeLocation(node.children, nodeId, node.id);
if (nestedLocation) {
return nestedLocation;
}
}
}
return null;
};
const workspaceTreeContainsNode = (nodes: readonly WorkspaceTreeNode[], nodeId: string): boolean => {
for (const node of nodes) {
if (node.id === nodeId) {
return true;
}
if (node.kind === "folder" && node.children && workspaceTreeContainsNode(node.children, nodeId)) {
return true;
}
}
return false;
};
const removeWorkspaceTreeNode = (
nodes: readonly WorkspaceTreeNode[],
nodeId: string,
): { nodes: WorkspaceTreeNode[]; removed: WorkspaceTreeNode | null } => {
const nextNodes: WorkspaceTreeNode[] = [];
let removed: WorkspaceTreeNode | null = null;
for (const node of nodes) {
if (node.id === nodeId) {
removed = node;
continue;
}
if (node.kind === "folder" && node.children) {
const result = removeWorkspaceTreeNode(node.children, nodeId);
if (result.removed) {
removed = result.removed;
nextNodes.push({
...node,
children: result.nodes,
});
continue;
}
}
nextNodes.push(node);
}
return { nodes: nextNodes, removed };
};
const insertWorkspaceTreeNode = (
nodes: readonly WorkspaceTreeNode[],
parentId: string | null,
index: number,
nodeToInsert: WorkspaceTreeNode,
): WorkspaceTreeNode[] => {
if (parentId === null) {
const nextNodes = [...nodes];
nextNodes.splice(Math.max(0, Math.min(index, nextNodes.length)), 0, nodeToInsert);
return nextNodes;
}
return nodes.map((node) => {
if (node.kind !== "folder") {
return node;
}
if (node.id === parentId) {
const nextChildren = [...(node.children ?? [])];
nextChildren.splice(Math.max(0, Math.min(index, nextChildren.length)), 0, nodeToInsert);
return {
...node,
children: nextChildren,
};
}
return {
...node,
children: node.children ? insertWorkspaceTreeNode(node.children, parentId, index, nodeToInsert) : node.children,
};
});
};
const moveWorkspaceTreeNode = (
nodes: readonly WorkspaceTreeNode[],
draggedNodeId: string,
dropTarget: WorkspaceDragTarget,
): WorkspaceTreeNode[] => {
const location = findWorkspaceNodeLocation(nodes, draggedNodeId);
if (!location) {
return [...nodes];
}
if (
location.node.kind === "folder" &&
dropTarget.parentId !== null &&
((location.node.children && workspaceTreeContainsNode(location.node.children, dropTarget.parentId)) ||
dropTarget.parentId === location.node.id)
) {
return [...nodes];
}
let normalizedIndex = dropTarget.index;
if (dropTarget.parentId === location.parentId && dropTarget.index > location.index) {
normalizedIndex -= 1;
}
if (dropTarget.parentId === location.parentId && normalizedIndex === location.index) {
return [...nodes];
}
const removalResult = removeWorkspaceTreeNode(nodes, draggedNodeId);
if (!removalResult.removed) {
return [...nodes];
}
return insertWorkspaceTreeNode(removalResult.nodes, dropTarget.parentId, normalizedIndex, removalResult.removed);
};
const FolderDraftRow = (props: {
depth: number;
value: string;
onInput: (value: string) => void;
onSubmit: () => void;
onCancel: () => void;
}): JSX.Element => {
let inputRef: HTMLInputElement | undefined;
queueMicrotask(() => inputRef?.focus());
return (
<li>
<div class={styles.treeInputRow} style={{ "--tree-depth": String(props.depth) }}>
<Folder class={styles.icon} size={18} strokeWidth={2} />
<input
ref={inputRef}
type="text"
class={styles.treeInput}
value={props.value}
placeholder="Folder name"
onInput={(event): void => props.onInput(event.currentTarget.value)}
onBlur={props.onSubmit}
onKeyDown={(event): void => {
if (event.key === "Enter") {
event.preventDefault();
event.currentTarget.blur();
return;
}
if (event.key === "Escape") {
event.preventDefault();
props.onCancel();
event.currentTarget.blur();
}
}}
/>
</div>
</li>
);
};
const isContextMenuKeyboardTrigger = (event: KeyboardEvent): boolean => event.key === "ContextMenu" || (event.shiftKey && event.key === "F10"); const isContextMenuKeyboardTrigger = (event: KeyboardEvent): boolean => event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");
const WorkspaceHomeEntry = (props: { const WorkspaceHomeEntry = (props: {
item: WorkspaceStaticItem; item: WorkspaceStaticItem;
onOpenContextMenu: (event: MouseEvent, target: WorkspaceContextMenuTarget) => void; onOpenContextMenu: (event: MouseEvent, target: WorkspaceContextMenuTarget) => void;
onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void; onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void;
onNodePointerDown: (event: PointerEvent, nodeId: string) => void;
onNodePointerMove: (event: PointerEvent, parentId: string | null, index: number, node: WorkspaceTreeNode) => void;
dragState: WorkspaceDragState | null;
isTreeClickSuppressed: () => boolean;
}): JSX.Element => { }): JSX.Element => {
const Icon = props.item.icon; const Icon = props.item.icon;
const target = createWorkspaceStaticTarget(props.item); const target = createWorkspaceStaticTarget(props.item);
@@ -75,18 +339,41 @@ const WorkspaceHomeEntry = (props: {
const WorkspaceTreeBranch = (props: { const WorkspaceTreeBranch = (props: {
nodes: readonly WorkspaceTreeNode[]; nodes: readonly WorkspaceTreeNode[];
parentId?: string | null;
depth?: number; depth?: number;
isFolderCollapsed: (folderId: string) => boolean;
onToggleFolder: (folderId: string) => void;
pendingFolderDraft: PendingWorkspaceFolderDraft | null;
pendingFolderName: string;
onPendingFolderNameChange: (value: string) => void;
onSubmitPendingFolder: () => void;
onCancelPendingFolder: () => void;
onOpenContextMenu: (event: MouseEvent, target: WorkspaceContextMenuTarget) => void; onOpenContextMenu: (event: MouseEvent, target: WorkspaceContextMenuTarget) => void;
onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void; onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void;
}): JSX.Element => { }): JSX.Element => {
const depth = () => props.depth ?? 0; const depth = () => props.depth ?? 0;
const parentId = () => props.parentId ?? null;
return ( return (
<ul class={styles.treeList} role="list"> <ul class={styles.treeList} role="list">
<Show when={props.nodes.length === 0 && props.pendingFolderDraft?.parentId !== parentId()}>
<li>
<div class={styles.treeEmptySlot} style={{ "--tree-depth": String(depth()) }} />
</li>
</Show>
<For each={props.nodes}> <For each={props.nodes}>
{(node): JSX.Element => { {(node, indexAccessor): JSX.Element => {
const Icon = getWorkspaceNodeIcon(node); const Icon = getWorkspaceNodeIcon(node);
const target = createWorkspaceTreeTarget(node); const target = createWorkspaceTreeTarget(node);
const isCollapsed = (): boolean => (node.kind === "folder" ? props.isFolderCollapsed(node.id) : false);
const isDraggedNode = (): boolean => props.dragState?.draggedNodeId === node.id;
const dropIntent = (): WorkspaceDragTarget["intent"] | null => {
if (props.dragState?.dropTarget?.targetNodeId !== node.id) {
return null;
}
return props.dragState.dropTarget.intent;
};
return ( return (
<li> <li>
@@ -96,8 +383,13 @@ const WorkspaceTreeBranch = (props: {
[styles.treeItem]: true, [styles.treeItem]: true,
[styles.treeItemActive]: !!node.active, [styles.treeItemActive]: !!node.active,
[styles.treeItemFolder]: node.kind === "folder", [styles.treeItemFolder]: node.kind === "folder",
[styles.treeItemDragging]: isDraggedNode(),
[styles.treeItemDropBefore]: dropIntent() === "before",
[styles.treeItemDropAfter]: dropIntent() === "after",
[styles.treeItemDropInside]: dropIntent() === "inside",
}} }}
style={{ "--tree-depth": String(depth()) }} style={{ "--tree-depth": String(depth()) }}
aria-expanded={node.kind === "folder" ? !isCollapsed() : undefined}
aria-current={node.active ? "page" : undefined} aria-current={node.active ? "page" : undefined}
aria-label={node.label} aria-label={node.label}
title={node.label} title={node.label}
@@ -105,10 +397,28 @@ const WorkspaceTreeBranch = (props: {
data-kind={node.kind} data-kind={node.kind}
data-item-type={node.kind === "item" ? node.itemType : undefined} data-item-type={node.kind === "item" ? node.itemType : undefined}
data-active={node.active ? "true" : "false"} data-active={node.active ? "true" : "false"}
onClick={(): void => {
if (props.dragState || props.isTreeClickSuppressed()) {
return;
}
if (node.kind !== "folder") {
return;
}
props.onToggleFolder(node.id);
}}
onContextMenu={(event): void => { onContextMenu={(event): void => {
event.stopPropagation(); event.stopPropagation();
props.onOpenContextMenu(event, target); props.onOpenContextMenu(event, target);
}} }}
onPointerDown={(event): void => props.onNodePointerDown(event, node.id)}
onPointerMove={(event): void =>
props.onNodePointerMove(event, parentId(), indexAccessor(), node)
}
onPointerEnter={(event): void =>
props.onNodePointerMove(event, parentId(), indexAccessor(), node)
}
onKeyDown={(event): void => { onKeyDown={(event): void => {
if (!isContextMenuKeyboardTrigger(event)) { if (!isContextMenuKeyboardTrigger(event)) {
return; return;
@@ -118,6 +428,16 @@ const WorkspaceTreeBranch = (props: {
props.onOpenContextMenuFromKeyboard(event.currentTarget, target); props.onOpenContextMenuFromKeyboard(event.currentTarget, target);
}} }}
> >
<Show when={node.kind === "folder"}>
<ChevronRight
classList={{
[styles.folderChevron]: true,
[styles.folderChevronOpen]: !isCollapsed(),
}}
size={16}
strokeWidth={2}
/>
</Show>
<Icon class={styles.icon} size={18} strokeWidth={2} /> <Icon class={styles.icon} size={18} strokeWidth={2} />
<span class={styles.label}>{node.label}</span> <span class={styles.label}>{node.label}</span>
<Show when={node.meta}> <Show when={node.meta}>
@@ -125,18 +445,40 @@ const WorkspaceTreeBranch = (props: {
</Show> </Show>
</button> </button>
<Show when={node.children?.length}> <Show when={node.kind === "folder" && !isCollapsed() && (((node.children?.length ?? 0) > 0) || props.pendingFolderDraft?.parentId === node.id)}>
<WorkspaceTreeBranch <WorkspaceTreeBranch
nodes={node.children ?? []} nodes={node.children ?? []}
parentId={node.id}
depth={depth() + 1} depth={depth() + 1}
isFolderCollapsed={props.isFolderCollapsed}
onToggleFolder={props.onToggleFolder}
pendingFolderDraft={props.pendingFolderDraft}
pendingFolderName={props.pendingFolderName}
onPendingFolderNameChange={props.onPendingFolderNameChange}
onSubmitPendingFolder={props.onSubmitPendingFolder}
onCancelPendingFolder={props.onCancelPendingFolder}
onOpenContextMenu={props.onOpenContextMenu} onOpenContextMenu={props.onOpenContextMenu}
onOpenContextMenuFromKeyboard={props.onOpenContextMenuFromKeyboard} onOpenContextMenuFromKeyboard={props.onOpenContextMenuFromKeyboard}
onNodePointerDown={props.onNodePointerDown}
onNodePointerMove={props.onNodePointerMove}
dragState={props.dragState}
isTreeClickSuppressed={props.isTreeClickSuppressed}
/> />
</Show> </Show>
</li> </li>
); );
}} }}
</For> </For>
<Show when={props.pendingFolderDraft && props.pendingFolderDraft.parentId === parentId()}>
<FolderDraftRow
depth={props.pendingFolderDraft?.depth ?? depth()}
value={props.pendingFolderName}
onInput={props.onPendingFolderNameChange}
onSubmit={props.onSubmitPendingFolder}
onCancel={props.onCancelPendingFolder}
/>
</Show>
</ul> </ul>
); );
}; };
@@ -144,23 +486,209 @@ const WorkspaceTreeBranch = (props: {
export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => { export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
const appShellData = useAppShellData(); const appShellData = useAppShellData();
const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false); const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false);
const [workspaceTreeNodes, setWorkspaceTreeNodes] = createSignal<readonly WorkspaceTreeNode[]>(appShellData.workspaceTree());
const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]);
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingWorkspaceFolderDraft | null>(null);
const [pendingFolderName, setPendingFolderName] = createSignal("");
const [dragState, setDragState] = createSignal<WorkspaceDragState | null>(null);
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
const contextMenu = createWorkspaceContextMenuController(); const contextMenu = createWorkspaceContextMenuController();
let longPressTimer: number | undefined;
let suppressClickTimer: number | undefined;
const railToggleLabel = (): string => (props.railCollapsed ? "Expand server rail" : "Collapse server rail"); const railToggleLabel = (): string => (props.railCollapsed ? "Expand server rail" : "Collapse server rail");
const sidebarContextMenuTarget = createMemo(() => createWorkspaceSurfaceTarget(appShellData.activeProject())); const sidebarContextMenuTarget = createWorkspaceSurfaceTarget(appShellData.activeProject());
const contextMenuTarget = createMemo(() => contextMenu.menuState()?.target ?? null); const isFolderCollapsed = (folderId: string): boolean => collapsedFolderIds().includes(folderId);
const contextMenuPosition = createMemo(() => { const toggleFolder = (folderId: string): void => {
const state = contextMenu.menuState(); setCollapsedFolderIds((current) =>
current.includes(folderId) ? current.filter((id) => id !== folderId) : [...current, folderId],
return state );
? { };
x: state.x, const clearLongPressTimer = (): void => {
y: state.y, if (longPressTimer !== undefined) {
window.clearTimeout(longPressTimer);
longPressTimer = undefined;
} }
: null; };
const suppressTreeClickTemporarily = (): void => {
setSuppressNextTreeClick(true);
if (suppressClickTimer !== undefined) {
window.clearTimeout(suppressClickTimer);
}
suppressClickTimer = window.setTimeout(() => {
setSuppressNextTreeClick(false);
suppressClickTimer = undefined;
}, 80);
};
createEffect(() => {
setWorkspaceTreeNodes(appShellData.workspaceTree());
setCollapsedFolderIds([]);
setPendingFolderDraft(null);
setPendingFolderName("");
setDragState(null);
}); });
const handleContextActionSelect = (_action: WorkspaceContextMenuAction, _target: WorkspaceContextMenuTarget): void => { onMount(() => {
// Initial implementation only establishes the menu IA and placement. const handlePointerUp = (): void => {
clearLongPressTimer();
const nextDragState = dragState();
if (!nextDragState?.dropTarget) {
if (nextDragState) {
suppressTreeClickTemporarily();
}
setDragState(null);
return;
}
suppressTreeClickTemporarily();
setWorkspaceTreeNodes((current) =>
moveWorkspaceTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget),
);
setDragState(null);
};
const handleEscape = (event: KeyboardEvent): void => {
if (event.key !== "Escape") {
return;
}
clearLongPressTimer();
if (dragState()) {
setDragState(null);
}
};
window.addEventListener("pointerup", handlePointerUp);
window.addEventListener("pointercancel", handlePointerUp);
window.addEventListener("keydown", handleEscape);
onCleanup(() => {
clearLongPressTimer();
if (suppressClickTimer !== undefined) {
window.clearTimeout(suppressClickTimer);
}
window.removeEventListener("pointerup", handlePointerUp);
window.removeEventListener("pointercancel", handlePointerUp);
window.removeEventListener("keydown", handleEscape);
});
});
const beginFolderDraft = (parentId: string | null, depth: number): void => {
if (parentId) {
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
}
setPendingFolderName("");
setPendingFolderDraft({ parentId, depth });
};
const submitPendingFolder = (): void => {
const name = pendingFolderName().trim();
const draft = pendingFolderDraft();
if (!draft) {
return;
}
if (!name) {
setPendingFolderDraft(null);
setPendingFolderName("");
return;
}
setWorkspaceTreeNodes((current) =>
insertWorkspaceFolderNode(current, draft.parentId, {
id: createWorkspaceFolderId(),
label: name,
kind: "folder",
icon: Folder,
children: [],
}),
);
setPendingFolderDraft(null);
setPendingFolderName("");
};
const cancelPendingFolder = (): void => {
setPendingFolderDraft(null);
setPendingFolderName("");
};
const handleNodePointerDown = (event: PointerEvent, nodeId: string): void => {
if (event.button !== 0 || pendingFolderDraft()) {
return;
}
clearLongPressTimer();
longPressTimer = window.setTimeout(() => {
suppressTreeClickTemporarily();
setDragState({ draggedNodeId: nodeId, dropTarget: null });
}, LONG_PRESS_MS);
};
const handleNodePointerMove = (
event: PointerEvent,
parentId: string | null,
index: number,
node: WorkspaceTreeNode,
): void => {
const nextDragState = dragState();
if (!nextDragState || nextDragState.draggedNodeId === getWorkspaceTreeNodeId(node)) {
return;
}
const bounds = event.currentTarget.getBoundingClientRect();
const relativeY = bounds.height <= 0 ? 0.5 : (event.clientY - bounds.top) / bounds.height;
let nextTarget: WorkspaceDragTarget;
if (node.kind === "folder") {
if (relativeY < 0.28) {
nextTarget = { parentId, index, intent: "before", targetNodeId: node.id };
} else if (relativeY > 0.72) {
nextTarget = { parentId, index: index + 1, intent: "after", targetNodeId: node.id };
} else {
nextTarget = {
parentId: node.id,
index: (node.children ?? []).length,
intent: "inside",
targetNodeId: node.id,
};
}
} else {
nextTarget = {
parentId,
index: relativeY < 0.5 ? index : index + 1,
intent: relativeY < 0.5 ? "before" : "after",
targetNodeId: node.id,
};
}
setDragState({ ...nextDragState, dropTarget: nextTarget });
};
const handleContextActionSelect = (action: WorkspaceContextMenuAction, target: WorkspaceContextMenuTarget): void => {
if (action.id !== "new-folder") {
return;
}
switch (target.kind) {
case "workspace":
case "home":
beginFolderDraft(null, 0);
return;
case "folder":
beginFolderDraft(target.id, (findWorkspaceFolderDepth(workspaceTreeNodes(), target.id) ?? 0) + 1);
return;
case "settings":
case "item":
return;
}
}; };
return ( return (
@@ -169,12 +697,13 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
classList={{ classList={{
[styles.sidebar]: true, [styles.sidebar]: true,
[styles.sidebarCollapsed]: props.collapsed, [styles.sidebarCollapsed]: props.collapsed,
[styles.sidebarDragMode]: !!dragState(),
}} }}
aria-label="Left workspace sidebar" aria-label="Left workspace sidebar"
data-ui="workspace-sidebar" data-ui="workspace-sidebar"
data-collapsed={props.collapsed ? "true" : "false"} data-collapsed={props.collapsed ? "true" : "false"}
onContextMenu={(event): void => { onContextMenu={(event): void => {
contextMenu.openMenu(event, sidebarContextMenuTarget()); contextMenu.openMenu(event, sidebarContextMenuTarget);
}} }}
> >
<div <div
@@ -256,9 +785,21 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
<div data-slot="workspace-tree-root"> <div data-slot="workspace-tree-root">
<WorkspaceTreeBranch <WorkspaceTreeBranch
nodes={appShellData.workspaceTree()} nodes={workspaceTreeNodes()}
parentId={null}
isFolderCollapsed={isFolderCollapsed}
onToggleFolder={toggleFolder}
pendingFolderDraft={pendingFolderDraft()}
pendingFolderName={pendingFolderName()}
onPendingFolderNameChange={setPendingFolderName}
onSubmitPendingFolder={submitPendingFolder}
onCancelPendingFolder={cancelPendingFolder}
onOpenContextMenu={contextMenu.openMenu} onOpenContextMenu={contextMenu.openMenu}
onOpenContextMenuFromKeyboard={contextMenu.openMenuFromElement} onOpenContextMenuFromKeyboard={contextMenu.openMenuFromElement}
onNodePointerDown={handleNodePointerDown}
onNodePointerMove={handleNodePointerMove}
dragState={dragState()}
isTreeClickSuppressed={suppressNextTreeClick}
/> />
</div> </div>
</div> </div>
@@ -266,8 +807,16 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
</aside> </aside>
<WorkspaceContextMenu <WorkspaceContextMenu
target={contextMenuTarget()} target={contextMenu.menuState()?.target ?? null}
position={contextMenuPosition()} position={(() => {
const state = contextMenu.menuState();
return state
? {
x: state.x,
y: state.y,
}
: null;
})()}
menuRef={contextMenu.setMenuRef} menuRef={contextMenu.setMenuRef}
onClose={contextMenu.closeMenu} onClose={contextMenu.closeMenu}
onSelect={handleContextActionSelect} onSelect={handleContextActionSelect}
+1
View File
@@ -1,6 +1,7 @@
set shell := ["bash", "-cu"] set shell := ["bash", "-cu"]
mod local "Commands/Local" mod local "Commands/Local"
mod test "Commands/Test"
[default] [default]
help: help: