Compare commits
22 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c64a7b8d44 | |||
| 0b368b09fa | |||
| 212dd1c435 | |||
| 69af324b1b | |||
| 5758074f6f | |||
| 5b9e14b442 | |||
| 618e3e84be | |||
| 2ff7fbd9e7 | |||
| 8a94d83e7e | |||
| 07590f1c4f | |||
| 3c7a73853d | |||
| 9b4f1ce197 | |||
| 5735e3008d | |||
| 626ae02df0 | |||
| 7f47ca84fa | |||
| eac4fb423e | |||
| 14ac0f46de | |||
| 5a565f8165 | |||
| 12cbc68db6 | |||
| 699574e345 | |||
| 35c1a861f5 | |||
| 27101bbdd6 |
@@ -27,3 +27,5 @@ tmp/
|
|||||||
bin/
|
bin/
|
||||||
|
|
||||||
.cgcignore
|
.cgcignore
|
||||||
|
|
||||||
|
POSIX/
|
||||||
@@ -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,9 @@
|
|||||||
|
-- +goose Up
|
||||||
|
|
||||||
|
ALTER TABLE installations
|
||||||
|
ADD COLUMN IF NOT EXISTS name TEXT NOT NULL DEFAULT '';
|
||||||
|
|
||||||
|
-- +goose Down
|
||||||
|
|
||||||
|
ALTER TABLE installations
|
||||||
|
DROP COLUMN IF EXISTS name;
|
||||||
@@ -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;
|
||||||
@@ -4,13 +4,18 @@ package bootstrap
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
"strings"
|
"strings"
|
||||||
|
"unicode"
|
||||||
|
|
||||||
"github.com/jackc/pgx/v5"
|
"github.com/jackc/pgx/v5"
|
||||||
|
|
||||||
"moku-backend/internal/database"
|
"moku-backend/internal/database"
|
||||||
|
"moku-backend/internal/posixproj"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
const (
|
||||||
@@ -38,10 +43,13 @@ const (
|
|||||||
var (
|
var (
|
||||||
ErrInstallationNotConfigured = errors.New("bootstrap installation step has not been completed")
|
ErrInstallationNotConfigured = errors.New("bootstrap installation step has not been completed")
|
||||||
ErrAdminNotConfigured = errors.New("bootstrap admin step has not been completed")
|
ErrAdminNotConfigured = errors.New("bootstrap admin step has not been completed")
|
||||||
|
ErrProjectNotFound = errors.New("project not found")
|
||||||
|
ErrProjectFolderNotFound = errors.New("project folder not found")
|
||||||
)
|
)
|
||||||
|
|
||||||
type Service struct {
|
type Service struct {
|
||||||
db *database.DB
|
db *database.DB
|
||||||
|
posixRoot string
|
||||||
}
|
}
|
||||||
|
|
||||||
type SaveInstanceInput struct {
|
type SaveInstanceInput struct {
|
||||||
@@ -52,6 +60,7 @@ type SaveInstanceInput struct {
|
|||||||
|
|
||||||
type SaveModeInput struct {
|
type SaveModeInput struct {
|
||||||
Mode string
|
Mode string
|
||||||
|
Name string
|
||||||
}
|
}
|
||||||
|
|
||||||
type SaveAdminInput struct {
|
type SaveAdminInput struct {
|
||||||
@@ -69,6 +78,7 @@ type SaveStructureInput struct {
|
|||||||
|
|
||||||
type InstallationRecord struct {
|
type InstallationRecord struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
Mode string `json:"mode"`
|
Mode string `json:"mode"`
|
||||||
Access string `json:"access"`
|
Access string `json:"access"`
|
||||||
Protocol string `json:"protocol"`
|
Protocol string `json:"protocol"`
|
||||||
@@ -170,15 +180,51 @@ type namedRecord struct {
|
|||||||
Slug string `json:"slug"`
|
Slug string `json:"slug"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewService(db *database.DB) *Service {
|
type ProjectHierarchyFolderRecord struct {
|
||||||
return &Service{db: db}
|
ID string `json:"id"`
|
||||||
|
Label string `json:"label"`
|
||||||
|
Children []ProjectHierarchyFolderRecord `json:"children"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateProjectFolderInput struct {
|
||||||
|
ProjectID string
|
||||||
|
ParentFolderID string
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteProjectFolderInput struct {
|
||||||
|
ProjectID string
|
||||||
|
FolderID string
|
||||||
|
}
|
||||||
|
|
||||||
|
type CreateProjectFolderResult struct {
|
||||||
|
ProjectID string `json:"projectId"`
|
||||||
|
CreatedFolder ProjectHierarchyFolderRecord `json:"createdFolder"`
|
||||||
|
Folders []ProjectHierarchyFolderRecord `json:"folders"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type DeleteProjectFolderResult struct {
|
||||||
|
ProjectID string `json:"projectId"`
|
||||||
|
DeletedFolderID string `json:"deletedFolderId"`
|
||||||
|
Folders []ProjectHierarchyFolderRecord `json:"folders"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type projectHierarchyFolderRow struct {
|
||||||
|
Path string
|
||||||
|
ParentPath string
|
||||||
|
Label string
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewService(db *database.DB, posixRoot string) *Service {
|
||||||
|
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) {
|
||||||
row := service.db.Pool.QueryRow(ctx, `
|
row := service.db.Pool.QueryRow(ctx, `
|
||||||
INSERT INTO installations (singleton, mode, access, protocol, host)
|
INSERT INTO installations (singleton, name, mode, access, protocol, host)
|
||||||
VALUES (
|
VALUES (
|
||||||
TRUE,
|
TRUE,
|
||||||
|
COALESCE((SELECT name FROM installations WHERE singleton = TRUE LIMIT 1), ''),
|
||||||
COALESCE((SELECT mode FROM installations WHERE singleton = TRUE LIMIT 1), 'personal'::instance_mode),
|
COALESCE((SELECT mode FROM installations WHERE singleton = TRUE LIMIT 1), 'personal'::instance_mode),
|
||||||
$1::instance_access,
|
$1::instance_access,
|
||||||
$2::instance_protocol,
|
$2::instance_protocol,
|
||||||
@@ -190,7 +236,7 @@ func (service *Service) SaveInstance(ctx context.Context, input SaveInstanceInpu
|
|||||||
protocol = EXCLUDED.protocol,
|
protocol = EXCLUDED.protocol,
|
||||||
host = EXCLUDED.host,
|
host = EXCLUDED.host,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
RETURNING id::text, mode::text, access::text, protocol::text, host, is_bootstrapped;
|
RETURNING id::text, name, mode::text, access::text, protocol::text, host, is_bootstrapped;
|
||||||
`, input.Access, input.Protocol, input.Host)
|
`, input.Access, input.Protocol, input.Host)
|
||||||
|
|
||||||
return scanInstallationRecord(row)
|
return scanInstallationRecord(row)
|
||||||
@@ -198,20 +244,22 @@ func (service *Service) SaveInstance(ctx context.Context, input SaveInstanceInpu
|
|||||||
|
|
||||||
func (service *Service) SaveMode(ctx context.Context, input SaveModeInput) (InstallationRecord, error) {
|
func (service *Service) SaveMode(ctx context.Context, input SaveModeInput) (InstallationRecord, error) {
|
||||||
row := service.db.Pool.QueryRow(ctx, `
|
row := service.db.Pool.QueryRow(ctx, `
|
||||||
INSERT INTO installations (singleton, mode, access, protocol, host)
|
INSERT INTO installations (singleton, name, mode, access, protocol, host)
|
||||||
VALUES (
|
VALUES (
|
||||||
TRUE,
|
TRUE,
|
||||||
|
$2,
|
||||||
$1::instance_mode,
|
$1::instance_mode,
|
||||||
COALESCE((SELECT access FROM installations WHERE singleton = TRUE LIMIT 1), 'local'::instance_access),
|
COALESCE((SELECT access FROM installations WHERE singleton = TRUE LIMIT 1), 'local'::instance_access),
|
||||||
COALESCE((SELECT protocol FROM installations WHERE singleton = TRUE LIMIT 1), 'http'::instance_protocol),
|
COALESCE((SELECT protocol FROM installations WHERE singleton = TRUE LIMIT 1), 'http'::instance_protocol),
|
||||||
COALESCE((SELECT host FROM installations WHERE singleton = TRUE LIMIT 1), $2)
|
COALESCE((SELECT host FROM installations WHERE singleton = TRUE LIMIT 1), $3)
|
||||||
)
|
)
|
||||||
ON CONFLICT (singleton) DO UPDATE
|
ON CONFLICT (singleton) DO UPDATE
|
||||||
SET
|
SET
|
||||||
|
name = EXCLUDED.name,
|
||||||
mode = EXCLUDED.mode,
|
mode = EXCLUDED.mode,
|
||||||
updated_at = NOW()
|
updated_at = NOW()
|
||||||
RETURNING id::text, mode::text, access::text, protocol::text, host, is_bootstrapped;
|
RETURNING id::text, name, mode::text, access::text, protocol::text, host, is_bootstrapped;
|
||||||
`, input.Mode, defaultInstallationHost)
|
`, input.Mode, input.Name, defaultInstallationHost)
|
||||||
|
|
||||||
return scanInstallationRecord(row)
|
return scanInstallationRecord(row)
|
||||||
}
|
}
|
||||||
@@ -301,7 +349,7 @@ func (service *Service) SaveStructure(ctx context.Context, input SaveStructureIn
|
|||||||
|
|
||||||
organizationName := strings.TrimSpace(input.OrganizationName)
|
organizationName := strings.TrimSpace(input.OrganizationName)
|
||||||
if organizationName == "" {
|
if organizationName == "" {
|
||||||
organizationName = defaultRootOrganizationName(installation.Mode, installation.Host, admin.DisplayName)
|
organizationName = defaultRootOrganizationName(installation.Name, installation.Mode, installation.Host, admin.DisplayName)
|
||||||
}
|
}
|
||||||
|
|
||||||
organization, err := upsertNamedRecord(ctx, tx, `
|
organization, err := upsertNamedRecord(ctx, tx, `
|
||||||
@@ -400,6 +448,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,
|
||||||
@@ -410,9 +466,39 @@ func (service *Service) SaveStructure(ctx context.Context, input SaveStructureIn
|
|||||||
}, nil
|
}, nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (service *Service) ResetDevelopmentState(ctx context.Context) error {
|
||||||
|
tx, err := service.db.Pool.BeginTx(ctx, pgx.TxOptions{})
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
defer func() {
|
||||||
|
_ = tx.Rollback(ctx)
|
||||||
|
}()
|
||||||
|
|
||||||
|
if _, err := tx.Exec(ctx, `
|
||||||
|
TRUNCATE TABLE
|
||||||
|
project_memberships,
|
||||||
|
team_memberships,
|
||||||
|
organization_memberships,
|
||||||
|
workspaces,
|
||||||
|
projects,
|
||||||
|
teams,
|
||||||
|
departments,
|
||||||
|
user_homes,
|
||||||
|
users,
|
||||||
|
organizations,
|
||||||
|
installations
|
||||||
|
RESTART IDENTITY;
|
||||||
|
`); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
|
||||||
|
return tx.Commit(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
func (service *Service) GetInstallation(ctx context.Context) (*InstallationRecord, error) {
|
func (service *Service) GetInstallation(ctx context.Context) (*InstallationRecord, error) {
|
||||||
record, err := scanInstallationRecord(service.db.Pool.QueryRow(ctx, `
|
record, err := scanInstallationRecord(service.db.Pool.QueryRow(ctx, `
|
||||||
SELECT id::text, mode::text, access::text, protocol::text, host, is_bootstrapped
|
SELECT id::text, name, mode::text, access::text, protocol::text, host, is_bootstrapped
|
||||||
FROM installations
|
FROM installations
|
||||||
WHERE singleton = TRUE
|
WHERE singleton = TRUE
|
||||||
LIMIT 1;
|
LIMIT 1;
|
||||||
@@ -567,7 +653,7 @@ func (service *Service) GetAppShellState(ctx context.Context) (AppShellState, er
|
|||||||
|
|
||||||
func scanInstallationRecord(row pgx.Row) (InstallationRecord, error) {
|
func scanInstallationRecord(row pgx.Row) (InstallationRecord, error) {
|
||||||
var record InstallationRecord
|
var record InstallationRecord
|
||||||
if err := row.Scan(&record.ID, &record.Mode, &record.Access, &record.Protocol, &record.Host, &record.IsBootstrapped); err != nil {
|
if err := row.Scan(&record.ID, &record.Name, &record.Mode, &record.Access, &record.Protocol, &record.Host, &record.IsBootstrapped); err != nil {
|
||||||
return InstallationRecord{}, err
|
return InstallationRecord{}, err
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -746,6 +832,164 @@ func (service *Service) listProjects(ctx context.Context) ([]ProjectRecord, erro
|
|||||||
return records, rows.Err()
|
return records, rows.Err()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (service *Service) loadProjectByID(ctx context.Context, projectID string) (*ProjectRecord, error) {
|
||||||
|
var record ProjectRecord
|
||||||
|
err := service.db.Pool.QueryRow(ctx, `
|
||||||
|
SELECT id::text, organization_id::text, department_id::text, team_id::text, name, slug
|
||||||
|
FROM projects
|
||||||
|
WHERE id = $1::uuid
|
||||||
|
LIMIT 1;
|
||||||
|
`, projectID).Scan(&record.ID, &record.OrganizationID, &record.DepartmentID, &record.TeamID, &record.Name, &record.Slug)
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, pgx.ErrNoRows) {
|
||||||
|
return nil, ErrProjectNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return &record, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) GetProjectHierarchyFolders(ctx context.Context, projectID string) ([]ProjectHierarchyFolderRecord, error) {
|
||||||
|
return service.getProjectHierarchyFoldersByRootPath(ctx, projectID, projectHierarchyRootPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) GetProjectTreeFolders(ctx context.Context, projectID string) ([]ProjectHierarchyFolderRecord, error) {
|
||||||
|
return service.getProjectHierarchyFoldersByRootPath(ctx, projectID, projectTreeRootPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) getProjectHierarchyFoldersByRootPath(
|
||||||
|
ctx context.Context,
|
||||||
|
projectID string,
|
||||||
|
rootPath func(projectSlug string) string,
|
||||||
|
) ([]ProjectHierarchyFolderRecord, error) {
|
||||||
|
project, err := service.loadProjectByID(ctx, projectID)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
rootParentPath := rootPath(project.Slug)
|
||||||
|
|
||||||
|
rows, err := service.db.Pool.Query(ctx, `
|
||||||
|
SELECT path, COALESCE(parent_path, ''), COALESCE(resource_name, '')
|
||||||
|
FROM posix_nodes
|
||||||
|
WHERE node_kind = 'directory'::posix_node_kind
|
||||||
|
AND logical_type = 'hierarchy_folder'
|
||||||
|
AND project_slug = $1
|
||||||
|
AND path LIKE $2
|
||||||
|
ORDER BY depth ASC, path ASC;
|
||||||
|
`, project.Slug, rootParentPath+"/%")
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
defer rows.Close()
|
||||||
|
|
||||||
|
var folderRows []projectHierarchyFolderRow
|
||||||
|
for rows.Next() {
|
||||||
|
var row projectHierarchyFolderRow
|
||||||
|
if err := rows.Scan(&row.Path, &row.ParentPath, &row.Label); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
folderRows = append(folderRows, row)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := rows.Err(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
return buildProjectHierarchyFolderTree(folderRows, rootParentPath), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) CreateProjectFolder(ctx context.Context, input CreateProjectFolderInput) (CreateProjectFolderResult, error) {
|
||||||
|
return service.createProjectHierarchyFolder(ctx, input, projectHierarchyRootPath, service.createProjectHierarchyFolderOnDisk)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) CreateProjectTreeFolder(ctx context.Context, input CreateProjectFolderInput) (CreateProjectFolderResult, error) {
|
||||||
|
return service.createProjectHierarchyFolder(ctx, input, projectTreeRootPath, service.createProjectTreeFolderOnDisk)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) DeleteProjectFolder(ctx context.Context, input DeleteProjectFolderInput) (DeleteProjectFolderResult, error) {
|
||||||
|
return service.deleteProjectHierarchyFolder(ctx, input, projectHierarchyRootPath, service.deleteProjectHierarchyFolderOnDisk)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) DeleteProjectTreeFolder(ctx context.Context, input DeleteProjectFolderInput) (DeleteProjectFolderResult, error) {
|
||||||
|
return service.deleteProjectHierarchyFolder(ctx, input, projectTreeRootPath, service.deleteProjectTreeFolderOnDisk)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) createProjectHierarchyFolder(
|
||||||
|
ctx context.Context,
|
||||||
|
input CreateProjectFolderInput,
|
||||||
|
rootPath func(projectSlug string) string,
|
||||||
|
createOnDisk func(projectSlug, parentFolderID, name string) (string, string, error),
|
||||||
|
) (CreateProjectFolderResult, error) {
|
||||||
|
project, err := service.loadProjectByID(ctx, strings.TrimSpace(input.ProjectID))
|
||||||
|
if err != nil {
|
||||||
|
return CreateProjectFolderResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
createdPath, _, err := createOnDisk(project.Slug, strings.TrimSpace(input.ParentFolderID), input.Name)
|
||||||
|
if err != nil {
|
||||||
|
return CreateProjectFolderResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := posixproj.NewProjector(service.db, service.posixRoot).Rebuild(ctx); err != nil {
|
||||||
|
return CreateProjectFolderResult{}, fmt.Errorf("rebuild POSIX projection: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
folders, err := service.getProjectHierarchyFoldersByRootPath(ctx, project.ID, rootPath)
|
||||||
|
if err != nil {
|
||||||
|
return CreateProjectFolderResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
createdFolder, ok := findProjectHierarchyFolder(folders, createdPath)
|
||||||
|
if !ok {
|
||||||
|
return CreateProjectFolderResult{}, fmt.Errorf("created project folder missing from projection")
|
||||||
|
}
|
||||||
|
|
||||||
|
return CreateProjectFolderResult{
|
||||||
|
ProjectID: project.ID,
|
||||||
|
CreatedFolder: createdFolder,
|
||||||
|
Folders: folders,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) deleteProjectHierarchyFolder(
|
||||||
|
ctx context.Context,
|
||||||
|
input DeleteProjectFolderInput,
|
||||||
|
rootPath func(projectSlug string) string,
|
||||||
|
deleteOnDisk func(projectSlug, folderID string) (string, error),
|
||||||
|
) (DeleteProjectFolderResult, error) {
|
||||||
|
project, err := service.loadProjectByID(ctx, strings.TrimSpace(input.ProjectID))
|
||||||
|
if err != nil {
|
||||||
|
return DeleteProjectFolderResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
deletedFolderID, err := deleteOnDisk(project.Slug, input.FolderID)
|
||||||
|
if err != nil {
|
||||||
|
return DeleteProjectFolderResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := posixproj.NewProjector(service.db, service.posixRoot).Rebuild(ctx); err != nil {
|
||||||
|
return DeleteProjectFolderResult{}, fmt.Errorf("rebuild POSIX projection: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
folders, err := service.getProjectHierarchyFoldersByRootPath(ctx, project.ID, rootPath)
|
||||||
|
if err != nil {
|
||||||
|
return DeleteProjectFolderResult{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, found := findProjectHierarchyFolder(folders, deletedFolderID); found {
|
||||||
|
return DeleteProjectFolderResult{}, fmt.Errorf("deleted project folder still present in projection")
|
||||||
|
}
|
||||||
|
|
||||||
|
return DeleteProjectFolderResult{
|
||||||
|
ProjectID: project.ID,
|
||||||
|
DeletedFolderID: deletedFolderID,
|
||||||
|
Folders: folders,
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
|
||||||
func (service *Service) listWorkspaces(ctx context.Context) ([]WorkspaceRecord, error) {
|
func (service *Service) listWorkspaces(ctx context.Context) ([]WorkspaceRecord, error) {
|
||||||
rows, err := service.db.Pool.Query(ctx, `
|
rows, err := service.db.Pool.Query(ctx, `
|
||||||
SELECT id::text, organization_id::text, name, slug, kind::text, department_id::text, team_id::text, project_id::text
|
SELECT id::text, organization_id::text, name, slug, kind::text, department_id::text, team_id::text, project_id::text
|
||||||
@@ -772,7 +1016,7 @@ func (service *Service) listWorkspaces(ctx context.Context) ([]WorkspaceRecord,
|
|||||||
|
|
||||||
func loadInstallation(ctx context.Context, tx pgx.Tx) (InstallationRecord, error) {
|
func loadInstallation(ctx context.Context, tx pgx.Tx) (InstallationRecord, error) {
|
||||||
return scanInstallationRecord(tx.QueryRow(ctx, `
|
return scanInstallationRecord(tx.QueryRow(ctx, `
|
||||||
SELECT id::text, mode::text, access::text, protocol::text, host, is_bootstrapped
|
SELECT id::text, name, mode::text, access::text, protocol::text, host, is_bootstrapped
|
||||||
FROM installations
|
FROM installations
|
||||||
WHERE singleton = TRUE
|
WHERE singleton = TRUE
|
||||||
LIMIT 1;
|
LIMIT 1;
|
||||||
@@ -799,7 +1043,7 @@ func updateBootstrappedInstallation(ctx context.Context, tx pgx.Tx) (Installatio
|
|||||||
UPDATE installations
|
UPDATE installations
|
||||||
SET is_bootstrapped = TRUE, bootstrapped_at = COALESCE(bootstrapped_at, NOW()), updated_at = NOW()
|
SET is_bootstrapped = TRUE, bootstrapped_at = COALESCE(bootstrapped_at, NOW()), updated_at = NOW()
|
||||||
WHERE singleton = TRUE
|
WHERE singleton = TRUE
|
||||||
RETURNING id::text, mode::text, access::text, protocol::text, host, is_bootstrapped;
|
RETURNING id::text, name, mode::text, access::text, protocol::text, host, is_bootstrapped;
|
||||||
`))
|
`))
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -830,10 +1074,15 @@ func upsertWorkspace(ctx context.Context, tx pgx.Tx, organizationID, name, slug,
|
|||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
|
|
||||||
func defaultRootOrganizationName(mode, host, adminDisplayName string) string {
|
func defaultRootOrganizationName(installationName, mode, host, adminDisplayName string) string {
|
||||||
|
trimmedInstallationName := strings.TrimSpace(installationName)
|
||||||
trimmedHost := strings.TrimSpace(host)
|
trimmedHost := strings.TrimSpace(host)
|
||||||
trimmedAdminDisplayName := strings.TrimSpace(adminDisplayName)
|
trimmedAdminDisplayName := strings.TrimSpace(adminDisplayName)
|
||||||
|
|
||||||
|
if trimmedInstallationName != "" {
|
||||||
|
return trimmedInstallationName
|
||||||
|
}
|
||||||
|
|
||||||
if strings.EqualFold(mode, defaultInstallationMode) {
|
if strings.EqualFold(mode, defaultInstallationMode) {
|
||||||
if trimmedAdminDisplayName != "" {
|
if trimmedAdminDisplayName != "" {
|
||||||
return fmt.Sprintf("%s %s", trimmedAdminDisplayName, defaultPersonalServerSuffix)
|
return fmt.Sprintf("%s %s", trimmedAdminDisplayName, defaultPersonalServerSuffix)
|
||||||
@@ -861,3 +1110,430 @@ 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 (service *Service) createProjectHierarchyFolderOnDisk(projectSlug, parentFolderID, name string) (string, string, error) {
|
||||||
|
return service.createProjectFolderOnDisk(projectSlug, parentFolderID, name, projectHierarchyRootPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) createProjectTreeFolderOnDisk(projectSlug, parentFolderID, name string) (string, string, error) {
|
||||||
|
return service.createProjectFolderOnDisk(projectSlug, parentFolderID, name, projectTreeRootPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) deleteProjectHierarchyFolderOnDisk(projectSlug, folderID string) (string, error) {
|
||||||
|
return service.deleteProjectFolderOnDisk(projectSlug, folderID, projectHierarchyRootPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) deleteProjectTreeFolderOnDisk(projectSlug, folderID string) (string, error) {
|
||||||
|
return service.deleteProjectFolderOnDisk(projectSlug, folderID, projectTreeRootPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) createProjectFolderOnDisk(
|
||||||
|
projectSlug, parentFolderID, name string,
|
||||||
|
rootPathBuilder func(projectSlug string) string,
|
||||||
|
) (string, string, error) {
|
||||||
|
posixRoot := strings.TrimSpace(service.posixRoot)
|
||||||
|
if posixRoot == "" {
|
||||||
|
return "", "", fmt.Errorf("POSIX root is not configured")
|
||||||
|
}
|
||||||
|
|
||||||
|
trimmedName := strings.TrimSpace(name)
|
||||||
|
if trimmedName == "" {
|
||||||
|
return "", "", fmt.Errorf("folder name is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
containerProjectionPath := rootPathBuilder(projectSlug)
|
||||||
|
parentDir := filepath.Join(posixRoot, filepath.FromSlash(containerProjectionPath))
|
||||||
|
|
||||||
|
if strings.TrimSpace(parentFolderID) != "" {
|
||||||
|
containerProjectionPath = filepath.ToSlash(filepath.Join(strings.TrimSpace(parentFolderID), "children"))
|
||||||
|
parentDir = filepath.Join(posixRoot, filepath.FromSlash(containerProjectionPath))
|
||||||
|
info, err := os.Stat(parentDir)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return "", "", ErrProjectFolderNotFound
|
||||||
|
}
|
||||||
|
return "", "", fmt.Errorf("stat parent project folder: %w", err)
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
return "", "", ErrProjectFolderNotFound
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.MkdirAll(parentDir, 0o755); err != nil {
|
||||||
|
return "", "", fmt.Errorf("create parent project folder path: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
baseSlug := normalizePOSIXSlug(trimmedName)
|
||||||
|
folderName := slugDir("folder", baseSlug)
|
||||||
|
folderDir := filepath.Join(parentDir, folderName)
|
||||||
|
folderSlug := baseSlug
|
||||||
|
|
||||||
|
for attempt := 2; ; attempt += 1 {
|
||||||
|
if _, err := os.Stat(folderDir); os.IsNotExist(err) {
|
||||||
|
break
|
||||||
|
} else if err != nil {
|
||||||
|
return "", "", fmt.Errorf("stat candidate project folder: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
folderSlug = fmt.Sprintf("%s-%d", baseSlug, attempt)
|
||||||
|
folderName = slugDir("folder", folderSlug)
|
||||||
|
folderDir = filepath.Join(parentDir, folderName)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.MkdirAll(filepath.Join(folderDir, "children"), 0o755); err != nil {
|
||||||
|
return "", "", fmt.Errorf("create project hierarchy folder: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeJSONFile(filepath.Join(folderDir, "folder.json"), map[string]any{
|
||||||
|
"name": trimmedName,
|
||||||
|
"slug": folderSlug,
|
||||||
|
"type": "folder",
|
||||||
|
}); err != nil {
|
||||||
|
return "", "", fmt.Errorf("write project folder.json: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := writeJSONFile(filepath.Join(folderDir, "acl.json"), map[string]any{
|
||||||
|
"version": 1,
|
||||||
|
"inherits": true,
|
||||||
|
"rules": []any{},
|
||||||
|
}); err != nil {
|
||||||
|
return "", "", fmt.Errorf("write project acl.json: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return filepath.ToSlash(filepath.Join(containerProjectionPath, folderName)), folderSlug, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (service *Service) deleteProjectFolderOnDisk(
|
||||||
|
projectSlug, folderID string,
|
||||||
|
rootPathBuilder func(projectSlug string) string,
|
||||||
|
) (string, error) {
|
||||||
|
posixRoot := strings.TrimSpace(service.posixRoot)
|
||||||
|
if posixRoot == "" {
|
||||||
|
return "", fmt.Errorf("POSIX root is not configured")
|
||||||
|
}
|
||||||
|
|
||||||
|
trimmedFolderID := strings.TrimSpace(folderID)
|
||||||
|
if trimmedFolderID == "" {
|
||||||
|
return "", ErrProjectFolderNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
rootProjectionPath := rootPathBuilder(projectSlug)
|
||||||
|
folderProjectionPath := strings.TrimPrefix(filepath.ToSlash(filepath.Clean("/"+trimmedFolderID)), "/")
|
||||||
|
if folderProjectionPath == "." || folderProjectionPath == rootProjectionPath || !strings.HasPrefix(folderProjectionPath, rootProjectionPath+"/") {
|
||||||
|
return "", ErrProjectFolderNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
folderDir := filepath.Join(posixRoot, filepath.FromSlash(folderProjectionPath))
|
||||||
|
info, err := os.Stat(folderDir)
|
||||||
|
if err != nil {
|
||||||
|
if os.IsNotExist(err) {
|
||||||
|
return "", ErrProjectFolderNotFound
|
||||||
|
}
|
||||||
|
return "", fmt.Errorf("stat project folder: %w", err)
|
||||||
|
}
|
||||||
|
if !info.IsDir() {
|
||||||
|
return "", ErrProjectFolderNotFound
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := os.RemoveAll(folderDir); err != nil {
|
||||||
|
return "", fmt.Errorf("delete project folder: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return folderProjectionPath, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildProjectHierarchyFolderTree(rows []projectHierarchyFolderRow, rootParentPath string) []ProjectHierarchyFolderRecord {
|
||||||
|
if len(rows) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
nodesByPath := make(map[string]*ProjectHierarchyFolderRecord, len(rows))
|
||||||
|
childrenByParent := make(map[string][]string)
|
||||||
|
|
||||||
|
for _, row := range rows {
|
||||||
|
label := strings.TrimSpace(row.Label)
|
||||||
|
if label == "" {
|
||||||
|
label = fallbackFolderLabel(row.Path)
|
||||||
|
}
|
||||||
|
nodesByPath[row.Path] = &ProjectHierarchyFolderRecord{
|
||||||
|
ID: row.Path,
|
||||||
|
Label: label,
|
||||||
|
Children: []ProjectHierarchyFolderRecord{},
|
||||||
|
}
|
||||||
|
childrenByParent[row.ParentPath] = append(childrenByParent[row.ParentPath], row.Path)
|
||||||
|
}
|
||||||
|
|
||||||
|
var build func(parentPath string) []ProjectHierarchyFolderRecord
|
||||||
|
build = func(parentPath string) []ProjectHierarchyFolderRecord {
|
||||||
|
childPaths := childrenByParent[parentPath]
|
||||||
|
if len(childPaths) == 0 {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
folders := make([]ProjectHierarchyFolderRecord, 0, len(childPaths))
|
||||||
|
for _, childPath := range childPaths {
|
||||||
|
node := nodesByPath[childPath]
|
||||||
|
if node == nil {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
folder := ProjectHierarchyFolderRecord{
|
||||||
|
ID: node.ID,
|
||||||
|
Label: node.Label,
|
||||||
|
Children: build(filepath.ToSlash(filepath.Join(childPath, "children"))),
|
||||||
|
}
|
||||||
|
folders = append(folders, folder)
|
||||||
|
}
|
||||||
|
|
||||||
|
return folders
|
||||||
|
}
|
||||||
|
|
||||||
|
return build(rootParentPath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func findProjectHierarchyFolder(folders []ProjectHierarchyFolderRecord, folderID string) (ProjectHierarchyFolderRecord, bool) {
|
||||||
|
for _, folder := range folders {
|
||||||
|
if folder.ID == folderID {
|
||||||
|
return folder, true
|
||||||
|
}
|
||||||
|
|
||||||
|
if child, ok := findProjectHierarchyFolder(folder.Children, folderID); ok {
|
||||||
|
return child, true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ProjectHierarchyFolderRecord{}, false
|
||||||
|
}
|
||||||
|
|
||||||
|
func projectHierarchyRootPath(projectSlug string) string {
|
||||||
|
return filepath.ToSlash(filepath.Join("projects", slugDir("project", projectSlug), "children"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func projectTreeRootPath(projectSlug string) string {
|
||||||
|
return filepath.ToSlash(filepath.Join("projects", slugDir("project", projectSlug), "tree"))
|
||||||
|
}
|
||||||
|
|
||||||
|
func normalizePOSIXSlug(value string) string {
|
||||||
|
trimmed := strings.TrimSpace(strings.ToLower(value))
|
||||||
|
if trimmed == "" {
|
||||||
|
return "untitled"
|
||||||
|
}
|
||||||
|
|
||||||
|
var builder strings.Builder
|
||||||
|
lastDash := false
|
||||||
|
for _, r := range trimmed {
|
||||||
|
switch {
|
||||||
|
case unicode.IsLetter(r) || unicode.IsDigit(r):
|
||||||
|
builder.WriteRune(r)
|
||||||
|
lastDash = false
|
||||||
|
case r == '-' || r == '_' || unicode.IsSpace(r):
|
||||||
|
if !lastDash && builder.Len() > 0 {
|
||||||
|
builder.WriteByte('-')
|
||||||
|
lastDash = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
slug := strings.Trim(builder.String(), "-")
|
||||||
|
if slug == "" {
|
||||||
|
return "untitled"
|
||||||
|
}
|
||||||
|
|
||||||
|
return slug
|
||||||
|
}
|
||||||
|
|
||||||
|
func fallbackFolderLabel(path string) string {
|
||||||
|
base := filepath.Base(filepath.FromSlash(path))
|
||||||
|
trimmed := strings.TrimPrefix(base, "folder-")
|
||||||
|
parts := strings.FieldsFunc(trimmed, func(r rune) bool { return r == '-' || r == '_' })
|
||||||
|
for index, part := range parts {
|
||||||
|
if part == "" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
parts[index] = strings.ToUpper(part[:1]) + part[1:]
|
||||||
|
}
|
||||||
|
label := strings.Join(parts, " ")
|
||||||
|
if label == "" {
|
||||||
|
return base
|
||||||
|
}
|
||||||
|
return label
|
||||||
|
}
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,247 @@
|
|||||||
|
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 TestCreateProjectHierarchyFolderOnDiskCreatesExpectedFolderShape(t *testing.T) {
|
||||||
|
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||||
|
service := NewService(nil, rootPath)
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
createdPath, createdSlug, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Design System")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("createProjectHierarchyFolderOnDisk root folder: %v", err)
|
||||||
|
}
|
||||||
|
if createdPath != "projects/project-primary-project/children/folder-design-system" {
|
||||||
|
t.Fatalf("unexpected created path: %s", createdPath)
|
||||||
|
}
|
||||||
|
if createdSlug != "design-system" {
|
||||||
|
t.Fatalf("unexpected created slug: %s", createdSlug)
|
||||||
|
}
|
||||||
|
|
||||||
|
createdFolderPath := filepath.Join(rootPath, "projects", "project-primary-project", "children", "folder-design-system")
|
||||||
|
for _, path := range []string{
|
||||||
|
filepath.Join(createdFolderPath, "folder.json"),
|
||||||
|
filepath.Join(createdFolderPath, "acl.json"),
|
||||||
|
filepath.Join(createdFolderPath, "children"),
|
||||||
|
} {
|
||||||
|
if _, err := os.Stat(path); err != nil {
|
||||||
|
t.Fatalf("expected path to exist %s: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(createdFolderPath, "folder.json"))
|
||||||
|
if folderPayload["name"] != "Design System" {
|
||||||
|
t.Fatalf("expected folder name Design System, got %#v", folderPayload["name"])
|
||||||
|
}
|
||||||
|
if folderPayload["slug"] != "design-system" {
|
||||||
|
t.Fatalf("expected folder slug design-system, got %#v", folderPayload["slug"])
|
||||||
|
}
|
||||||
|
|
||||||
|
nestedPath, nestedSlug, err := service.createProjectHierarchyFolderOnDisk("primary-project", createdPath, "Research")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("createProjectHierarchyFolderOnDisk nested folder: %v", err)
|
||||||
|
}
|
||||||
|
if nestedPath != "projects/project-primary-project/children/folder-design-system/children/folder-research" {
|
||||||
|
t.Fatalf("unexpected nested path: %s", nestedPath)
|
||||||
|
}
|
||||||
|
if nestedSlug != "research" {
|
||||||
|
t.Fatalf("unexpected nested slug: %s", nestedSlug)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCreateProjectTreeFolderOnDiskCreatesExpectedFolderShape(t *testing.T) {
|
||||||
|
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||||
|
service := NewService(nil, rootPath)
|
||||||
|
|
||||||
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
createdPath, createdSlug, err := service.createProjectTreeFolderOnDisk("primary-project", "", "Docs")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("createProjectTreeFolderOnDisk root folder: %v", err)
|
||||||
|
}
|
||||||
|
if createdPath != "projects/project-primary-project/tree/folder-docs" {
|
||||||
|
t.Fatalf("unexpected created path: %s", createdPath)
|
||||||
|
}
|
||||||
|
if createdSlug != "docs" {
|
||||||
|
t.Fatalf("unexpected created slug: %s", createdSlug)
|
||||||
|
}
|
||||||
|
|
||||||
|
createdFolderPath := filepath.Join(rootPath, "projects", "project-primary-project", "tree", "folder-docs")
|
||||||
|
for _, path := range []string{
|
||||||
|
filepath.Join(createdFolderPath, "folder.json"),
|
||||||
|
filepath.Join(createdFolderPath, "acl.json"),
|
||||||
|
filepath.Join(createdFolderPath, "children"),
|
||||||
|
} {
|
||||||
|
if _, err := os.Stat(path); err != nil {
|
||||||
|
t.Fatalf("expected path to exist %s: %v", path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nestedPath, nestedSlug, err := service.createProjectTreeFolderOnDisk("primary-project", createdPath, "Research")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("createProjectTreeFolderOnDisk nested folder: %v", err)
|
||||||
|
}
|
||||||
|
if nestedPath != "projects/project-primary-project/tree/folder-docs/children/folder-research" {
|
||||||
|
t.Fatalf("unexpected nested path: %s", nestedPath)
|
||||||
|
}
|
||||||
|
if nestedSlug != "research" {
|
||||||
|
t.Fatalf("unexpected nested slug: %s", nestedSlug)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildProjectHierarchyFolderTreeBuildsNestedStructure(t *testing.T) {
|
||||||
|
rows := []projectHierarchyFolderRow{
|
||||||
|
{Path: "projects/project-primary-project/children/folder-design", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Design"},
|
||||||
|
{Path: "projects/project-primary-project/children/folder-design/children/folder-research", ParentPath: "projects/project-primary-project/children/folder-design/children", Label: "Research"},
|
||||||
|
{Path: "projects/project-primary-project/children/folder-ops", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Ops"},
|
||||||
|
}
|
||||||
|
|
||||||
|
folders := buildProjectHierarchyFolderTree(rows, projectHierarchyRootPath("primary-project"))
|
||||||
|
if len(folders) != 2 {
|
||||||
|
t.Fatalf("expected 2 top-level folders, got %d", len(folders))
|
||||||
|
}
|
||||||
|
if folders[0].Label != "Design" || folders[1].Label != "Ops" {
|
||||||
|
t.Fatalf("unexpected top-level folder labels: %#v", folders)
|
||||||
|
}
|
||||||
|
if len(folders[0].Children) != 1 || folders[0].Children[0].Label != "Research" {
|
||||||
|
t.Fatalf("unexpected nested folder structure: %#v", folders[0].Children)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
}
|
||||||
@@ -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),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ type bootstrapInstanceStepRequest struct {
|
|||||||
|
|
||||||
type bootstrapModeStepRequest struct {
|
type bootstrapModeStepRequest struct {
|
||||||
Mode string `json:"mode"`
|
Mode string `json:"mode"`
|
||||||
|
Name string `json:"name"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type bootstrapAdminStepRequest struct {
|
type bootstrapAdminStepRequest struct {
|
||||||
@@ -166,6 +167,28 @@ func (routes apiRoutes) handleAppShellState(w http.ResponseWriter, r *http.Reque
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleDevelopmentBootstrapReset(w http.ResponseWriter, r *http.Request) {
|
||||||
|
if !routes.cfg.Config.IsDevelopment() {
|
||||||
|
WriteError(w, http.StatusNotFound, RequestIDFromContext(r.Context()), "not_found", "The requested endpoint does not exist.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := routes.bootstrapService().ResetDevelopmentState(r.Context()); err != nil {
|
||||||
|
routes.writeBootstrapPersistenceError(w, r, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"data": map[string]any{
|
||||||
|
"reset": true,
|
||||||
|
},
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "development-bootstrap-reset",
|
||||||
|
"developmentOnly": true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
func (routes apiRoutes) handleBootstrapInstanceStep(w http.ResponseWriter, r *http.Request) {
|
func (routes apiRoutes) handleBootstrapInstanceStep(w http.ResponseWriter, r *http.Request) {
|
||||||
payload, ok := decodeBootstrapRequest[bootstrapInstanceStepRequest](w, r)
|
payload, ok := decodeBootstrapRequest[bootstrapInstanceStepRequest](w, r)
|
||||||
if !ok {
|
if !ok {
|
||||||
@@ -212,13 +235,19 @@ func (routes apiRoutes) handleBootstrapModeStep(w http.ResponseWriter, r *http.R
|
|||||||
return
|
return
|
||||||
}
|
}
|
||||||
payload.Mode = strings.ToLower(strings.TrimSpace(payload.Mode))
|
payload.Mode = strings.ToLower(strings.TrimSpace(payload.Mode))
|
||||||
|
payload.Name = strings.TrimSpace(payload.Name)
|
||||||
|
|
||||||
if payload.Mode != "personal" && payload.Mode != "organizational" {
|
if payload.Mode != "personal" && payload.Mode != "organizational" {
|
||||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Mode must be either 'personal' or 'organizational'.")
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Mode must be either 'personal' or 'organizational'.")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
record, err := routes.bootstrapService().SaveMode(r.Context(), bootstrapservice.SaveModeInput{Mode: payload.Mode})
|
if payload.Name == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Name is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
record, err := routes.bootstrapService().SaveMode(r.Context(), bootstrapservice.SaveModeInput{Mode: payload.Mode, Name: payload.Name})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
routes.writeBootstrapPersistenceError(w, r, err)
|
routes.writeBootstrapPersistenceError(w, r, err)
|
||||||
return
|
return
|
||||||
@@ -312,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) {
|
||||||
@@ -334,7 +363,11 @@ func (routes apiRoutes) writeBootstrapPersistenceError(w http.ResponseWriter, r
|
|||||||
WriteError(w, http.StatusConflict, RequestIDFromContext(r.Context()), "bootstrap_prerequisite_missing", err.Error())
|
WriteError(w, http.StatusConflict, RequestIDFromContext(r.Context()), "bootstrap_prerequisite_missing", err.Error())
|
||||||
default:
|
default:
|
||||||
routes.cfg.Logger.Error("persist bootstrap step", "error", err, "path", r.URL.Path)
|
routes.cfg.Logger.Error("persist bootstrap step", "error", err, "path", r.URL.Path)
|
||||||
WriteError(w, http.StatusInternalServerError, RequestIDFromContext(r.Context()), "bootstrap_persist_failed", "Failed to persist bootstrap data.")
|
message := "Failed to persist bootstrap data."
|
||||||
|
if routes.cfg.Config.IsDevelopment() {
|
||||||
|
message = message + " " + err.Error()
|
||||||
|
}
|
||||||
|
WriteError(w, http.StatusInternalServerError, RequestIDFromContext(r.Context()), "bootstrap_persist_failed", message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,252 @@
|
|||||||
|
package httpx
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"net/http"
|
||||||
|
"strings"
|
||||||
|
|
||||||
|
bootstrapservice "moku-backend/internal/bootstrap"
|
||||||
|
|
||||||
|
"github.com/go-chi/chi/v5"
|
||||||
|
)
|
||||||
|
|
||||||
|
type createProjectFolderRequest struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
ParentFolderID string `json:"parentFolderId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type deleteProjectFolderRequest struct {
|
||||||
|
FolderID string `json:"folderId"`
|
||||||
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleProjectFolders(w http.ResponseWriter, r *http.Request) {
|
||||||
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
|
if projectID == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
folders, err := routes.bootstrapService().GetProjectHierarchyFolders(r.Context(), projectID)
|
||||||
|
if err != nil {
|
||||||
|
routes.writeProjectFolderError(w, r, err, "load")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"data": map[string]any{
|
||||||
|
"projectId": projectID,
|
||||||
|
"folders": folders,
|
||||||
|
},
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "project-folders",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleCreateProjectFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
|
if projectID == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, ok := decodeProjectFolderRequest(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload.Name = strings.TrimSpace(payload.Name)
|
||||||
|
payload.ParentFolderID = strings.TrimSpace(payload.ParentFolderID)
|
||||||
|
if payload.Name == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := routes.bootstrapService().CreateProjectFolder(r.Context(), bootstrapservice.CreateProjectFolderInput{
|
||||||
|
ProjectID: projectID,
|
||||||
|
ParentFolderID: payload.ParentFolderID,
|
||||||
|
Name: payload.Name,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
routes.writeProjectFolderError(w, r, err, "persist")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusCreated, map[string]any{
|
||||||
|
"data": result,
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "project-folder-create",
|
||||||
|
"persisted": true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleDeleteProjectFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
|
if projectID == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := decodeDeleteProjectFolderRequest(r)
|
||||||
|
if strings.TrimSpace(payload.FolderID) == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := routes.bootstrapService().DeleteProjectFolder(r.Context(), bootstrapservice.DeleteProjectFolderInput{
|
||||||
|
ProjectID: projectID,
|
||||||
|
FolderID: payload.FolderID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
routes.writeProjectFolderError(w, r, err, "delete")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"data": result,
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "project-folder-delete",
|
||||||
|
"persisted": true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleProjectTreeFolders(w http.ResponseWriter, r *http.Request) {
|
||||||
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
|
if projectID == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
folders, err := routes.bootstrapService().GetProjectTreeFolders(r.Context(), projectID)
|
||||||
|
if err != nil {
|
||||||
|
routes.writeProjectFolderError(w, r, err, "load")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"data": map[string]any{
|
||||||
|
"projectId": projectID,
|
||||||
|
"folders": folders,
|
||||||
|
},
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "project-tree-folders",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleCreateProjectTreeFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
|
if projectID == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload, ok := decodeProjectFolderRequest(w, r)
|
||||||
|
if !ok {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload.Name = strings.TrimSpace(payload.Name)
|
||||||
|
payload.ParentFolderID = strings.TrimSpace(payload.ParentFolderID)
|
||||||
|
if payload.Name == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := routes.bootstrapService().CreateProjectTreeFolder(r.Context(), bootstrapservice.CreateProjectFolderInput{
|
||||||
|
ProjectID: projectID,
|
||||||
|
ParentFolderID: payload.ParentFolderID,
|
||||||
|
Name: payload.Name,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
routes.writeProjectFolderError(w, r, err, "persist")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusCreated, map[string]any{
|
||||||
|
"data": result,
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "project-tree-folder-create",
|
||||||
|
"persisted": true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) handleDeleteProjectTreeFolder(w http.ResponseWriter, r *http.Request) {
|
||||||
|
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||||
|
if projectID == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := decodeDeleteProjectFolderRequest(r)
|
||||||
|
if strings.TrimSpace(payload.FolderID) == "" {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
result, err := routes.bootstrapService().DeleteProjectTreeFolder(r.Context(), bootstrapservice.DeleteProjectFolderInput{
|
||||||
|
ProjectID: projectID,
|
||||||
|
FolderID: payload.FolderID,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
routes.writeProjectFolderError(w, r, err, "delete")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteJSON(w, http.StatusOK, map[string]any{
|
||||||
|
"data": result,
|
||||||
|
"meta": map[string]any{
|
||||||
|
"resource": "project-tree-folder-delete",
|
||||||
|
"persisted": true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.Request, err error, operation string) {
|
||||||
|
switch {
|
||||||
|
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound):
|
||||||
|
WriteError(w, http.StatusNotFound, RequestIDFromContext(r.Context()), "not_found", err.Error())
|
||||||
|
default:
|
||||||
|
routes.cfg.Logger.Error(operation+" project folder", "error", err, "path", r.URL.Path)
|
||||||
|
message := "Failed to " + operation + " project folder."
|
||||||
|
if routes.cfg.Config.IsDevelopment() {
|
||||||
|
message = message + " " + err.Error()
|
||||||
|
}
|
||||||
|
WriteError(w, http.StatusInternalServerError, RequestIDFromContext(r.Context()), "project_folder_"+operation+"_failed", message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeDeleteProjectFolderRequest(r *http.Request) deleteProjectFolderRequest {
|
||||||
|
return deleteProjectFolderRequest{
|
||||||
|
FolderID: strings.TrimSpace(r.URL.Query().Get("folderId")),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodeProjectFolderRequest(w http.ResponseWriter, r *http.Request) (createProjectFolderRequest, bool) {
|
||||||
|
var payload createProjectFolderRequest
|
||||||
|
|
||||||
|
decoder := json.NewDecoder(r.Body)
|
||||||
|
decoder.DisallowUnknownFields()
|
||||||
|
|
||||||
|
if err := decoder.Decode(&payload); err != nil {
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body is required and must be valid JSON.")
|
||||||
|
return payload, false
|
||||||
|
}
|
||||||
|
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must be valid JSON.")
|
||||||
|
return payload, false
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||||
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must contain a single JSON object.")
|
||||||
|
return payload, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return payload, true
|
||||||
|
}
|
||||||
@@ -33,6 +33,18 @@ func (routes apiRoutes) Register(router chi.Router) {
|
|||||||
apiRouter.Get("/app-shell", routes.handleAppShellState)
|
apiRouter.Get("/app-shell", routes.handleAppShellState)
|
||||||
apiRouter.Get("/organizations", routes.handleOrganizations)
|
apiRouter.Get("/organizations", routes.handleOrganizations)
|
||||||
apiRouter.Get("/workspaces", routes.handleWorkspaces)
|
apiRouter.Get("/workspaces", routes.handleWorkspaces)
|
||||||
|
apiRouter.Route("/projects/{projectId}", func(projectRouter chi.Router) {
|
||||||
|
projectRouter.Get("/folders", routes.handleProjectFolders)
|
||||||
|
projectRouter.Post("/folders", routes.handleCreateProjectFolder)
|
||||||
|
projectRouter.Delete("/folders", routes.handleDeleteProjectFolder)
|
||||||
|
projectRouter.Get("/tree/folders", routes.handleProjectTreeFolders)
|
||||||
|
projectRouter.Post("/tree/folders", routes.handleCreateProjectTreeFolder)
|
||||||
|
projectRouter.Delete("/tree/folders", routes.handleDeleteProjectTreeFolder)
|
||||||
|
})
|
||||||
|
|
||||||
|
if routes.cfg.Config.IsDevelopment() {
|
||||||
|
apiRouter.Post("/dev/bootstrap/reset", routes.handleDevelopmentBootstrapReset)
|
||||||
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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 "hierarchy_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 "hierarchy_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,232 @@
|
|||||||
|
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", "children"))
|
||||||
|
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 != "hierarchy_folder" || treeFolder.ProjectSlug != "primary-project" {
|
||||||
|
t.Fatalf("unexpected tree folder node: %#v", treeFolder)
|
||||||
|
}
|
||||||
|
|
||||||
|
treeFolderACL := index["projects/project-primary-project/tree/folder-docs/folder.json"]
|
||||||
|
if treeFolderACL.LogicalType != "hierarchy_folder" || treeFolderACL.FileRole != "folder" {
|
||||||
|
t.Fatalf("unexpected tree folder file classification: %#v", treeFolderACL)
|
||||||
|
}
|
||||||
|
|
||||||
|
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,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 ./...
|
|
||||||
|
|||||||
@@ -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
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
mod backend
|
||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -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:
|
||||||
|
|||||||
@@ -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.
|
||||||
+114
-52
@@ -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)
|
||||||
|
|||||||
@@ -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
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,204 @@
|
|||||||
|
import { For, Show, createEffect, createMemo, createSignal, onMount, type JSX } from "solid-js";
|
||||||
|
import { Portal } from "solid-js/web";
|
||||||
|
import { ChevronRight, Plus } from "../../../lib/icons";
|
||||||
|
import {
|
||||||
|
getProjectContextMenuEyebrow,
|
||||||
|
getProjectContextMenuSections,
|
||||||
|
type ProjectContextMenuAction,
|
||||||
|
type ProjectMenuTarget,
|
||||||
|
type WorkspaceContextMenuShortcut,
|
||||||
|
} from "../data/shell.data";
|
||||||
|
import styles from "../WorkspaceContextMenu/WorkspaceContextMenu.module.scss";
|
||||||
|
|
||||||
|
type ShortcutPlatform = "mac" | "windows";
|
||||||
|
|
||||||
|
type NavigatorWithUserAgentData = Navigator & {
|
||||||
|
userAgentData?: {
|
||||||
|
platform?: string;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
type ProjectContextMenuPosition = {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ProjectContextMenuProps = {
|
||||||
|
target: ProjectMenuTarget | null;
|
||||||
|
position: ProjectContextMenuPosition | null;
|
||||||
|
onClose: VoidFunction;
|
||||||
|
onSelect: (action: ProjectContextMenuAction, target: ProjectMenuTarget) => void;
|
||||||
|
menuRef: (element: HTMLDivElement) => void;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getShortcutPlatform = (): ShortcutPlatform => {
|
||||||
|
if (typeof navigator === "undefined") {
|
||||||
|
return "mac";
|
||||||
|
}
|
||||||
|
|
||||||
|
const navigatorWithUserAgentData = navigator as NavigatorWithUserAgentData;
|
||||||
|
const platform =
|
||||||
|
typeof navigatorWithUserAgentData.userAgentData?.platform === "string"
|
||||||
|
? navigatorWithUserAgentData.userAgentData.platform
|
||||||
|
: navigator.platform;
|
||||||
|
|
||||||
|
return /mac|iphone|ipad|ipod/i.test(platform) ? "mac" : "windows";
|
||||||
|
};
|
||||||
|
|
||||||
|
const formatShortcut = (shortcut: WorkspaceContextMenuShortcut, platform: ShortcutPlatform): string => {
|
||||||
|
const keyLabel = (() => {
|
||||||
|
switch (shortcut.key) {
|
||||||
|
case "enter":
|
||||||
|
return platform === "mac" ? "↩" : "Enter";
|
||||||
|
case "delete":
|
||||||
|
return platform === "mac" ? "⌫" : "Del";
|
||||||
|
default:
|
||||||
|
return shortcut.key.toUpperCase();
|
||||||
|
}
|
||||||
|
})();
|
||||||
|
|
||||||
|
const modifierLabels =
|
||||||
|
shortcut.modifiers?.map((modifier) => {
|
||||||
|
switch (modifier) {
|
||||||
|
case "meta":
|
||||||
|
return platform === "mac" ? "⌘" : "Ctrl";
|
||||||
|
case "alt":
|
||||||
|
return platform === "mac" ? "⌥" : "Alt";
|
||||||
|
case "shift":
|
||||||
|
return platform === "mac" ? "⇧" : "Shift";
|
||||||
|
}
|
||||||
|
}) ?? [];
|
||||||
|
|
||||||
|
return platform === "mac" ? `${modifierLabels.join("")}${keyLabel}` : [...modifierLabels, keyLabel].join("+");
|
||||||
|
};
|
||||||
|
|
||||||
|
export const ProjectContextMenu = (props: ProjectContextMenuProps): JSX.Element => {
|
||||||
|
const [activeSubmenuActionId, setActiveSubmenuActionId] = createSignal<string | null>(null);
|
||||||
|
const [shortcutPlatform, setShortcutPlatform] = createSignal<ShortcutPlatform>("mac");
|
||||||
|
const sections = createMemo(() => (props.target ? getProjectContextMenuSections(props.target) : []));
|
||||||
|
const isCreateAction = (action: ProjectContextMenuAction): boolean => action.id.startsWith("new-");
|
||||||
|
const menuState = createMemo<{
|
||||||
|
target: ProjectMenuTarget;
|
||||||
|
position: ProjectContextMenuPosition;
|
||||||
|
} | null>(() => (props.target && props.position ? { target: props.target, position: props.position } : null));
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
setShortcutPlatform(getShortcutPlatform());
|
||||||
|
});
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
void props.target;
|
||||||
|
setActiveSubmenuActionId(null);
|
||||||
|
});
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Show when={menuState()}>
|
||||||
|
{(resolvedMenuState): JSX.Element => {
|
||||||
|
const target = resolvedMenuState().target;
|
||||||
|
const position = resolvedMenuState().position;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Portal>
|
||||||
|
<div
|
||||||
|
ref={props.menuRef}
|
||||||
|
class={styles.menu}
|
||||||
|
role="menu"
|
||||||
|
aria-label={`${target.label} project context menu`}
|
||||||
|
style={{ left: `${position.x}px`, top: `${position.y}px` }}
|
||||||
|
>
|
||||||
|
<Show when={target.kind !== "surface"}>
|
||||||
|
<header class={styles.header}>
|
||||||
|
<span class={styles.eyebrow}>{getProjectContextMenuEyebrow(target)}</span>
|
||||||
|
<strong class={styles.title}>{target.label}</strong>
|
||||||
|
</header>
|
||||||
|
</Show>
|
||||||
|
|
||||||
|
<div class={styles.sectionList}>
|
||||||
|
<For each={sections()}>
|
||||||
|
{(section): JSX.Element => (
|
||||||
|
<section class={styles.section}>
|
||||||
|
<Show when={section.label}>
|
||||||
|
<span class={styles.sectionLabel}>{section.label}</span>
|
||||||
|
</Show>
|
||||||
|
<div class={styles.actionList}>
|
||||||
|
<For each={section.items}>
|
||||||
|
{(action): JSX.Element => {
|
||||||
|
const isSubmenuOpen = () => activeSubmenuActionId() === action.id;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div class={styles.actionItem} onMouseEnter={() => setActiveSubmenuActionId(action.children ? action.id : null)}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
classList={{
|
||||||
|
[styles.action]: true,
|
||||||
|
[styles.actionCreate]: isCreateAction(action),
|
||||||
|
[styles.actionDanger]: action.tone === "danger",
|
||||||
|
[styles.actionSubmenuOpen]: isSubmenuOpen(),
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
if (action.children) {
|
||||||
|
setActiveSubmenuActionId(isSubmenuOpen() ? null : action.id);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
props.onSelect(action, target);
|
||||||
|
props.onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<Show when={isCreateAction(action)}>
|
||||||
|
<span class={styles.actionCreateIcon} aria-hidden="true">
|
||||||
|
<Plus size={14} strokeWidth={2.25} />
|
||||||
|
</span>
|
||||||
|
</Show>
|
||||||
|
<span class={styles.actionLabel}>{action.label}</span>
|
||||||
|
<div class={styles.actionMeta}>
|
||||||
|
<Show when={action.shortcut}>
|
||||||
|
<span class={styles.actionShortcut}>{formatShortcut(action.shortcut!, shortcutPlatform())}</span>
|
||||||
|
</Show>
|
||||||
|
<Show when={action.children}>
|
||||||
|
<ChevronRight class={styles.actionChevron} size={16} strokeWidth={2} />
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
|
||||||
|
<Show when={action.children && isSubmenuOpen()}>
|
||||||
|
<div class={styles.submenu} role="menu" aria-label={`${action.label} submenu`}>
|
||||||
|
<div class={styles.submenuList}>
|
||||||
|
<For each={action.children ?? []}>
|
||||||
|
{(childAction): JSX.Element => (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
role="menuitem"
|
||||||
|
classList={{
|
||||||
|
[styles.action]: true,
|
||||||
|
[styles.actionDanger]: childAction.tone === "danger",
|
||||||
|
}}
|
||||||
|
onClick={() => {
|
||||||
|
props.onSelect(childAction, target);
|
||||||
|
props.onClose();
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
<span class={styles.actionLabel}>{childAction.label}</span>
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</For>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
</For>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</For>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Portal>
|
||||||
|
);
|
||||||
|
}}
|
||||||
|
</Show>
|
||||||
|
);
|
||||||
|
};
|
||||||
+120
@@ -0,0 +1,120 @@
|
|||||||
|
import { createEffect, createSignal, onCleanup } from "solid-js";
|
||||||
|
import type { ProjectMenuTarget } from "../data/shell.data";
|
||||||
|
|
||||||
|
type ProjectContextMenuState = {
|
||||||
|
target: ProjectMenuTarget;
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
const readRootPixelToken = (name: string, fallback: number): number => {
|
||||||
|
if (typeof window === "undefined") {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
const value = window.getComputedStyle(document.documentElement).getPropertyValue(name).trim();
|
||||||
|
const parsed = Number.parseFloat(value);
|
||||||
|
|
||||||
|
if (!Number.isFinite(parsed)) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (value.endsWith("px")) {
|
||||||
|
return parsed;
|
||||||
|
}
|
||||||
|
|
||||||
|
return parsed * 16;
|
||||||
|
};
|
||||||
|
|
||||||
|
const clampMenuPosition = (value: number, min: number, max: number): number => {
|
||||||
|
if (max <= min) {
|
||||||
|
return min;
|
||||||
|
}
|
||||||
|
|
||||||
|
return Math.min(Math.max(value, min), max);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const createProjectContextMenuController = () => {
|
||||||
|
const [menuState, setMenuState] = createSignal<ProjectContextMenuState | null>(null);
|
||||||
|
let menuRef: HTMLDivElement | undefined;
|
||||||
|
|
||||||
|
const closeMenu = (): void => {
|
||||||
|
setMenuState(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const repositionMenu = (): void => {
|
||||||
|
if (typeof window === "undefined" || !menuRef) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const current = menuState();
|
||||||
|
|
||||||
|
if (!current) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const viewportPadding = readRootPixelToken("--space-4", 16);
|
||||||
|
const rect = menuRef.getBoundingClientRect();
|
||||||
|
const nextX = clampMenuPosition(current.x, viewportPadding, window.innerWidth - rect.width - viewportPadding);
|
||||||
|
const nextY = clampMenuPosition(current.y, viewportPadding, window.innerHeight - rect.height - viewportPadding);
|
||||||
|
|
||||||
|
if (nextX === current.x && nextY === current.y) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setMenuState({ ...current, x: nextX, y: nextY });
|
||||||
|
};
|
||||||
|
|
||||||
|
const openMenu = (event: MouseEvent, target: ProjectMenuTarget): void => {
|
||||||
|
event.preventDefault();
|
||||||
|
setMenuState({ target, x: event.clientX, y: event.clientY });
|
||||||
|
};
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
if (!menuState() || typeof window === "undefined") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const frame = window.requestAnimationFrame(() => {
|
||||||
|
repositionMenu();
|
||||||
|
});
|
||||||
|
|
||||||
|
const handlePointerDown = (event: PointerEvent): void => {
|
||||||
|
if (!menuRef?.contains(event.target as Node)) {
|
||||||
|
closeMenu();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleKeyDown = (event: KeyboardEvent): void => {
|
||||||
|
if (event.key === "Escape") {
|
||||||
|
closeMenu();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleViewportChange = (): void => {
|
||||||
|
closeMenu();
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("pointerdown", handlePointerDown);
|
||||||
|
window.addEventListener("resize", handleViewportChange);
|
||||||
|
window.addEventListener("scroll", handleViewportChange, true);
|
||||||
|
window.addEventListener("keydown", handleKeyDown);
|
||||||
|
|
||||||
|
onCleanup(() => {
|
||||||
|
window.cancelAnimationFrame(frame);
|
||||||
|
document.removeEventListener("pointerdown", handlePointerDown);
|
||||||
|
window.removeEventListener("resize", handleViewportChange);
|
||||||
|
window.removeEventListener("scroll", handleViewportChange, true);
|
||||||
|
window.removeEventListener("keydown", handleKeyDown);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
menuState,
|
||||||
|
openMenu,
|
||||||
|
closeMenu,
|
||||||
|
setMenuRef: (element: HTMLDivElement): void => {
|
||||||
|
menuRef = element;
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
@use "../shared/tree-nav" as treeNav;
|
||||||
|
|
||||||
.root {
|
.root {
|
||||||
display: grid;
|
display: grid;
|
||||||
--project-drawer-gap: var(--space-3);
|
--project-drawer-gap: var(--space-3);
|
||||||
@@ -9,6 +11,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;
|
||||||
@@ -38,9 +49,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.triggerOpen {
|
.triggerOpen {
|
||||||
border-color: color-mix(in srgb, var(--color-border-strong) 22%, transparent);
|
border-color: color-mix(in srgb, var(--color-accent-strong) 22%, var(--color-border-strong));
|
||||||
background: color-mix(in srgb, var(--color-surface) 92%, transparent);
|
background: color-mix(in srgb, var(--color-accent-soft) 26%, var(--color-surface));
|
||||||
box-shadow: var(--shadow-soft);
|
box-shadow: 0 10px 28px color-mix(in srgb, black 8%, transparent);
|
||||||
}
|
}
|
||||||
|
|
||||||
.triggerCompact {
|
.triggerCompact {
|
||||||
@@ -83,19 +94,14 @@
|
|||||||
gap: 0.12rem;
|
gap: 0.12rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.eyebrow,
|
.eyebrow {
|
||||||
.projectItemDescription {
|
|
||||||
@include text-caption;
|
@include text-caption;
|
||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
|
||||||
|
|
||||||
.eyebrow {
|
|
||||||
text-transform: uppercase;
|
text-transform: uppercase;
|
||||||
letter-spacing: 0.08em;
|
letter-spacing: 0.08em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.value,
|
.value {
|
||||||
.projectItemName {
|
|
||||||
@include text-label;
|
@include text-label;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -175,7 +181,7 @@
|
|||||||
min-height: 0;
|
min-height: 0;
|
||||||
display: grid;
|
display: grid;
|
||||||
align-content: start;
|
align-content: start;
|
||||||
gap: var(--space-3);
|
gap: var(--space-2);
|
||||||
padding: var(--space-4);
|
padding: var(--space-4);
|
||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
overscroll-behavior: contain;
|
overscroll-behavior: contain;
|
||||||
@@ -186,49 +192,132 @@
|
|||||||
width: 0;
|
width: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.projectList {
|
.treeSectionLabel {
|
||||||
list-style: none;
|
@include treeNav.section-label;
|
||||||
display: grid;
|
margin: 0;
|
||||||
gap: 0.2rem;
|
padding: 0 var(--space-3);
|
||||||
padding: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.projectItem {
|
.treeSectionHeader {
|
||||||
width: 100%;
|
display: flex;
|
||||||
min-width: 0;
|
align-items: center;
|
||||||
min-height: calc(var(--control-size-md) + var(--space-2));
|
justify-content: space-between;
|
||||||
padding: var(--space-2) var(--space-3);
|
gap: var(--space-2);
|
||||||
border: 1px solid transparent;
|
margin-bottom: var(--space-2);
|
||||||
border-radius: var(--radius-sm);
|
padding-right: var(--space-1);
|
||||||
background: transparent;
|
|
||||||
color: var(--color-text-muted);
|
|
||||||
transition:
|
|
||||||
background 160ms var(--easing-standard),
|
|
||||||
color 160ms var(--easing-standard),
|
|
||||||
border-color 160ms var(--easing-standard),
|
|
||||||
transform 180ms var(--easing-standard);
|
|
||||||
text-align: left;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.projectItem:hover {
|
.treeControls {
|
||||||
background: color-mix(in srgb, var(--color-surface-hover) 82%, transparent);
|
display: inline-flex;
|
||||||
color: var(--color-text);
|
align-items: center;
|
||||||
border-color: color-mix(in srgb, var(--color-border) 22%, transparent);
|
gap: var(--space-1);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
justify-content: flex-end;
|
||||||
}
|
}
|
||||||
|
|
||||||
.projectItemActive {
|
.treeControlButton {
|
||||||
border-color: color-mix(in srgb, var(--color-border) 28%, transparent);
|
display: inline-flex;
|
||||||
background: color-mix(in srgb, var(--color-surface) 82%, transparent);
|
align-items: center;
|
||||||
color: var(--color-text);
|
justify-content: center;
|
||||||
box-shadow: none;
|
width: calc(var(--control-size-md) - var(--space-1));
|
||||||
|
height: calc(var(--control-size-md) - var(--space-1));
|
||||||
|
@include text-caption;
|
||||||
|
padding: 0;
|
||||||
|
border: 1px solid color-mix(in srgb, var(--color-border) 46%, transparent);
|
||||||
|
border-radius: var(--radius-pill);
|
||||||
|
background: color-mix(in srgb, var(--color-surface) 95%, transparent);
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
transition:
|
||||||
|
border-color 160ms var(--easing-standard),
|
||||||
|
background 160ms var(--easing-standard),
|
||||||
|
color 160ms var(--easing-standard);
|
||||||
}
|
}
|
||||||
|
|
||||||
.projectItemCopy {
|
.treeControlButton:hover,
|
||||||
min-width: 0;
|
.treeControlButton:focus-visible {
|
||||||
display: grid;
|
border-color: color-mix(in srgb, var(--color-border-strong) 56%, transparent);
|
||||||
gap: 0.05rem;
|
background: var(--color-surface-hover);
|
||||||
|
color: var(--color-text);
|
||||||
|
outline: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.projectItemDescription {
|
.treeControlButton:disabled {
|
||||||
color: color-mix(in srgb, var(--color-text-muted) 84%, transparent);
|
opacity: 0.45;
|
||||||
|
cursor: default;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeList {
|
||||||
|
@include treeNav.tree-list;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeEmptySlot {
|
||||||
|
@include treeNav.empty-slot;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeInputRow {
|
||||||
|
@include treeNav.input-row;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeInput {
|
||||||
|
@include treeNav.input;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItem {
|
||||||
|
@include treeNav.item;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItem:hover,
|
||||||
|
.treeItem:focus-visible {
|
||||||
|
@include treeNav.item-hover;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemFolder {
|
||||||
|
@include treeNav.item-folder;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemDragging {
|
||||||
|
@include treeNav.item-dragging;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemDropBefore {
|
||||||
|
@include treeNav.item-drop-before;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemDropAfter {
|
||||||
|
@include treeNav.item-drop-after;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemDropInside {
|
||||||
|
@include treeNav.item-drop-inside;
|
||||||
|
}
|
||||||
|
|
||||||
|
.folderChevron {
|
||||||
|
@include treeNav.folder-chevron;
|
||||||
|
}
|
||||||
|
|
||||||
|
.folderChevronOpen {
|
||||||
|
@include treeNav.folder-chevron-open;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemActive {
|
||||||
|
@include treeNav.item-active;
|
||||||
|
}
|
||||||
|
|
||||||
|
.icon {
|
||||||
|
@include treeNav.icon;
|
||||||
|
}
|
||||||
|
|
||||||
|
.label {
|
||||||
|
@include treeNav.label;
|
||||||
|
}
|
||||||
|
|
||||||
|
.itemMeta {
|
||||||
|
@include treeNav.item-meta;
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (max-width: 720px) {
|
||||||
|
.rootCompact .scrim,
|
||||||
|
.rootCompact .drawer {
|
||||||
|
width: min(18rem, calc(100vw - 5rem));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,29 @@
|
|||||||
// Path: Frontend/src/components/shell/ProjectSelector/ProjectSelector.tsx
|
// Path: Frontend/src/components/shell/ProjectSelector/ProjectSelector.tsx
|
||||||
|
|
||||||
import { For, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
||||||
import { ChevronDown, Folder } from "../../../lib/icons";
|
import { ChevronDown, ChevronRight, Folder, LayoutGrid, ListCollapse, UnfoldVertical } from "../../../lib/icons";
|
||||||
|
import { ProjectContextMenu } from "../ProjectContextMenu/ProjectContextMenu";
|
||||||
import { useAppShellData } from "../data/app-shell.context";
|
import { useAppShellData } from "../data/app-shell.context";
|
||||||
|
import { resolveAPIBase } from "../../../lib/api";
|
||||||
|
import {
|
||||||
|
collectBranchNodeIds,
|
||||||
|
findTreeNodeDepth,
|
||||||
|
findTreeNodeLocation,
|
||||||
|
getPointerRelativeY,
|
||||||
|
isUuidString,
|
||||||
|
moveTreeNode,
|
||||||
|
resolveTreeDropTarget,
|
||||||
|
type NavTreeAdapter,
|
||||||
|
type NavTreeDropTarget,
|
||||||
|
} from "../shared/navTreeDnd";
|
||||||
|
import {
|
||||||
|
createProjectFolderTarget,
|
||||||
|
createProjectSurfaceTarget,
|
||||||
|
createProjectTarget,
|
||||||
|
type ProjectItem,
|
||||||
|
type ProjectMenuTarget,
|
||||||
|
} from "../data/shell.data";
|
||||||
|
import { createProjectContextMenuController } from "../ProjectContextMenu/createProjectContextMenuController";
|
||||||
import styles from "./ProjectSelector.module.scss";
|
import styles from "./ProjectSelector.module.scss";
|
||||||
|
|
||||||
type ProjectSelectorProps = {
|
type ProjectSelectorProps = {
|
||||||
@@ -12,41 +33,552 @@ 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 PersistedProjectFolderRecord = {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
children: PersistedProjectFolderRecord[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type ProjectFoldersResponse = {
|
||||||
|
data?: {
|
||||||
|
folders?: PersistedProjectFolderRecord[];
|
||||||
|
};
|
||||||
|
error?: string;
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type PendingProjectFolderDraft = {
|
||||||
|
parentId: string | null;
|
||||||
|
depth: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type ProjectDragTarget = NavTreeDropTarget;
|
||||||
|
|
||||||
|
type ProjectDragState = {
|
||||||
|
draggedNodeId: string;
|
||||||
|
dropTarget: ProjectDragTarget | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LONG_PRESS_MS = 320;
|
||||||
|
|
||||||
|
const getProjectTreeNodeId = (node: ProjectTreeNode): string =>
|
||||||
|
node.kind === "folder" ? node.id : node.item.id;
|
||||||
|
|
||||||
|
const buildPersistedFolderNodes = (folders: readonly PersistedProjectFolderRecord[] = []): ProjectTreeNode[] =>
|
||||||
|
folders.map((folder) => ({
|
||||||
|
kind: "folder",
|
||||||
|
id: folder.id,
|
||||||
|
label: folder.label,
|
||||||
|
children: buildPersistedFolderNodes(folder.children ?? []),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const buildProjectTree = (
|
||||||
|
items: readonly ProjectItem[],
|
||||||
|
folders: readonly PersistedProjectFolderRecord[] = [],
|
||||||
|
): ProjectTreeNode[] => [
|
||||||
|
...items.map((item) => ({
|
||||||
|
kind: "project" as const,
|
||||||
|
item,
|
||||||
|
})),
|
||||||
|
...buildPersistedFolderNodes(folders),
|
||||||
|
];
|
||||||
|
|
||||||
|
const readPersistedFolders = (body: ProjectFoldersResponse): PersistedProjectFolderRecord[] =>
|
||||||
|
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
||||||
|
|
||||||
|
const projectTreeAdapter: NavTreeAdapter<ProjectTreeNode> = {
|
||||||
|
getNodeId: getProjectTreeNodeId,
|
||||||
|
isBranchNode: (node) => node.kind === "folder",
|
||||||
|
getChildren: (node) => (node.kind === "folder" ? node.children : []),
|
||||||
|
withChildren: (node, children) =>
|
||||||
|
node.kind === "folder"
|
||||||
|
? {
|
||||||
|
...node,
|
||||||
|
children: [...children],
|
||||||
|
}
|
||||||
|
: node,
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
isTreeClickSuppressed: () => boolean;
|
||||||
|
}): 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 || props.isTreeClickSuppressed()) {
|
||||||
|
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) > 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}
|
||||||
|
isTreeClickSuppressed={props.isTreeClickSuppressed}
|
||||||
|
/>
|
||||||
|
</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 || props.isTreeClickSuppressed()) {
|
||||||
|
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 [persistedFolders, setPersistedFolders] = createSignal<readonly PersistedProjectFolderRecord[]>([]);
|
||||||
|
const [projectTreeNodes, setProjectTreeNodes] = createSignal<ProjectTreeNode[]>(
|
||||||
|
buildProjectTree(appShellData.projectItems(), persistedFolders()),
|
||||||
|
);
|
||||||
|
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 triggerRef: HTMLButtonElement | undefined;
|
let triggerRef: HTMLButtonElement | undefined;
|
||||||
|
let contextMenuRef: HTMLDivElement | undefined;
|
||||||
|
let longPressTimer: number | undefined;
|
||||||
|
let suppressClickTimer: number | undefined;
|
||||||
|
let lastSelectedProjectId: string | null = null;
|
||||||
|
let latestPersistedFoldersRequest = 0;
|
||||||
|
const contextMenu = createProjectContextMenuController();
|
||||||
|
|
||||||
|
const clearLongPressTimer = (): void => {
|
||||||
|
if (longPressTimer !== undefined) {
|
||||||
|
window.clearTimeout(longPressTimer);
|
||||||
|
longPressTimer = undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const suppressTreeClickTemporarily = (): void => {
|
||||||
|
setSuppressNextTreeClick(true);
|
||||||
|
|
||||||
|
if (suppressClickTimer !== undefined) {
|
||||||
|
window.clearTimeout(suppressClickTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
suppressClickTimer = window.setTimeout(() => {
|
||||||
|
setSuppressNextTreeClick(false);
|
||||||
|
suppressClickTimer = undefined;
|
||||||
|
}, 80);
|
||||||
|
};
|
||||||
|
|
||||||
|
const isFolderCollapsed = (folderId: string): boolean => collapsedFolderIds().includes(folderId);
|
||||||
|
|
||||||
|
const toggleFolder = (folderId: string): void => {
|
||||||
|
setCollapsedFolderIds((current) =>
|
||||||
|
current.includes(folderId) ? current.filter((id) => id !== folderId) : [...current, folderId],
|
||||||
|
);
|
||||||
|
};
|
||||||
|
|
||||||
|
const syncProjectTree = (): void => {
|
||||||
|
const nextTree = buildProjectTree(appShellData.projectItems(), persistedFolders());
|
||||||
|
const availableFolderIds = new Set(collectBranchNodeIds(nextTree, projectTreeAdapter));
|
||||||
|
|
||||||
|
setProjectTreeNodes(nextTree);
|
||||||
|
setCollapsedFolderIds((current) => current.filter((folderId) => availableFolderIds.has(folderId)));
|
||||||
|
};
|
||||||
|
|
||||||
|
const resetProjectTreeInteractionState = (): void => {
|
||||||
|
setCollapsedFolderIds([]);
|
||||||
|
setPendingFolderDraft(null);
|
||||||
|
setPendingFolderName("");
|
||||||
|
setDragState(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const folderIds = (): string[] => collectBranchNodeIds(projectTreeNodes(), projectTreeAdapter);
|
||||||
|
|
||||||
|
const expandAllFolders = (): void => {
|
||||||
|
setCollapsedFolderIds([]);
|
||||||
|
};
|
||||||
|
|
||||||
|
const collapseAllFolders = (): void => {
|
||||||
|
setCollapsedFolderIds(folderIds());
|
||||||
|
};
|
||||||
|
|
||||||
|
const totalFolderCount = (): number => folderIds().length;
|
||||||
|
|
||||||
|
const areAllFoldersCollapsed = (): boolean => {
|
||||||
|
const folderCount = totalFolderCount();
|
||||||
|
|
||||||
|
return folderCount > 0 && collapsedFolderIds().length >= folderCount;
|
||||||
|
};
|
||||||
|
|
||||||
|
const toggleAllFolders = (): void => {
|
||||||
|
if (areAllFoldersCollapsed()) {
|
||||||
|
expandAllFolders();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
collapseAllFolders();
|
||||||
|
};
|
||||||
|
|
||||||
|
const loadPersistedFolders = async (projectId: string): Promise<void> => {
|
||||||
|
const requestId = latestPersistedFoldersRequest + 1;
|
||||||
|
latestPersistedFoldersRequest = requestId;
|
||||||
|
|
||||||
|
if (!projectId) {
|
||||||
|
setPersistedFolders([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isUuidString(projectId)) {
|
||||||
|
setPersistedFolders([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const body = (await response.json()) as ProjectFoldersResponse;
|
||||||
|
|
||||||
|
if (requestId !== latestPersistedFoldersRequest) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to load project folders.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedFolders(body));
|
||||||
|
} catch (error) {
|
||||||
|
if (requestId !== latestPersistedFoldersRequest) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error(error);
|
||||||
|
setPersistedFolders([]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
setSelectedProject(appShellData.activeProject());
|
setSelectedProject(appShellData.activeProject());
|
||||||
});
|
});
|
||||||
|
|
||||||
onMount(() => {
|
createEffect(() => {
|
||||||
if (!triggerRef) {
|
syncProjectTree();
|
||||||
|
});
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
const projectId = selectedProject().id;
|
||||||
|
|
||||||
|
if (lastSelectedProjectId === null) {
|
||||||
|
lastSelectedProjectId = projectId;
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const updateDrawerTop = (): void => {
|
if (projectId === lastSelectedProjectId) {
|
||||||
if (!triggerRef) {
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lastSelectedProjectId = projectId;
|
||||||
|
resetProjectTreeInteractionState();
|
||||||
|
});
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
const projectId = selectedProject().id;
|
||||||
|
void loadPersistedFolders(projectId);
|
||||||
|
});
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
if (triggerRef) {
|
||||||
|
const updateDrawerTop = (): void => {
|
||||||
|
if (!triggerRef) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setDrawerTop(triggerRef.offsetTop + triggerRef.offsetHeight + 8);
|
||||||
|
};
|
||||||
|
|
||||||
|
updateDrawerTop();
|
||||||
|
|
||||||
|
const observer = new ResizeObserver(() => {
|
||||||
|
updateDrawerTop();
|
||||||
|
});
|
||||||
|
|
||||||
|
observer.observe(triggerRef);
|
||||||
|
window.addEventListener("resize", updateDrawerTop);
|
||||||
|
|
||||||
|
onCleanup(() => {
|
||||||
|
observer.disconnect();
|
||||||
|
window.removeEventListener("resize", updateDrawerTop);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const handlePointerDown = (event: PointerEvent): void => {
|
||||||
|
if (!props.isOpen || !rootRef) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setDrawerTop(triggerRef.offsetTop + triggerRef.offsetHeight);
|
const target = event.target;
|
||||||
|
|
||||||
|
if (target instanceof Node && rootRef.contains(target)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (target instanceof Node && contextMenuRef?.contains(target)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
props.onClose();
|
||||||
};
|
};
|
||||||
|
|
||||||
updateDrawerTop();
|
const handlePointerUp = (): void => {
|
||||||
|
clearLongPressTimer();
|
||||||
|
|
||||||
const observer = new ResizeObserver(() => {
|
const nextDragState = dragState();
|
||||||
updateDrawerTop();
|
|
||||||
});
|
|
||||||
|
|
||||||
observer.observe(triggerRef);
|
if (!nextDragState?.dropTarget) {
|
||||||
window.addEventListener("resize", updateDrawerTop);
|
if (nextDragState) {
|
||||||
|
suppressTreeClickTemporarily();
|
||||||
|
}
|
||||||
|
setDragState(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
suppressTreeClickTemporarily();
|
||||||
|
setProjectTreeNodes((current) =>
|
||||||
|
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget, projectTreeAdapter),
|
||||||
|
);
|
||||||
|
setDragState(null);
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleEscape = (event: KeyboardEvent): void => {
|
||||||
|
if (event.key !== "Escape") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
clearLongPressTimer();
|
||||||
|
|
||||||
|
if (dragState()) {
|
||||||
|
setDragState(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!props.isOpen) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
props.onClose();
|
||||||
|
triggerRef?.focus();
|
||||||
|
};
|
||||||
|
|
||||||
|
document.addEventListener("pointerdown", handlePointerDown);
|
||||||
|
window.addEventListener("pointerup", handlePointerUp);
|
||||||
|
window.addEventListener("pointercancel", handlePointerUp);
|
||||||
|
window.addEventListener("keydown", handleEscape);
|
||||||
|
|
||||||
onCleanup(() => {
|
onCleanup(() => {
|
||||||
observer.disconnect();
|
clearLongPressTimer();
|
||||||
window.removeEventListener("resize", updateDrawerTop);
|
if (suppressClickTimer !== undefined) {
|
||||||
|
window.clearTimeout(suppressClickTimer);
|
||||||
|
}
|
||||||
|
document.removeEventListener("pointerdown", handlePointerDown);
|
||||||
|
window.removeEventListener("pointerup", handlePointerUp);
|
||||||
|
window.removeEventListener("pointercancel", handlePointerUp);
|
||||||
|
window.removeEventListener("keydown", handleEscape);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -60,27 +592,199 @@ 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 = findTreeNodeLocation(projectTreeNodes(), projectId, projectTreeAdapter);
|
||||||
|
|
||||||
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 beginFolderDraft = (parentId: string | null, depth: number): void => {
|
||||||
|
if (parentId) {
|
||||||
|
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
|
||||||
|
}
|
||||||
|
|
||||||
|
setPendingFolderName("");
|
||||||
|
setPendingFolderDraft({ parentId, depth });
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitPendingFolder = async (): Promise<void> => {
|
||||||
|
const name = pendingFolderName().trim();
|
||||||
|
const draft = pendingFolderDraft();
|
||||||
|
const projectId = selectedProject().id;
|
||||||
|
|
||||||
|
if (!draft) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
setPendingFolderDraft(null);
|
||||||
|
setPendingFolderName("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isUuidString(projectId)) {
|
||||||
|
cancelPendingFolder();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
name,
|
||||||
|
parentFolderId: draft.parentId,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as ProjectFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to create project folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedFolders(body));
|
||||||
|
setPendingFolderDraft(null);
|
||||||
|
setPendingFolderName("");
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deletePersistedFolder = async (folderId: string): Promise<void> => {
|
||||||
|
const projectId = selectedProject().id;
|
||||||
|
if (!folderId || !isUuidString(projectId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${resolveAPIBase()}/projects/${projectId}/folders?folderId=${encodeURIComponent(folderId)}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const body = (await response.json()) as ProjectFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to delete project folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedFolders(body));
|
||||||
|
setCollapsedFolderIds((current) => current.filter((id) => id !== folderId));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelPendingFolder = (): void => {
|
||||||
|
setPendingFolderDraft(null);
|
||||||
|
setPendingFolderName("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleContextActionSelect = (action: { id: string; label: string }, target: ProjectMenuTarget): void => {
|
||||||
|
switch (action.id) {
|
||||||
|
case "new-folder":
|
||||||
|
switch (target.kind) {
|
||||||
|
case "surface":
|
||||||
|
beginFolderDraft(null, 0);
|
||||||
|
return;
|
||||||
|
case "folder":
|
||||||
|
beginFolderDraft(target.id, (findTreeNodeDepth(projectTreeNodes(), target.id, projectTreeAdapter) ?? 0) + 1);
|
||||||
|
return;
|
||||||
|
case "project": {
|
||||||
|
const parentId = findTreeNodeLocation(projectTreeNodes(), target.id, projectTreeAdapter)?.parentId ?? null;
|
||||||
|
beginFolderDraft(parentId, parentId ? (findTreeNodeDepth(projectTreeNodes(), parentId, projectTreeAdapter) ?? 0) + 1 : 0);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
case "delete-folder":
|
||||||
|
if (target.kind === "folder") {
|
||||||
|
void deletePersistedFolder(target.id);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSurfaceContextMenu = (event: MouseEvent): void => {
|
||||||
|
event.stopPropagation();
|
||||||
|
contextMenu.openMenu(event, createProjectSurfaceTarget("Projects"));
|
||||||
|
};
|
||||||
|
|
||||||
|
const treeControlLabel = (): string =>
|
||||||
|
areAllFoldersCollapsed() ? "Expand all folders" : "Collapse all folders";
|
||||||
|
|
||||||
|
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 relativeY = getPointerRelativeY(event);
|
||||||
|
if (relativeY === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setDragState({
|
||||||
|
...nextDragState,
|
||||||
|
dropTarget: resolveTreeDropTarget({
|
||||||
|
parentId,
|
||||||
|
index,
|
||||||
|
node,
|
||||||
|
relativeY,
|
||||||
|
adapter: projectTreeAdapter,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
|
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`,
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{/* Project trigger */}
|
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
ref={triggerRef}
|
ref={triggerRef}
|
||||||
@@ -89,8 +793,9 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
[styles.triggerCompact]: !!props.compact,
|
[styles.triggerCompact]: !!props.compact,
|
||||||
[styles.triggerOpen]: props.isOpen,
|
[styles.triggerOpen]: props.isOpen,
|
||||||
}}
|
}}
|
||||||
aria-label={`Open left workspace sidebar menu for ${selectedProject().name}`}
|
aria-label={`Open project menu for ${selectedProject().name}`}
|
||||||
aria-expanded={props.isOpen}
|
aria-expanded={props.isOpen}
|
||||||
|
aria-haspopup="menu"
|
||||||
title={selectedProject().name}
|
title={selectedProject().name}
|
||||||
onClick={toggleOpen}
|
onClick={toggleOpen}
|
||||||
>
|
>
|
||||||
@@ -113,54 +818,96 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
/>
|
/>
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
{/* Outside-click scrim */}
|
<Show when={props.isOpen}>
|
||||||
<button
|
<>
|
||||||
type="button"
|
<button
|
||||||
classList={{
|
type="button"
|
||||||
[styles.scrim]: true,
|
classList={{
|
||||||
[styles.scrimOpen]: props.isOpen,
|
[styles.scrim]: true,
|
||||||
}}
|
[styles.scrimOpen]: props.isOpen,
|
||||||
aria-hidden={!props.isOpen}
|
}}
|
||||||
tabIndex={props.isOpen ? 0 : -1}
|
aria-hidden={!props.isOpen}
|
||||||
onClick={props.onClose}
|
tabIndex={props.isOpen ? 0 : -1}
|
||||||
/>
|
onClick={props.onClose}
|
||||||
|
/>
|
||||||
|
|
||||||
{/* Slide-out project list */}
|
<div
|
||||||
<div
|
classList={{
|
||||||
classList={{
|
[styles.drawer]: true,
|
||||||
[styles.drawer]: true,
|
[styles.drawerOpen]: props.isOpen,
|
||||||
[styles.drawerOpen]: props.isOpen,
|
}}
|
||||||
}}
|
aria-hidden={!props.isOpen}
|
||||||
aria-hidden={!props.isOpen}
|
onContextMenu={handleSurfaceContextMenu}
|
||||||
>
|
>
|
||||||
<div class={styles.drawerBody}>
|
<div class={styles.drawerBody}>
|
||||||
<ul class={styles.projectList} role="list">
|
<div class={styles.treeSectionHeader}>
|
||||||
<For each={appShellData.projectItems()}>
|
<Show when={!props.compact}>
|
||||||
{(item): JSX.Element => {
|
<div class={styles.treeSectionLabel}>Projects</div>
|
||||||
const isSelected = (): boolean => selectedProject().id === item.id;
|
</Show>
|
||||||
|
|
||||||
return (
|
<div class={styles.treeControls}>
|
||||||
<li>
|
<button
|
||||||
<button
|
type="button"
|
||||||
type="button"
|
class={styles.treeControlButton}
|
||||||
classList={{
|
onClick={toggleAllFolders}
|
||||||
[styles.projectItem]: true,
|
aria-label={treeControlLabel()}
|
||||||
[styles.projectItemActive]: isSelected(),
|
title={treeControlLabel()}
|
||||||
}}
|
disabled={totalFolderCount() === 0}
|
||||||
onClick={(): void => selectProject(item.id)}
|
>
|
||||||
|
<Show
|
||||||
|
when={areAllFoldersCollapsed()}
|
||||||
|
fallback={<ListCollapse size={16} strokeWidth={2} />}
|
||||||
>
|
>
|
||||||
<span class={styles.projectItemCopy}>
|
<UnfoldVertical size={16} strokeWidth={2} />
|
||||||
<span class={styles.projectItemName}>{item.name}</span>
|
</Show>
|
||||||
<span class={styles.projectItemDescription}>{item.description}</span>
|
</button>
|
||||||
</span>
|
</div>
|
||||||
</button>
|
</div>
|
||||||
</li>
|
|
||||||
);
|
<ProjectFolderBranch
|
||||||
}}
|
nodes={projectTreeNodes()}
|
||||||
</For>
|
depth={0}
|
||||||
</ul>
|
parentId={null}
|
||||||
</div>
|
selectedProjectId={selectedProject().id}
|
||||||
</div>
|
isFolderCollapsed={isFolderCollapsed}
|
||||||
|
onToggleFolder={toggleFolder}
|
||||||
|
onSelectProject={selectProject}
|
||||||
|
onOpenFolderMenu={(event, folder): void => {
|
||||||
|
event.stopPropagation();
|
||||||
|
contextMenu.openMenu(event, createProjectFolderTarget(folder.id, folder.label));
|
||||||
|
}}
|
||||||
|
onOpenProjectMenu={(event, item): void => {
|
||||||
|
event.stopPropagation();
|
||||||
|
contextMenu.openMenu(event, createProjectTarget(item));
|
||||||
|
}}
|
||||||
|
onNodePointerDown={handleNodePointerDown}
|
||||||
|
onNodePointerMove={handleNodePointerMove}
|
||||||
|
pendingFolderDraft={pendingFolderDraft()}
|
||||||
|
pendingFolderName={pendingFolderName()}
|
||||||
|
onPendingFolderNameChange={setPendingFolderName}
|
||||||
|
onSubmitPendingFolder={submitPendingFolder}
|
||||||
|
onCancelPendingFolder={cancelPendingFolder}
|
||||||
|
dragState={dragState()}
|
||||||
|
isTreeClickSuppressed={suppressNextTreeClick}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
</Show>
|
||||||
|
|
||||||
|
<ProjectContextMenu
|
||||||
|
target={contextMenu.menuState()?.target ?? null}
|
||||||
|
position={(() => {
|
||||||
|
const state = contextMenu.menuState();
|
||||||
|
return state ? { x: state.x, y: state.y } : null;
|
||||||
|
})()}
|
||||||
|
menuRef={(element) => {
|
||||||
|
contextMenuRef = element;
|
||||||
|
contextMenu.setMenuRef(element);
|
||||||
|
}}
|
||||||
|
onClose={contextMenu.closeMenu}
|
||||||
|
onSelect={handleContextActionSelect}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
@use "../shared/tree-nav" as treeNav;
|
||||||
|
|
||||||
.sidebar {
|
.sidebar {
|
||||||
--sidebar-nav-item-min-height: var(--control-size-lg);
|
--sidebar-nav-item-min-height: var(--control-size-lg);
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -12,6 +14,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);
|
||||||
@@ -108,19 +119,25 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.treeSectionLabel {
|
.treeSectionLabel {
|
||||||
@include text-caption;
|
@include treeNav.section-label;
|
||||||
margin: var(--space-3) 0 var(--space-2);
|
margin: var(--space-3) 0 var(--space-2);
|
||||||
padding: 0 var(--space-3);
|
padding: 0 var(--space-3);
|
||||||
color: var(--color-text-subtle);
|
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.04em;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeList {
|
.treeList {
|
||||||
list-style: none;
|
@include treeNav.tree-list;
|
||||||
display: grid;
|
}
|
||||||
gap: var(--space-1);
|
|
||||||
padding: 0;
|
.treeEmptySlot {
|
||||||
|
@include treeNav.empty-slot;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeInputRow {
|
||||||
|
@include treeNav.input-row;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeInput {
|
||||||
|
@include treeNav.input;
|
||||||
}
|
}
|
||||||
|
|
||||||
.navItem {
|
.navItem {
|
||||||
@@ -138,42 +155,44 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.treeItem {
|
.treeItem {
|
||||||
width: 100%;
|
@include treeNav.item;
|
||||||
min-width: 0;
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: auto minmax(0, 1fr) auto;
|
|
||||||
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 transparent;
|
|
||||||
border-radius: var(--radius-lg);
|
|
||||||
background: transparent;
|
|
||||||
color: var(--color-text-muted);
|
|
||||||
text-align: left;
|
|
||||||
transition:
|
|
||||||
background 160ms var(--easing-standard),
|
|
||||||
color 160ms var(--easing-standard),
|
|
||||||
border-color 160ms var(--easing-standard),
|
|
||||||
transform 180ms var(--easing-standard);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItem:hover,
|
.treeItem:hover,
|
||||||
.treeItem:focus-visible {
|
.treeItem:focus-visible {
|
||||||
background: var(--color-surface-hover);
|
@include treeNav.item-hover;
|
||||||
color: var(--color-text);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemFolder {
|
.treeItemFolder {
|
||||||
color: var(--color-text);
|
@include treeNav.item-folder;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemDragging {
|
||||||
|
@include treeNav.item-dragging;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemDropBefore {
|
||||||
|
@include treeNav.item-drop-before;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemDropAfter {
|
||||||
|
@include treeNav.item-drop-after;
|
||||||
|
}
|
||||||
|
|
||||||
|
.treeItemDropInside {
|
||||||
|
@include treeNav.item-drop-inside;
|
||||||
|
}
|
||||||
|
|
||||||
|
.folderChevron {
|
||||||
|
@include treeNav.folder-chevron;
|
||||||
|
}
|
||||||
|
|
||||||
|
.folderChevronOpen {
|
||||||
|
@include treeNav.folder-chevron-open;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemActive {
|
.treeItemActive {
|
||||||
border-color: var(--color-border);
|
@include treeNav.item-active;
|
||||||
background: var(--color-surface);
|
|
||||||
color: var(--color-text);
|
|
||||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.navItemActive {
|
.navItemActive {
|
||||||
@@ -184,18 +203,15 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.icon {
|
.icon {
|
||||||
color: inherit;
|
@include treeNav.icon;
|
||||||
opacity: 0.85;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.label {
|
.label {
|
||||||
@include text-label;
|
@include treeNav.label;
|
||||||
min-width: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.itemMeta {
|
.itemMeta {
|
||||||
@include text-caption;
|
@include treeNav.item-meta;
|
||||||
color: var(--color-text-muted);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.sidebarCollapsed {
|
.sidebarCollapsed {
|
||||||
|
|||||||
@@ -1,9 +1,20 @@
|
|||||||
// 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 { resolveAPIBase } from "../../../lib/api";
|
||||||
|
import { ChevronLeft, ChevronRight, Folder, ListCollapse, UnfoldVertical } 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 {
|
||||||
|
collectBranchNodeIds,
|
||||||
|
findTreeNodeDepth,
|
||||||
|
getPointerRelativeY,
|
||||||
|
isUuidString,
|
||||||
|
moveTreeNode,
|
||||||
|
resolveTreeDropTarget,
|
||||||
|
type NavTreeAdapter,
|
||||||
|
type NavTreeDropTarget,
|
||||||
|
} from "../shared/navTreeDnd";
|
||||||
import {
|
import {
|
||||||
createWorkspaceStaticTarget,
|
createWorkspaceStaticTarget,
|
||||||
createWorkspaceSurfaceTarget,
|
createWorkspaceSurfaceTarget,
|
||||||
@@ -26,6 +37,105 @@ type WorkspaceSidebarProps = {
|
|||||||
onToggleRailCollapse: () => void;
|
onToggleRailCollapse: () => void;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type PendingWorkspaceFolderDraft = {
|
||||||
|
parentId: string | null;
|
||||||
|
depth: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
type WorkspaceDragTarget = NavTreeDropTarget;
|
||||||
|
|
||||||
|
type WorkspaceDragState = {
|
||||||
|
draggedNodeId: string;
|
||||||
|
dropTarget: WorkspaceDragTarget | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
type PersistedWorkspaceFolderRecord = {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
children?: PersistedWorkspaceFolderRecord[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type WorkspaceFoldersResponse = {
|
||||||
|
data?: {
|
||||||
|
folders?: PersistedWorkspaceFolderRecord[];
|
||||||
|
};
|
||||||
|
error?: string;
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const LONG_PRESS_MS = 320;
|
||||||
|
|
||||||
|
const getWorkspaceTreeNodeId = (node: WorkspaceTreeNode): string => node.id;
|
||||||
|
|
||||||
|
const buildPersistedWorkspaceFolderNodes = (
|
||||||
|
folders: readonly PersistedWorkspaceFolderRecord[],
|
||||||
|
): WorkspaceTreeNode[] =>
|
||||||
|
folders.map((folder) => ({
|
||||||
|
id: folder.id,
|
||||||
|
label: folder.label,
|
||||||
|
kind: "folder",
|
||||||
|
icon: Folder,
|
||||||
|
children: buildPersistedWorkspaceFolderNodes(folder.children ?? []),
|
||||||
|
}));
|
||||||
|
|
||||||
|
const readPersistedWorkspaceFolders = (body: WorkspaceFoldersResponse): PersistedWorkspaceFolderRecord[] =>
|
||||||
|
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
||||||
|
|
||||||
|
const workspaceTreeAdapter: NavTreeAdapter<WorkspaceTreeNode> = {
|
||||||
|
getNodeId: getWorkspaceTreeNodeId,
|
||||||
|
isBranchNode: (node) => node.kind === "folder",
|
||||||
|
getChildren: (node) => (node.kind === "folder" ? (node.children ?? []) : []),
|
||||||
|
withChildren: (node, children) =>
|
||||||
|
node.kind === "folder"
|
||||||
|
? {
|
||||||
|
...node,
|
||||||
|
children: [...children],
|
||||||
|
}
|
||||||
|
: node,
|
||||||
|
};
|
||||||
|
|
||||||
|
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: {
|
||||||
@@ -75,18 +185,45 @@ 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;
|
||||||
|
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 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 +233,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 +247,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 +278,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,42 +295,403 @@ 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>
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||||
const appShellData = useAppShellData();
|
const appShellData = useAppShellData();
|
||||||
|
const activeProject = () => appShellData.activeProject();
|
||||||
const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false);
|
const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false);
|
||||||
|
const [workspaceTreeNodes, setWorkspaceTreeNodes] = createSignal<readonly WorkspaceTreeNode[]>(appShellData.workspaceTree());
|
||||||
|
const [persistedFolders, setPersistedFolders] = createSignal<readonly PersistedWorkspaceFolderRecord[]>([]);
|
||||||
|
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);
|
||||||
|
let lastSelectedProjectId: string | null = null;
|
||||||
|
let latestPersistedFoldersRequest = 0;
|
||||||
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 folderIds = (): string[] => collectBranchNodeIds(workspaceTreeNodes(), workspaceTreeAdapter);
|
||||||
const state = contextMenu.menuState();
|
const totalFolderCount = (): number => folderIds().length;
|
||||||
|
const areAllFoldersCollapsed = (): boolean => {
|
||||||
|
const count = totalFolderCount();
|
||||||
|
return count > 0 && collapsedFolderIds().length >= count;
|
||||||
|
};
|
||||||
|
const workspaceFolderToggleLabel = (): string =>
|
||||||
|
areAllFoldersCollapsed() ? "Expand all folders" : "Collapse all folders";
|
||||||
|
const toggleFolder = (folderId: string): void => {
|
||||||
|
setCollapsedFolderIds((current) =>
|
||||||
|
current.includes(folderId) ? current.filter((id) => id !== folderId) : [...current, folderId],
|
||||||
|
);
|
||||||
|
};
|
||||||
|
const expandAllFolders = (): void => {
|
||||||
|
setCollapsedFolderIds([]);
|
||||||
|
};
|
||||||
|
const collapseAllFolders = (): void => {
|
||||||
|
setCollapsedFolderIds(folderIds());
|
||||||
|
};
|
||||||
|
const toggleAllFolders = (): void => {
|
||||||
|
if (areAllFoldersCollapsed()) {
|
||||||
|
expandAllFolders();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
return state
|
collapseAllFolders();
|
||||||
? {
|
};
|
||||||
x: state.x,
|
const resetWorkspaceTreeInteractionState = (): void => {
|
||||||
y: state.y,
|
setCollapsedFolderIds([]);
|
||||||
|
setPendingFolderDraft(null);
|
||||||
|
setPendingFolderName("");
|
||||||
|
setDragState(null);
|
||||||
|
};
|
||||||
|
const syncWorkspaceTree = (): void => {
|
||||||
|
const nextTree = activeProject()?.id
|
||||||
|
? buildPersistedWorkspaceFolderNodes(persistedFolders())
|
||||||
|
: appShellData.workspaceTree();
|
||||||
|
const availableFolderIds = new Set(collectBranchNodeIds(nextTree, workspaceTreeAdapter));
|
||||||
|
|
||||||
|
setWorkspaceTreeNodes(nextTree);
|
||||||
|
setCollapsedFolderIds((current) => current.filter((id) => availableFolderIds.has(id)));
|
||||||
|
};
|
||||||
|
const loadPersistedFolders = async (projectId: string): Promise<void> => {
|
||||||
|
const requestId = latestPersistedFoldersRequest + 1;
|
||||||
|
latestPersistedFoldersRequest = requestId;
|
||||||
|
|
||||||
|
if (!projectId) {
|
||||||
|
setPersistedFolders([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isUuidString(projectId)) {
|
||||||
|
setPersistedFolders([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (requestId !== latestPersistedFoldersRequest) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
: null;
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to load project tree folders.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
|
} catch (error) {
|
||||||
|
if (requestId !== latestPersistedFoldersRequest) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error(error);
|
||||||
|
setPersistedFolders([]);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const clearLongPressTimer = (): void => {
|
||||||
|
if (longPressTimer !== undefined) {
|
||||||
|
window.clearTimeout(longPressTimer);
|
||||||
|
longPressTimer = undefined;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
const suppressTreeClickTemporarily = (): void => {
|
||||||
|
setSuppressNextTreeClick(true);
|
||||||
|
|
||||||
|
if (suppressClickTimer !== undefined) {
|
||||||
|
window.clearTimeout(suppressClickTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
suppressClickTimer = window.setTimeout(() => {
|
||||||
|
setSuppressNextTreeClick(false);
|
||||||
|
suppressClickTimer = undefined;
|
||||||
|
}, 80);
|
||||||
|
};
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
syncWorkspaceTree();
|
||||||
});
|
});
|
||||||
|
|
||||||
const handleContextActionSelect = (_action: WorkspaceContextMenuAction, _target: WorkspaceContextMenuTarget): void => {
|
createEffect(() => {
|
||||||
// Initial implementation only establishes the menu IA and placement.
|
const projectId = activeProject()?.id ?? null;
|
||||||
|
|
||||||
|
if (lastSelectedProjectId === null) {
|
||||||
|
lastSelectedProjectId = projectId;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (projectId === lastSelectedProjectId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lastSelectedProjectId = projectId;
|
||||||
|
resetWorkspaceTreeInteractionState();
|
||||||
|
});
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
void loadPersistedFolders(activeProject()?.id ?? "");
|
||||||
|
});
|
||||||
|
|
||||||
|
onMount(() => {
|
||||||
|
const handlePointerUp = (): void => {
|
||||||
|
clearLongPressTimer();
|
||||||
|
|
||||||
|
const nextDragState = dragState();
|
||||||
|
|
||||||
|
if (!nextDragState?.dropTarget) {
|
||||||
|
if (nextDragState) {
|
||||||
|
suppressTreeClickTemporarily();
|
||||||
|
}
|
||||||
|
setDragState(null);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
suppressTreeClickTemporarily();
|
||||||
|
setWorkspaceTreeNodes((current) =>
|
||||||
|
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter),
|
||||||
|
);
|
||||||
|
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 = async (): Promise<void> => {
|
||||||
|
const name = pendingFolderName().trim();
|
||||||
|
const draft = pendingFolderDraft();
|
||||||
|
const projectId = activeProject()?.id ?? "";
|
||||||
|
|
||||||
|
if (!draft) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!name) {
|
||||||
|
setPendingFolderDraft(null);
|
||||||
|
setPendingFolderName("");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!projectId || !isUuidString(projectId)) {
|
||||||
|
cancelPendingFolder();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
name,
|
||||||
|
parentFolderId: draft.parentId,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to create project tree folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
|
setPendingFolderDraft(null);
|
||||||
|
setPendingFolderName("");
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deletePersistedFolder = async (folderId: string): Promise<void> => {
|
||||||
|
const projectId = activeProject()?.id ?? "";
|
||||||
|
if (!folderId || !projectId || !isUuidString(projectId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${resolveAPIBase()}/projects/${projectId}/tree/folders?folderId=${encodeURIComponent(folderId)}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to delete project tree folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
|
setCollapsedFolderIds((current) => current.filter((id) => id !== folderId));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const cancelPendingFolder = (): void => {
|
||||||
|
setPendingFolderDraft(null);
|
||||||
|
setPendingFolderName("");
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleHeaderActionClick = (actionId: string): void => {
|
||||||
|
switch (actionId) {
|
||||||
|
case "toggle-workspace-folders":
|
||||||
|
toggleAllFolders();
|
||||||
|
return;
|
||||||
|
case "search-workspace":
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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 relativeY = getPointerRelativeY(event);
|
||||||
|
if (relativeY === null) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setDragState({
|
||||||
|
...nextDragState,
|
||||||
|
dropTarget: resolveTreeDropTarget({
|
||||||
|
parentId,
|
||||||
|
index,
|
||||||
|
node,
|
||||||
|
relativeY,
|
||||||
|
adapter: workspaceTreeAdapter,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleContextActionSelect = (action: WorkspaceContextMenuAction, target: WorkspaceContextMenuTarget): void => {
|
||||||
|
switch (action.id) {
|
||||||
|
case "new-folder":
|
||||||
|
switch (target.kind) {
|
||||||
|
case "workspace":
|
||||||
|
case "home":
|
||||||
|
beginFolderDraft(null, 0);
|
||||||
|
return;
|
||||||
|
case "folder":
|
||||||
|
beginFolderDraft(target.id, (findTreeNodeDepth(workspaceTreeNodes(), target.id, workspaceTreeAdapter) ?? 0) + 1);
|
||||||
|
return;
|
||||||
|
case "settings":
|
||||||
|
case "item":
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
case "delete-folder":
|
||||||
|
if (target.kind === "folder") {
|
||||||
|
void deletePersistedFolder(target.id);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -169,12 +700,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
|
||||||
@@ -200,12 +732,30 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
{props.railCollapsed ? <ChevronRight size={16} strokeWidth={2} /> : <ChevronLeft size={16} strokeWidth={2} />}
|
{props.railCollapsed ? <ChevronRight size={16} strokeWidth={2} /> : <ChevronLeft size={16} strokeWidth={2} />}
|
||||||
</button>
|
</button>
|
||||||
|
|
||||||
<For each={workspaceSidebarHeaderActions}>
|
<For each={workspaceSidebarHeaderActions}>
|
||||||
{(action): JSX.Element => {
|
{(action): JSX.Element => {
|
||||||
const Icon = action.icon;
|
const label =
|
||||||
|
action.id === "toggle-workspace-folders"
|
||||||
|
? workspaceFolderToggleLabel()
|
||||||
|
: action.label;
|
||||||
|
const Icon =
|
||||||
|
action.id === "toggle-workspace-folders"
|
||||||
|
? areAllFoldersCollapsed()
|
||||||
|
? UnfoldVertical
|
||||||
|
: ListCollapse
|
||||||
|
: action.icon;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button type="button" class={styles.headerActionButton} aria-label={action.label} title={action.label} data-slot="workspace-sidebar-header-action" data-action-id={action.id}>
|
<button
|
||||||
|
type="button"
|
||||||
|
class={styles.headerActionButton}
|
||||||
|
aria-label={label}
|
||||||
|
title={label}
|
||||||
|
data-slot="workspace-sidebar-header-action"
|
||||||
|
data-action-id={action.id}
|
||||||
|
disabled={action.id === "toggle-workspace-folders" && totalFolderCount() === 0}
|
||||||
|
onClick={(): void => handleHeaderActionClick(action.id)}
|
||||||
|
>
|
||||||
<Icon size={16} strokeWidth={2} />
|
<Icon size={16} strokeWidth={2} />
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
@@ -255,19 +805,39 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
</Show>
|
</Show>
|
||||||
|
|
||||||
<div data-slot="workspace-tree-root">
|
<div data-slot="workspace-tree-root">
|
||||||
<WorkspaceTreeBranch
|
<WorkspaceTreeBranch
|
||||||
nodes={appShellData.workspaceTree()}
|
nodes={workspaceTreeNodes()}
|
||||||
onOpenContextMenu={contextMenu.openMenu}
|
parentId={null}
|
||||||
onOpenContextMenuFromKeyboard={contextMenu.openMenuFromElement}
|
isFolderCollapsed={isFolderCollapsed}
|
||||||
/>
|
onToggleFolder={toggleFolder}
|
||||||
|
pendingFolderDraft={pendingFolderDraft()}
|
||||||
|
pendingFolderName={pendingFolderName()}
|
||||||
|
onPendingFolderNameChange={setPendingFolderName}
|
||||||
|
onSubmitPendingFolder={submitPendingFolder}
|
||||||
|
onCancelPendingFolder={cancelPendingFolder}
|
||||||
|
onOpenContextMenu={contextMenu.openMenu}
|
||||||
|
onOpenContextMenuFromKeyboard={contextMenu.openMenuFromElement}
|
||||||
|
onNodePointerDown={handleNodePointerDown}
|
||||||
|
onNodePointerMove={handleNodePointerMove}
|
||||||
|
dragState={dragState()}
|
||||||
|
isTreeClickSuppressed={suppressNextTreeClick}
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</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}
|
||||||
|
|||||||
@@ -34,6 +34,7 @@ import {
|
|||||||
|
|
||||||
type AppShellInstallation = {
|
type AppShellInstallation = {
|
||||||
id: string;
|
id: string;
|
||||||
|
name: string;
|
||||||
mode: "personal" | "organizational" | string;
|
mode: "personal" | "organizational" | string;
|
||||||
access: string;
|
access: string;
|
||||||
protocol: string;
|
protocol: string;
|
||||||
@@ -100,9 +101,20 @@ type AppShellPayload = {
|
|||||||
workspaces: AppShellWorkspace[];
|
workspaces: AppShellWorkspace[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const normalizeAppShellPayload = (payload: AppShellPayload | null | undefined): AppShellPayload => ({
|
||||||
|
installation: payload?.installation,
|
||||||
|
admin: payload?.admin,
|
||||||
|
organizations: Array.isArray(payload?.organizations) ? payload.organizations : [],
|
||||||
|
departments: Array.isArray(payload?.departments) ? payload.departments : [],
|
||||||
|
teams: Array.isArray(payload?.teams) ? payload.teams : [],
|
||||||
|
projects: Array.isArray(payload?.projects) ? payload.projects : [],
|
||||||
|
workspaces: Array.isArray(payload?.workspaces) ? payload.workspaces : [],
|
||||||
|
});
|
||||||
|
|
||||||
type AppShellContextValue = {
|
type AppShellContextValue = {
|
||||||
status: Accessor<"idle" | "loading" | "success" | "error">;
|
status: Accessor<"idle" | "loading" | "success" | "error">;
|
||||||
error: Accessor<string>;
|
error: Accessor<string>;
|
||||||
|
installation: Accessor<AppShellInstallation | undefined>;
|
||||||
railItems: Accessor<readonly RailItem[]>;
|
railItems: Accessor<readonly RailItem[]>;
|
||||||
activeServer: Accessor<ActiveServer>;
|
activeServer: Accessor<ActiveServer>;
|
||||||
activeProject: Accessor<ActiveProject>;
|
activeProject: Accessor<ActiveProject>;
|
||||||
@@ -140,11 +152,12 @@ const buildRailItems = (payload: AppShellPayload | null): readonly RailItem[] =>
|
|||||||
}
|
}
|
||||||
|
|
||||||
const kind = payload.installation.mode === "personal" ? "personal" : "organization";
|
const kind = payload.installation.mode === "personal" ? "personal" : "organization";
|
||||||
|
const serverName = payload.installation.name || payload.organizations[0]?.name || payload.installation.host;
|
||||||
|
|
||||||
return payload.organizations.map((organization, index) => ({
|
return payload.organizations.map((organization, index) => ({
|
||||||
id: organization.id,
|
id: organization.id,
|
||||||
label: organization.name,
|
label: serverName || organization.name,
|
||||||
abbreviation: buildAbbreviation(organization.name, kind === "personal" ? "P" : "O"),
|
abbreviation: buildAbbreviation(serverName || organization.name, kind === "personal" ? "P" : "O"),
|
||||||
kind,
|
kind,
|
||||||
active: index === 0,
|
active: index === 0,
|
||||||
}));
|
}));
|
||||||
@@ -159,11 +172,12 @@ const buildActiveServer = (payload: AppShellPayload | null): ActiveServer => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const kind = installation.mode === "personal" ? "personal" : "organization";
|
const kind = installation.mode === "personal" ? "personal" : "organization";
|
||||||
|
const serverName = installation.name || organization.name || installation.host;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
id: installation.id,
|
id: installation.id,
|
||||||
name: organization.name || installation.host || fallbackActiveServer.name,
|
name: serverName || fallbackActiveServer.name,
|
||||||
abbreviation: buildAbbreviation(organization.name || installation.host, kind === "personal" ? "P" : "O"),
|
abbreviation: buildAbbreviation(serverName, kind === "personal" ? "P" : "O"),
|
||||||
kind,
|
kind,
|
||||||
connectedLabel: kind === "organization" ? `${payload?.teams.length ?? 0} connected` : undefined,
|
connectedLabel: kind === "organization" ? `${payload?.teams.length ?? 0} connected` : undefined,
|
||||||
subtitle: kind === "personal" ? installation.host || payload?.admin?.homeTitle || "Personal home" : undefined,
|
subtitle: kind === "personal" ? installation.host || payload?.admin?.homeTitle || "Personal home" : undefined,
|
||||||
@@ -180,6 +194,16 @@ const buildProjectItems = (payload: AppShellPayload | null): readonly ProjectIte
|
|||||||
id: project.id,
|
id: project.id,
|
||||||
name: project.name,
|
name: project.name,
|
||||||
description: project.slug || "Persisted project workspace",
|
description: project.slug || "Persisted project workspace",
|
||||||
|
groupLabel: payload.departments.find((department) => department.id === project.departmentId)?.name || "Projects",
|
||||||
|
parentLabel:
|
||||||
|
payload.teams.find((team) => team.id === project.teamId)?.name ||
|
||||||
|
payload.departments.find((department) => department.id === project.departmentId)?.name ||
|
||||||
|
"Shared project",
|
||||||
|
meta: (() => {
|
||||||
|
const workspaceCount = payload.workspaces.filter((workspace) => workspace.projectId === project.id).length;
|
||||||
|
|
||||||
|
return workspaceCount > 0 ? `${workspaceCount} workspace${workspaceCount === 1 ? "" : "s"}` : undefined;
|
||||||
|
})(),
|
||||||
active: index === 0,
|
active: index === 0,
|
||||||
}));
|
}));
|
||||||
};
|
};
|
||||||
@@ -244,7 +268,7 @@ const buildActiveUserProfile = (payload: AppShellPayload | null): ActiveUserProf
|
|||||||
return fallbackActiveUserProfile;
|
return fallbackActiveUserProfile;
|
||||||
}
|
}
|
||||||
|
|
||||||
const organizationName = payload.organizations[0]?.name ?? fallbackActiveServer.name;
|
const organizationName = payload.installation?.name || payload.organizations[0]?.name || fallbackActiveServer.name;
|
||||||
const departmentName = payload.departments[0]?.name;
|
const departmentName = payload.departments[0]?.name;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
@@ -271,13 +295,23 @@ export const AppShellDataProvider = (props: { children: JSX.Element }): JSX.Elem
|
|||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
const body = (await response.json()) as { data?: AppShellPayload; error?: { message?: string } };
|
const body = (await response.json()) as {
|
||||||
|
data?: AppShellPayload;
|
||||||
|
error?: { message?: string } | string;
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
const errorMessage =
|
||||||
|
typeof body.message === "string"
|
||||||
|
? body.message
|
||||||
|
: typeof body.error === "string"
|
||||||
|
? body.error
|
||||||
|
: body.error?.message;
|
||||||
|
|
||||||
if (!response.ok || !body.data) {
|
if (!response.ok || !body.data) {
|
||||||
throw new Error(body.error?.message || "Failed to load app shell state.");
|
throw new Error(errorMessage || "Failed to load app shell state.");
|
||||||
}
|
}
|
||||||
|
|
||||||
setPayload(body.data);
|
setPayload(normalizeAppShellPayload(body.data));
|
||||||
setStatus("success");
|
setStatus("success");
|
||||||
} catch (loadError) {
|
} catch (loadError) {
|
||||||
setStatus("error");
|
setStatus("error");
|
||||||
@@ -292,6 +326,7 @@ export const AppShellDataProvider = (props: { children: JSX.Element }): JSX.Elem
|
|||||||
const value: AppShellContextValue = {
|
const value: AppShellContextValue = {
|
||||||
status,
|
status,
|
||||||
error,
|
error,
|
||||||
|
installation: createMemo(() => payload()?.installation),
|
||||||
railItems: createMemo(() => buildRailItems(payload())),
|
railItems: createMemo(() => buildRailItems(payload())),
|
||||||
activeServer: createMemo(() => buildActiveServer(payload())),
|
activeServer: createMemo(() => buildActiveServer(payload())),
|
||||||
activeProject: createMemo(() => buildActiveProject(payload())),
|
activeProject: createMemo(() => buildActiveProject(payload())),
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
Home,
|
Home,
|
||||||
Keyboard,
|
Keyboard,
|
||||||
LayoutGrid,
|
LayoutGrid,
|
||||||
|
ListCollapse,
|
||||||
LogOut,
|
LogOut,
|
||||||
Repeat,
|
Repeat,
|
||||||
Search,
|
Search,
|
||||||
@@ -71,9 +72,43 @@ export type ProjectItem = {
|
|||||||
id: string;
|
id: string;
|
||||||
name: string;
|
name: string;
|
||||||
description: string;
|
description: string;
|
||||||
|
groupLabel?: string;
|
||||||
|
parentLabel?: string;
|
||||||
|
meta?: string;
|
||||||
active?: boolean;
|
active?: boolean;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type ProjectMenuTarget =
|
||||||
|
| {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
kind: "surface";
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
kind: "folder";
|
||||||
|
}
|
||||||
|
| {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
kind: "project";
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ProjectContextMenuAction = {
|
||||||
|
id: string;
|
||||||
|
label: string;
|
||||||
|
tone?: "default" | "danger";
|
||||||
|
shortcut?: WorkspaceContextMenuShortcut;
|
||||||
|
children?: readonly ProjectContextMenuAction[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ProjectContextMenuSection = {
|
||||||
|
id: string;
|
||||||
|
label?: string;
|
||||||
|
items: readonly ProjectContextMenuAction[];
|
||||||
|
};
|
||||||
|
|
||||||
export type SidebarItem = {
|
export type SidebarItem = {
|
||||||
id: string;
|
id: string;
|
||||||
label: string;
|
label: string;
|
||||||
@@ -364,9 +399,31 @@ export const activeDepartment: ActiveDepartment = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const projectItems: readonly ProjectItem[] = [
|
export const projectItems: readonly ProjectItem[] = [
|
||||||
{ id: "general", name: "General", description: "Default shared project", active: true },
|
{
|
||||||
{ id: "operations", name: "Operations", description: "Cross-team planning and delivery" },
|
id: "general",
|
||||||
{ id: "hiring", name: "Hiring", description: "Candidate pipeline and interview loops" },
|
name: "General",
|
||||||
|
description: "Default shared project",
|
||||||
|
groupLabel: "Shared space",
|
||||||
|
parentLabel: "Workspace home",
|
||||||
|
meta: "1 workspace",
|
||||||
|
active: true,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "operations",
|
||||||
|
name: "Operations",
|
||||||
|
description: "Cross-team planning and delivery",
|
||||||
|
groupLabel: "Team folders",
|
||||||
|
parentLabel: "Shared Services",
|
||||||
|
meta: "2 workspaces",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "hiring",
|
||||||
|
name: "Hiring",
|
||||||
|
description: "Candidate pipeline and interview loops",
|
||||||
|
groupLabel: "Team folders",
|
||||||
|
parentLabel: "People Ops",
|
||||||
|
meta: "1 workspace",
|
||||||
|
},
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const departmentItems: readonly DepartmentItem[] = [
|
export const departmentItems: readonly DepartmentItem[] = [
|
||||||
@@ -420,6 +477,7 @@ export const workspaceTree: readonly WorkspaceTreeNode[] = [
|
|||||||
|
|
||||||
export const workspaceSidebarHeaderActions: readonly SidebarHeaderAction[] = [
|
export const workspaceSidebarHeaderActions: readonly SidebarHeaderAction[] = [
|
||||||
{ id: "search-workspace", label: "Search workspace", icon: Search },
|
{ id: "search-workspace", label: "Search workspace", icon: Search },
|
||||||
|
{ id: "toggle-workspace-folders", label: "Collapse all folders", icon: ListCollapse },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const mobileBottomNavItems: readonly MobileBottomNavItem[] = [
|
export const mobileBottomNavItems: readonly MobileBottomNavItem[] = [
|
||||||
@@ -533,6 +591,78 @@ export const getWorkspaceContextMenuSections = (
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getProjectCreateActions = (): readonly ProjectContextMenuAction[] =>
|
||||||
|
[
|
||||||
|
{ id: "new-project", label: "New project" },
|
||||||
|
{ id: "new-folder", label: "New folder" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
const getProjectFolderDangerActions = (): readonly ProjectContextMenuAction[] =>
|
||||||
|
[
|
||||||
|
{ id: "delete-folder", label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||||
|
] as const;
|
||||||
|
|
||||||
|
export const createProjectSurfaceTarget = (label = "Projects"): ProjectMenuTarget => ({
|
||||||
|
id: "project-surface",
|
||||||
|
label,
|
||||||
|
kind: "surface",
|
||||||
|
});
|
||||||
|
|
||||||
|
export const createProjectFolderTarget = (id: string, label: string): ProjectMenuTarget => ({
|
||||||
|
id,
|
||||||
|
label,
|
||||||
|
kind: "folder",
|
||||||
|
});
|
||||||
|
|
||||||
|
export const createProjectTarget = (project: ProjectItem): ProjectMenuTarget => ({
|
||||||
|
id: project.id,
|
||||||
|
label: project.name,
|
||||||
|
kind: "project",
|
||||||
|
});
|
||||||
|
|
||||||
|
export const getProjectContextMenuEyebrow = (target: ProjectMenuTarget): string => {
|
||||||
|
switch (target.kind) {
|
||||||
|
case "surface":
|
||||||
|
return "Projects";
|
||||||
|
case "folder":
|
||||||
|
return "Folder";
|
||||||
|
case "project":
|
||||||
|
return "Project";
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getProjectContextMenuSections = (target: ProjectMenuTarget): readonly ProjectContextMenuSection[] => {
|
||||||
|
const createActions = getProjectCreateActions();
|
||||||
|
|
||||||
|
switch (target.kind) {
|
||||||
|
case "surface":
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: "create",
|
||||||
|
items: createActions,
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
case "folder":
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: "create",
|
||||||
|
items: createActions,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: "organize",
|
||||||
|
items: getProjectFolderDangerActions(),
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
case "project":
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
id: "create",
|
||||||
|
items: createActions,
|
||||||
|
},
|
||||||
|
] as const;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
export const topBarActions: readonly TopBarAction[] = [
|
export const topBarActions: readonly TopBarAction[] = [
|
||||||
{ id: "search", label: "Search", icon: Search },
|
{ id: "search", label: "Search", icon: Search },
|
||||||
] as const;
|
] as const;
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
@use "../../../styles/tools/mixins" as *;
|
||||||
|
|
||||||
|
@mixin section-label {
|
||||||
|
@include text-caption;
|
||||||
|
color: var(--color-text-subtle);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin tree-list {
|
||||||
|
list-style: none;
|
||||||
|
display: grid;
|
||||||
|
gap: var(--space-1);
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin empty-slot {
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin input-row {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin input {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--color-text);
|
||||||
|
font: inherit;
|
||||||
|
outline: none;
|
||||||
|
|
||||||
|
&::placeholder {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
position: relative;
|
||||||
|
isolation: isolate;
|
||||||
|
grid-template-columns: auto auto minmax(0, 1fr) auto;
|
||||||
|
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: 0;
|
||||||
|
border-radius: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-align: left;
|
||||||
|
transition:
|
||||||
|
color 160ms var(--easing-standard),
|
||||||
|
box-shadow 160ms var(--easing-standard),
|
||||||
|
transform 180ms var(--easing-standard);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
background: transparent;
|
||||||
|
transition:
|
||||||
|
background 160ms var(--easing-standard),
|
||||||
|
border-color 160ms var(--easing-standard),
|
||||||
|
box-shadow 160ms var(--easing-standard);
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
> * {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-hover {
|
||||||
|
color: var(--color-text);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
background: color-mix(in srgb, var(--color-surface-hover) 80%, var(--color-accent-soft) 20%);
|
||||||
|
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-folder {
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-dragging {
|
||||||
|
opacity: 0.45;
|
||||||
|
transform: scale(0.985);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-drop-before {
|
||||||
|
&::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||||
|
right: var(--space-3);
|
||||||
|
top: calc((var(--space-1) * -0.5) - 1px);
|
||||||
|
height: 2px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-drop-after {
|
||||||
|
&::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||||
|
right: var(--space-3);
|
||||||
|
bottom: calc((var(--space-1) * -0.5) - 1px);
|
||||||
|
height: 2px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-drop-inside {
|
||||||
|
color: var(--color-text);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
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));
|
||||||
|
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin folder-chevron {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
transition: transform 160ms var(--easing-standard);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin folder-chevron-open {
|
||||||
|
transform: rotate(90deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-active {
|
||||||
|
color: var(--color-text);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
border-color: var(--color-border);
|
||||||
|
background: var(--color-surface);
|
||||||
|
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin icon {
|
||||||
|
color: inherit;
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin label {
|
||||||
|
@include text-label;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-meta {
|
||||||
|
@include text-caption;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
export type NavTreeDropIntent = "before" | "after" | "inside";
|
||||||
|
|
||||||
|
export type NavTreeDropTarget = {
|
||||||
|
parentId: string | null;
|
||||||
|
index: number;
|
||||||
|
intent: NavTreeDropIntent;
|
||||||
|
targetNodeId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type NavTreeDragState = {
|
||||||
|
draggedNodeId: string;
|
||||||
|
dropTarget: NavTreeDropTarget | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type NavTreeLocation<TNode> = {
|
||||||
|
parentId: string | null;
|
||||||
|
index: number;
|
||||||
|
node: TNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type NavTreeAdapter<TNode> = {
|
||||||
|
getNodeId: (node: TNode) => string;
|
||||||
|
isBranchNode: (node: TNode) => boolean;
|
||||||
|
getChildren: (node: TNode) => readonly TNode[];
|
||||||
|
withChildren: (node: TNode, children: readonly TNode[]) => TNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
export const isUuidString = (value: string | null | undefined): boolean => {
|
||||||
|
if (typeof value !== "string") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return UUID_PATTERN.test(value.trim());
|
||||||
|
};
|
||||||
|
|
||||||
|
export const collectBranchNodeIds = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): string[] => {
|
||||||
|
const ids: string[] = [];
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (!adapter.isBranchNode(node)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ids.push(adapter.getNodeId(node));
|
||||||
|
ids.push(...collectBranchNodeIds(adapter.getChildren(node), adapter));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ids;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const findTreeNodeLocation = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
nodeId: string,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
parentId: string | null = null,
|
||||||
|
): NavTreeLocation<TNode> | null => {
|
||||||
|
for (let index = 0; index < nodes.length; index += 1) {
|
||||||
|
const node = nodes[index];
|
||||||
|
|
||||||
|
if (adapter.getNodeId(node) === nodeId) {
|
||||||
|
return { parentId, index, node };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adapter.isBranchNode(node)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nestedLocation = findTreeNodeLocation(adapter.getChildren(node), nodeId, adapter, adapter.getNodeId(node));
|
||||||
|
if (nestedLocation) {
|
||||||
|
return nestedLocation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const findTreeNodeDepth = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
nodeId: string,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
depth = 0,
|
||||||
|
): number | null => {
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (adapter.getNodeId(node) === nodeId) {
|
||||||
|
return depth;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adapter.isBranchNode(node)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nestedDepth = findTreeNodeDepth(adapter.getChildren(node), nodeId, adapter, depth + 1);
|
||||||
|
if (nestedDepth !== null) {
|
||||||
|
return nestedDepth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const treeContainsNode = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
nodeId: string,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): boolean => {
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (adapter.getNodeId(node) === nodeId) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (adapter.isBranchNode(node) && treeContainsNode(adapter.getChildren(node), nodeId, adapter)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const removeTreeNode = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
nodeId: string,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): { nodes: TNode[]; removed: TNode | null } => {
|
||||||
|
const nextNodes: TNode[] = [];
|
||||||
|
let removed: TNode | null = null;
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (adapter.getNodeId(node) === nodeId) {
|
||||||
|
removed = node;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (adapter.isBranchNode(node)) {
|
||||||
|
const result = removeTreeNode(adapter.getChildren(node), nodeId, adapter);
|
||||||
|
|
||||||
|
if (result.removed) {
|
||||||
|
removed = result.removed;
|
||||||
|
nextNodes.push(adapter.withChildren(node, result.nodes));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nextNodes.push(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { nodes: nextNodes, removed };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const insertTreeNode = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
parentId: string | null,
|
||||||
|
index: number,
|
||||||
|
nodeToInsert: TNode,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): TNode[] => {
|
||||||
|
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 (!adapter.isBranchNode(node)) {
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (adapter.getNodeId(node) === parentId) {
|
||||||
|
const nextChildren = [...adapter.getChildren(node)];
|
||||||
|
nextChildren.splice(Math.max(0, Math.min(index, nextChildren.length)), 0, nodeToInsert);
|
||||||
|
return adapter.withChildren(node, nextChildren);
|
||||||
|
}
|
||||||
|
|
||||||
|
return adapter.withChildren(node, insertTreeNode(adapter.getChildren(node), parentId, index, nodeToInsert, adapter));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const moveTreeNode = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
draggedNodeId: string,
|
||||||
|
dropTarget: NavTreeDropTarget,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): TNode[] => {
|
||||||
|
const location = findTreeNodeLocation(nodes, draggedNodeId, adapter);
|
||||||
|
|
||||||
|
if (!location) {
|
||||||
|
return [...nodes];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
adapter.isBranchNode(location.node) &&
|
||||||
|
dropTarget.parentId !== null &&
|
||||||
|
(treeContainsNode(adapter.getChildren(location.node), dropTarget.parentId, adapter) ||
|
||||||
|
dropTarget.parentId === adapter.getNodeId(location.node))
|
||||||
|
) {
|
||||||
|
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 = removeTreeNode(nodes, draggedNodeId, adapter);
|
||||||
|
if (!removalResult.removed) {
|
||||||
|
return [...nodes];
|
||||||
|
}
|
||||||
|
|
||||||
|
return insertTreeNode(removalResult.nodes, dropTarget.parentId, normalizedIndex, removalResult.removed, adapter);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getPointerRelativeY = (event: PointerEvent): number | null => {
|
||||||
|
const currentTarget = event.currentTarget;
|
||||||
|
if (!(currentTarget instanceof HTMLElement)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bounds = currentTarget.getBoundingClientRect();
|
||||||
|
return bounds.height <= 0 ? 0.5 : (event.clientY - bounds.top) / bounds.height;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const resolveTreeDropTarget = <TNode>(params: {
|
||||||
|
parentId: string | null;
|
||||||
|
index: number;
|
||||||
|
node: TNode;
|
||||||
|
relativeY: number;
|
||||||
|
adapter: NavTreeAdapter<TNode>;
|
||||||
|
beforeThreshold?: number;
|
||||||
|
beforeThresholdFirstSibling?: number;
|
||||||
|
afterThreshold?: number;
|
||||||
|
}): NavTreeDropTarget => {
|
||||||
|
const {
|
||||||
|
parentId,
|
||||||
|
index,
|
||||||
|
node,
|
||||||
|
relativeY,
|
||||||
|
adapter,
|
||||||
|
beforeThreshold = 0.28,
|
||||||
|
beforeThresholdFirstSibling = 0.42,
|
||||||
|
afterThreshold = 0.72,
|
||||||
|
} = params;
|
||||||
|
|
||||||
|
const targetNodeId = adapter.getNodeId(node);
|
||||||
|
|
||||||
|
if (adapter.isBranchNode(node)) {
|
||||||
|
const nextBeforeThreshold = index === 0 ? beforeThresholdFirstSibling : beforeThreshold;
|
||||||
|
|
||||||
|
if (relativeY < nextBeforeThreshold) {
|
||||||
|
return { parentId, index, intent: "before", targetNodeId };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (relativeY > afterThreshold) {
|
||||||
|
return { parentId, index: index + 1, intent: "after", targetNodeId };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
parentId: targetNodeId,
|
||||||
|
index: adapter.getChildren(node).length,
|
||||||
|
intent: "inside",
|
||||||
|
targetNodeId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
parentId,
|
||||||
|
index: relativeY < 0.5 ? index : index + 1,
|
||||||
|
intent: relativeY < 0.5 ? "before" : "after",
|
||||||
|
targetNodeId,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -92,12 +92,6 @@
|
|||||||
flex-wrap: wrap;
|
flex-wrap: wrap;
|
||||||
}
|
}
|
||||||
|
|
||||||
.eyebrow {
|
|
||||||
@include text-caption;
|
|
||||||
color: var(--color-text-muted);
|
|
||||||
text-transform: uppercase;
|
|
||||||
}
|
|
||||||
|
|
||||||
.title {
|
.title {
|
||||||
@include text-display;
|
@include text-display;
|
||||||
font-family: var(--font-family-display);
|
font-family: var(--font-family-display);
|
||||||
@@ -246,10 +240,16 @@
|
|||||||
color: var(--color-text-muted);
|
color: var(--color-text-muted);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.fieldHelp {
|
||||||
|
@include text-caption;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
|
||||||
.field input,
|
.field input,
|
||||||
.field select {
|
.field select {
|
||||||
min-height: var(--control-size-md);
|
min-height: var(--control-size-md);
|
||||||
width: 100%;
|
width: 100%;
|
||||||
|
font: inherit;
|
||||||
border: 1px solid var(--color-border);
|
border: 1px solid var(--color-border);
|
||||||
border-radius: var(--radius-lg);
|
border-radius: var(--radius-lg);
|
||||||
background: var(--color-surface-elevated);
|
background: var(--color-surface-elevated);
|
||||||
@@ -261,6 +261,14 @@
|
|||||||
background 160ms var(--easing-standard);
|
background 160ms var(--easing-standard);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.field input:disabled,
|
||||||
|
.field select:disabled {
|
||||||
|
cursor: not-allowed;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
background: color-mix(in srgb, var(--color-surface-secondary) 92%, transparent);
|
||||||
|
border-color: color-mix(in srgb, var(--color-border) 72%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
.field input:focus-visible,
|
.field input:focus-visible,
|
||||||
.field select:focus-visible {
|
.field select:focus-visible {
|
||||||
outline: none;
|
outline: none;
|
||||||
@@ -519,13 +527,45 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.wizardPanel {
|
.wizardPanel {
|
||||||
width: calc(100vw - (var(--space-4) * 2));
|
width: 100vw;
|
||||||
max-height: calc(100dvh - (var(--space-4) * 2));
|
max-height: 100dvh;
|
||||||
margin: var(--space-4) auto;
|
margin: 0;
|
||||||
padding: var(--space-3);
|
padding: var(--space-3);
|
||||||
|
padding-bottom: calc(var(--space-3) + env(safe-area-inset-bottom, 0px));
|
||||||
|
border-radius: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wizardHeader,
|
||||||
|
.wizardBody,
|
||||||
|
.wizardSidebar {
|
||||||
|
gap: var(--space-3);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wizardSteps {
|
||||||
|
grid-auto-flow: column;
|
||||||
|
grid-auto-columns: minmax(10rem, 1fr);
|
||||||
|
overflow-x: auto;
|
||||||
|
padding-bottom: var(--space-1);
|
||||||
|
scrollbar-width: thin;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wizardStepButton {
|
||||||
|
min-width: 10rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardFormActions {
|
.wizardFormActions {
|
||||||
gap: var(--space-2);
|
gap: var(--space-2);
|
||||||
|
flex-direction: column-reverse;
|
||||||
|
align-items: stretch;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wizardFormActions .primaryButton {
|
||||||
|
margin-left: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
.wizardFormActions .primaryButton,
|
||||||
|
.wizardFormActions .secondaryButton,
|
||||||
|
.wizardCloseButton {
|
||||||
|
width: 100%;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.tsx
|
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.tsx
|
||||||
|
|
||||||
import { For, Show, createMemo, createSignal, onMount, type JSX } from "solid-js";
|
import { For, Show, createEffect, createMemo, createSignal, type JSX } from "solid-js";
|
||||||
import { Portal } from "solid-js/web";
|
import { Portal } from "solid-js/web";
|
||||||
import { createStore } from "solid-js/store";
|
import { createStore } from "solid-js/store";
|
||||||
import { resolveAPIBase } from "../../../lib/api";
|
import { resolveAPIBase } from "../../../lib/api";
|
||||||
@@ -44,34 +44,43 @@ const bootstrapStepDefinitions: readonly BootstrapStepDefinition[] = [
|
|||||||
},
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
const bootstrapCompletionStorageKey = "moku.bootstrap.completed";
|
const defaultInstanceForm = {
|
||||||
|
protocol: "http",
|
||||||
|
access: "local",
|
||||||
|
host: "localhost",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const defaultModeForm = {
|
||||||
|
mode: "personal",
|
||||||
|
name: "",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const defaultAdminForm = {
|
||||||
|
displayName: "Admin",
|
||||||
|
email: "admin@example.com",
|
||||||
|
password: "",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const personalStructureDefaults = {
|
||||||
|
departmentName: "Default",
|
||||||
|
teamName: "Personal",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const organizationalStructureDefaults = {
|
||||||
|
departmentName: "Department",
|
||||||
|
teamName: "Team",
|
||||||
|
} as const;
|
||||||
|
|
||||||
|
const defaultStructureForm = {
|
||||||
|
...personalStructureDefaults,
|
||||||
|
projectName: "Project",
|
||||||
|
} as const;
|
||||||
|
|
||||||
const initialSubmissionState = (): BootstrapSubmissionState => ({
|
const initialSubmissionState = (): BootstrapSubmissionState => ({
|
||||||
status: "idle",
|
status: "idle",
|
||||||
error: "",
|
error: "",
|
||||||
});
|
});
|
||||||
|
|
||||||
const readBootstrapCompletion = (): boolean => {
|
|
||||||
if (typeof window === "undefined") {
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
return window.localStorage.getItem(bootstrapCompletionStorageKey) === "true";
|
|
||||||
};
|
|
||||||
|
|
||||||
const writeBootstrapCompletion = (isComplete: boolean): void => {
|
|
||||||
if (typeof window === "undefined") {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (isComplete) {
|
|
||||||
window.localStorage.setItem(bootstrapCompletionStorageKey, "true");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
window.localStorage.removeItem(bootstrapCompletionStorageKey);
|
|
||||||
};
|
|
||||||
|
|
||||||
const readResponseBody = async (response: Response): Promise<unknown> => {
|
const readResponseBody = async (response: Response): Promise<unknown> => {
|
||||||
const raw = await response.text();
|
const raw = await response.text();
|
||||||
|
|
||||||
@@ -86,6 +95,52 @@ const readResponseBody = async (response: Response): Promise<unknown> => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const readResponseError = (step: BootstrapStepKey, data: unknown): string => {
|
||||||
|
const fallback = `Bootstrap ${step} request failed.`;
|
||||||
|
|
||||||
|
if (typeof data === "string") {
|
||||||
|
const message = data.trim();
|
||||||
|
return message || fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!data || typeof data !== "object") {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
const record = data as {
|
||||||
|
error?: string;
|
||||||
|
message?: string;
|
||||||
|
requestId?: string;
|
||||||
|
};
|
||||||
|
const message = typeof record.message === "string" ? record.message.trim() : "";
|
||||||
|
const errorCode = typeof record.error === "string" ? record.error.trim() : "";
|
||||||
|
const requestId = typeof record.requestId === "string" ? record.requestId.trim() : "";
|
||||||
|
|
||||||
|
if (!message && !errorCode && !requestId) {
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
const details: string[] = [];
|
||||||
|
|
||||||
|
if (errorCode) {
|
||||||
|
details.push(`code: ${errorCode}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (requestId) {
|
||||||
|
details.push(`request: ${requestId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message && details.length > 0) {
|
||||||
|
return `${message} (${details.join(", ")})`;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (message) {
|
||||||
|
return message;
|
||||||
|
}
|
||||||
|
|
||||||
|
return `${fallback} (${details.join(", ")})`;
|
||||||
|
};
|
||||||
|
|
||||||
type WorkspaceHomeProps = {
|
type WorkspaceHomeProps = {
|
||||||
sidebarCollapsed: boolean;
|
sidebarCollapsed: boolean;
|
||||||
onToggleSidebarCollapse: () => void;
|
onToggleSidebarCollapse: () => void;
|
||||||
@@ -93,24 +148,10 @@ type WorkspaceHomeProps = {
|
|||||||
|
|
||||||
export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
||||||
const appShellData = useAppShellData();
|
const appShellData = useAppShellData();
|
||||||
const [instanceForm, setInstanceForm] = createStore({
|
const [instanceForm, setInstanceForm] = createStore({ ...defaultInstanceForm });
|
||||||
protocol: "http",
|
const [modeForm, setModeForm] = createStore({ ...defaultModeForm });
|
||||||
access: "local",
|
const [adminForm, setAdminForm] = createStore({ ...defaultAdminForm });
|
||||||
host: "localhost",
|
const [structureForm, setStructureForm] = createStore({ ...defaultStructureForm });
|
||||||
});
|
|
||||||
const [modeForm, setModeForm] = createStore({
|
|
||||||
mode: "personal",
|
|
||||||
});
|
|
||||||
const [adminForm, setAdminForm] = createStore({
|
|
||||||
displayName: "Ronald",
|
|
||||||
email: "admin@example.com",
|
|
||||||
password: "",
|
|
||||||
});
|
|
||||||
const [structureForm, setStructureForm] = createStore({
|
|
||||||
departmentName: "Platform",
|
|
||||||
teamName: "Core",
|
|
||||||
projectName: "Moku",
|
|
||||||
});
|
|
||||||
const [stepState, setStepState] = createStore<Record<BootstrapStepKey, BootstrapSubmissionState>>({
|
const [stepState, setStepState] = createStore<Record<BootstrapStepKey, BootstrapSubmissionState>>({
|
||||||
instance: initialSubmissionState(),
|
instance: initialSubmissionState(),
|
||||||
mode: initialSubmissionState(),
|
mode: initialSubmissionState(),
|
||||||
@@ -122,10 +163,43 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
const [isWizardOpen, setIsWizardOpen] = createSignal(false);
|
const [isWizardOpen, setIsWizardOpen] = createSignal(false);
|
||||||
const [currentStepIndex, setCurrentStepIndex] = createSignal(0);
|
const [currentStepIndex, setCurrentStepIndex] = createSignal(0);
|
||||||
|
|
||||||
onMount(() => {
|
createEffect(() => {
|
||||||
const isComplete = readBootstrapCompletion();
|
if (modeForm.mode === "personal") {
|
||||||
setIsBootstrapComplete(isComplete);
|
setStructureForm("departmentName", personalStructureDefaults.departmentName);
|
||||||
setIsWizardOpen(!isComplete);
|
setStructureForm("teamName", personalStructureDefaults.teamName);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (structureForm.departmentName === personalStructureDefaults.departmentName) {
|
||||||
|
setStructureForm("departmentName", organizationalStructureDefaults.departmentName);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (structureForm.teamName === personalStructureDefaults.teamName) {
|
||||||
|
setStructureForm("teamName", organizationalStructureDefaults.teamName);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
const shellStatus = appShellData.status();
|
||||||
|
|
||||||
|
if (shellStatus === "idle" || shellStatus === "loading") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (shellStatus !== "success") {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const installationAccessor = appShellData.installation;
|
||||||
|
const installation = typeof installationAccessor === "function" ? installationAccessor() : undefined;
|
||||||
|
const isPersistedBootstrap = installation?.isBootstrapped ?? false;
|
||||||
|
|
||||||
|
if (!isPersistedBootstrap) {
|
||||||
|
resetWizardState();
|
||||||
|
}
|
||||||
|
|
||||||
|
setIsBootstrapComplete(isPersistedBootstrap);
|
||||||
|
setIsWizardOpen(!isPersistedBootstrap);
|
||||||
setIsBootstrapStateResolved(true);
|
setIsBootstrapStateResolved(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -133,6 +207,10 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
props.sidebarCollapsed ? "Expand left workspace sidebar" : "Collapse left workspace sidebar";
|
props.sidebarCollapsed ? "Expand left workspace sidebar" : "Collapse left workspace sidebar";
|
||||||
const breadcrumb = (): string => `${appShellData.activeServer().name} / ${appShellData.activeProject().name} / Home`;
|
const breadcrumb = (): string => `${appShellData.activeServer().name} / ${appShellData.activeProject().name} / Home`;
|
||||||
const apiBase = (): string => resolveAPIBase();
|
const apiBase = (): string => resolveAPIBase();
|
||||||
|
const bootstrapTargetLabel = (): string =>
|
||||||
|
modeForm.mode === "personal" ? "Personal server" : "Organization server";
|
||||||
|
const bootstrapNamePlaceholder = (): string =>
|
||||||
|
modeForm.mode === "personal" ? "Personal server name" : "Organization server name";
|
||||||
const currentStep = createMemo<BootstrapStepDefinition>(
|
const currentStep = createMemo<BootstrapStepDefinition>(
|
||||||
() => bootstrapStepDefinitions[currentStepIndex()] ?? bootstrapStepDefinitions[0]!,
|
() => bootstrapStepDefinitions[currentStepIndex()] ?? bootstrapStepDefinitions[0]!,
|
||||||
);
|
);
|
||||||
@@ -141,6 +219,20 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
const isLastStep = (): boolean => currentStepIndex() === bootstrapStepDefinitions.length - 1;
|
const isLastStep = (): boolean => currentStepIndex() === bootstrapStepDefinitions.length - 1;
|
||||||
const canDismissWizard = (): boolean => isBootstrapComplete();
|
const canDismissWizard = (): boolean => isBootstrapComplete();
|
||||||
|
|
||||||
|
const resetWizardState = (): void => {
|
||||||
|
setInstanceForm({ ...defaultInstanceForm });
|
||||||
|
setModeForm({ ...defaultModeForm });
|
||||||
|
setAdminForm({ ...defaultAdminForm });
|
||||||
|
setStructureForm({ ...defaultStructureForm });
|
||||||
|
setStepState({
|
||||||
|
instance: initialSubmissionState(),
|
||||||
|
mode: initialSubmissionState(),
|
||||||
|
admin: initialSubmissionState(),
|
||||||
|
structure: initialSubmissionState(),
|
||||||
|
});
|
||||||
|
setCurrentStepIndex(0);
|
||||||
|
};
|
||||||
|
|
||||||
const submitStep = async (step: BootstrapStepKey, payload: unknown): Promise<boolean> => {
|
const submitStep = async (step: BootstrapStepKey, payload: unknown): Promise<boolean> => {
|
||||||
setStepState(step, { status: "submitting", error: "" });
|
setStepState(step, { status: "submitting", error: "" });
|
||||||
|
|
||||||
@@ -156,11 +248,7 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
const data = await readResponseBody(response);
|
const data = await readResponseBody(response);
|
||||||
|
|
||||||
if (!response.ok) {
|
if (!response.ok) {
|
||||||
throw new Error(
|
throw new Error(readResponseError(step, data));
|
||||||
typeof data?.error?.message === "string"
|
|
||||||
? data.error.message
|
|
||||||
: `Bootstrap ${step} request failed.`,
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
setStepState(step, {
|
setStepState(step, {
|
||||||
@@ -201,9 +289,14 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isLastStep()) {
|
if (isLastStep()) {
|
||||||
writeBootstrapCompletion(true);
|
await appShellData.reload();
|
||||||
setIsBootstrapComplete(true);
|
const installationAccessor = appShellData.installation;
|
||||||
setIsWizardOpen(false);
|
const installation = typeof installationAccessor === "function" ? installationAccessor() : undefined;
|
||||||
|
const isPersistedBootstrap = installation?.isBootstrapped ?? false;
|
||||||
|
|
||||||
|
setIsBootstrapComplete(isPersistedBootstrap);
|
||||||
|
setIsWizardOpen(!isPersistedBootstrap);
|
||||||
|
setIsBootstrapStateResolved(true);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -267,8 +360,7 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<section class={styles.hero} data-slot="workspace-home-hero">
|
<section class={styles.hero} data-slot="workspace-home-hero">
|
||||||
<span class={styles.eyebrow}>Bootstrap</span>
|
<h1 class={styles.title}>{isBootstrapComplete() ? appShellData.activeServer().name : bootstrapTargetLabel()}</h1>
|
||||||
<h1 class={styles.title}>{appShellData.activeServer().name}</h1>
|
|
||||||
<Show when={isBootstrapStateResolved() && !isBootstrapComplete()}>
|
<Show when={isBootstrapStateResolved() && !isBootstrapComplete()}>
|
||||||
<div class={styles.heroActions}>
|
<div class={styles.heroActions}>
|
||||||
<button type="button" class={styles.primaryButton} onClick={(): void => setIsWizardOpen(true)}>
|
<button type="button" class={styles.primaryButton} onClick={(): void => setIsWizardOpen(true)}>
|
||||||
@@ -288,7 +380,7 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
<header class={styles.wizardHeader} data-slot="bootstrap-wizard-header">
|
<header class={styles.wizardHeader} data-slot="bootstrap-wizard-header">
|
||||||
<div class={styles.wizardHeaderCopy}>
|
<div class={styles.wizardHeaderCopy}>
|
||||||
<h2 id="bootstrap-wizard-title" class={styles.wizardTitle}>
|
<h2 id="bootstrap-wizard-title" class={styles.wizardTitle}>
|
||||||
Bootstrap {appShellData.activeServer().name}
|
Bootstrap {bootstrapTargetLabel()}
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
<Show when={canDismissWizard()}>
|
<Show when={canDismissWizard()}>
|
||||||
@@ -365,27 +457,39 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
</>
|
</>
|
||||||
</Show>
|
</Show>
|
||||||
|
|
||||||
<Show when={currentStep().id === "mode"}>
|
<Show when={currentStep().id === "mode"}>
|
||||||
<label class={styles.field}>
|
<>
|
||||||
<span class={styles.fieldLabel}>Mode</span>
|
<label class={styles.field}>
|
||||||
<select value={modeForm.mode} onInput={(event): void => setModeForm("mode", event.currentTarget.value)}>
|
<span class={styles.fieldLabel}>Mode</span>
|
||||||
<option value="personal">personal</option>
|
<select value={modeForm.mode} onInput={(event): void => setModeForm("mode", event.currentTarget.value)}>
|
||||||
<option value="organizational">organizational</option>
|
<option value="personal">personal</option>
|
||||||
</select>
|
<option value="organizational">organizational</option>
|
||||||
</label>
|
</select>
|
||||||
</Show>
|
</label>
|
||||||
|
<label class={styles.field}>
|
||||||
|
<span class={styles.fieldLabel}>Server name</span>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={modeForm.name}
|
||||||
|
required
|
||||||
|
onInput={(event): void => setModeForm("name", event.currentTarget.value)}
|
||||||
|
placeholder={bootstrapNamePlaceholder()}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
</>
|
||||||
|
</Show>
|
||||||
|
|
||||||
<Show when={currentStep().id === "admin"}>
|
<Show when={currentStep().id === "admin"}>
|
||||||
<>
|
<>
|
||||||
<label class={styles.field}>
|
<label class={styles.field}>
|
||||||
<span class={styles.fieldLabel}>Display name</span>
|
<span class={styles.fieldLabel}>Display name</span>
|
||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={adminForm.displayName}
|
value={adminForm.displayName}
|
||||||
onInput={(event): void => setAdminForm("displayName", event.currentTarget.value)}
|
onInput={(event): void => setAdminForm("displayName", event.currentTarget.value)}
|
||||||
placeholder="First admin"
|
placeholder="Admin"
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label class={styles.field}>
|
<label class={styles.field}>
|
||||||
<span class={styles.fieldLabel}>Email</span>
|
<span class={styles.fieldLabel}>Email</span>
|
||||||
<input
|
<input
|
||||||
@@ -397,13 +501,16 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
</label>
|
</label>
|
||||||
<label class={styles.field}>
|
<label class={styles.field}>
|
||||||
<span class={styles.fieldLabel}>Password</span>
|
<span class={styles.fieldLabel}>Password</span>
|
||||||
<input
|
<input
|
||||||
type="password"
|
type="password"
|
||||||
value={adminForm.password}
|
value={adminForm.password}
|
||||||
onInput={(event): void => setAdminForm("password", event.currentTarget.value)}
|
onInput={(event): void => setAdminForm("password", event.currentTarget.value)}
|
||||||
placeholder="Temporary for echo testing"
|
placeholder="Create a strong password"
|
||||||
/>
|
/>
|
||||||
</label>
|
<small class={styles.fieldHelp}>
|
||||||
|
Use at least 12 characters with uppercase, lowercase, numbers, and symbols.
|
||||||
|
</small>
|
||||||
|
</label>
|
||||||
</>
|
</>
|
||||||
</Show>
|
</Show>
|
||||||
|
|
||||||
@@ -414,8 +521,9 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={structureForm.departmentName}
|
value={structureForm.departmentName}
|
||||||
|
disabled={modeForm.mode === "personal"}
|
||||||
onInput={(event): void => setStructureForm("departmentName", event.currentTarget.value)}
|
onInput={(event): void => setStructureForm("departmentName", event.currentTarget.value)}
|
||||||
placeholder="Platform"
|
placeholder={organizationalStructureDefaults.departmentName}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label class={styles.field}>
|
<label class={styles.field}>
|
||||||
@@ -423,8 +531,9 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
<input
|
<input
|
||||||
type="text"
|
type="text"
|
||||||
value={structureForm.teamName}
|
value={structureForm.teamName}
|
||||||
|
disabled={modeForm.mode === "personal"}
|
||||||
onInput={(event): void => setStructureForm("teamName", event.currentTarget.value)}
|
onInput={(event): void => setStructureForm("teamName", event.currentTarget.value)}
|
||||||
placeholder="Core"
|
placeholder={organizationalStructureDefaults.teamName}
|
||||||
/>
|
/>
|
||||||
</label>
|
</label>
|
||||||
<label class={styles.field}>
|
<label class={styles.field}>
|
||||||
|
|||||||
@@ -10,6 +10,7 @@ export { default as Folder } from "lucide-solid/icons/folder";
|
|||||||
export { default as Home } from "lucide-solid/icons/house";
|
export { default as Home } from "lucide-solid/icons/house";
|
||||||
export { default as Keyboard } from "lucide-solid/icons/keyboard";
|
export { default as Keyboard } from "lucide-solid/icons/keyboard";
|
||||||
export { default as LayoutGrid } from "lucide-solid/icons/layout-grid";
|
export { default as LayoutGrid } from "lucide-solid/icons/layout-grid";
|
||||||
|
export { default as ListCollapse } from "lucide-solid/icons/list-collapse";
|
||||||
export { default as LogOut } from "lucide-solid/icons/log-out";
|
export { default as LogOut } from "lucide-solid/icons/log-out";
|
||||||
export { default as Moon } from "lucide-solid/icons/moon";
|
export { default as Moon } from "lucide-solid/icons/moon";
|
||||||
export { default as Plus } from "lucide-solid/icons/plus";
|
export { default as Plus } from "lucide-solid/icons/plus";
|
||||||
@@ -18,5 +19,6 @@ export { default as Search } from "lucide-solid/icons/search";
|
|||||||
export { default as Settings } from "lucide-solid/icons/settings";
|
export { default as Settings } from "lucide-solid/icons/settings";
|
||||||
export { default as Shield } from "lucide-solid/icons/shield";
|
export { default as Shield } from "lucide-solid/icons/shield";
|
||||||
export { default as Sun } from "lucide-solid/icons/sun";
|
export { default as Sun } from "lucide-solid/icons/sun";
|
||||||
|
export { default as UnfoldVertical } from "lucide-solid/icons/unfold-vertical";
|
||||||
export { default as User } from "lucide-solid/icons/user";
|
export { default as User } from "lucide-solid/icons/user";
|
||||||
export { default as X } from "lucide-solid/icons/x";
|
export { default as X } from "lucide-solid/icons/x";
|
||||||
|
|||||||
Reference in New Issue
Block a user