Compare commits
34 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| fc5ef23af8 | |||
| c47eae1381 | |||
| bcfe73411c | |||
| 32acf6dc17 | |||
| 6b87e8a1fe | |||
| 3247f28c87 | |||
| 891e8b83ed | |||
| ae1f347549 | |||
| 7e62ff6d9a | |||
| adcc9afe05 | |||
| 24d1e472a2 | |||
| da1b210865 | |||
| eadf630c61 | |||
| 4fb073a1ff | |||
| 9ddfa0c3c7 | |||
| a92e188f84 | |||
| dcf181d640 | |||
| 1a8556df68 | |||
| a5f0c41cba | |||
| 268093d223 | |||
| c64a7b8d44 | |||
| 0b368b09fa | |||
| 212dd1c435 | |||
| 69af324b1b | |||
| 5758074f6f | |||
| 5b9e14b442 | |||
| 618e3e84be | |||
| 2ff7fbd9e7 | |||
| 8a94d83e7e | |||
| 07590f1c4f | |||
| 3c7a73853d | |||
| 9b4f1ce197 | |||
| 5735e3008d | |||
| 626ae02df0 |
@@ -27,3 +27,5 @@ tmp/
|
||||
bin/
|
||||
|
||||
.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
|
||||
}
|
||||
@@ -1,10 +1,16 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
|
||||
"moku-backend/internal/bootstrap"
|
||||
"moku-backend/internal/process"
|
||||
"moku-backend/internal/jobs"
|
||||
"moku-backend/internal/worker"
|
||||
)
|
||||
|
||||
func main() {
|
||||
@@ -18,9 +24,25 @@ func main() {
|
||||
}
|
||||
}()
|
||||
|
||||
app.Logger.Info("worker ready", "service", app.ServiceName, "environment", app.Config.Environment)
|
||||
jobStore := jobs.NewStore(app.Database)
|
||||
runner := worker.NewRunner(jobStore, app.Logger, time.Second)
|
||||
runner.Register(jobs.KindBootstrapStructureMaterialize, func(ctx context.Context, job jobs.Job) error {
|
||||
var payload jobs.BootstrapStructureMaterializePayload
|
||||
if len(job.Payload) > 0 {
|
||||
if err := json.Unmarshal(job.Payload, &payload); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
if err := process.WaitForShutdown(app.ServiceName, app.Logger); err != nil {
|
||||
return bootstrap.NewService(app.Database, app.Config.POSIXRoot).ProcessBootstrapStructureMaterialization(ctx, payload.InstallationID)
|
||||
})
|
||||
|
||||
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM)
|
||||
defer stop()
|
||||
|
||||
app.Logger.Info("worker ready", "service", app.ServiceName, "environment", app.Config.Environment, "pollInterval", time.Second)
|
||||
|
||||
if err := runner.Run(ctx); err != nil {
|
||||
app.Logger.Error("worker stopped", "error", err)
|
||||
log.Fatal(err)
|
||||
}
|
||||
|
||||
@@ -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;
|
||||
@@ -0,0 +1,64 @@
|
||||
-- +goose Up
|
||||
|
||||
CREATE TYPE bootstrap_materialization_status AS ENUM ('not_started', 'pending', 'running', 'succeeded', 'failed');
|
||||
CREATE TYPE background_job_status AS ENUM ('pending', 'running', 'succeeded', 'failed');
|
||||
|
||||
ALTER TABLE installations
|
||||
ADD COLUMN IF NOT EXISTS materialization_status bootstrap_materialization_status NOT NULL DEFAULT 'not_started',
|
||||
ADD COLUMN IF NOT EXISTS materialization_error TEXT,
|
||||
ADD COLUMN IF NOT EXISTS materialization_requested_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS materialization_started_at TIMESTAMPTZ,
|
||||
ADD COLUMN IF NOT EXISTS materialization_finished_at TIMESTAMPTZ;
|
||||
|
||||
UPDATE installations
|
||||
SET
|
||||
materialization_status = CASE
|
||||
WHEN is_bootstrapped THEN 'succeeded'::bootstrap_materialization_status
|
||||
ELSE 'not_started'::bootstrap_materialization_status
|
||||
END,
|
||||
materialization_error = NULL,
|
||||
materialization_requested_at = CASE
|
||||
WHEN is_bootstrapped THEN COALESCE(bootstrapped_at, created_at, NOW())
|
||||
ELSE NULL
|
||||
END,
|
||||
materialization_started_at = CASE
|
||||
WHEN is_bootstrapped THEN COALESCE(bootstrapped_at, created_at, NOW())
|
||||
ELSE NULL
|
||||
END,
|
||||
materialization_finished_at = CASE
|
||||
WHEN is_bootstrapped THEN COALESCE(bootstrapped_at, created_at, NOW())
|
||||
ELSE NULL
|
||||
END
|
||||
WHERE materialization_status = 'not_started'::bootstrap_materialization_status;
|
||||
|
||||
CREATE TABLE IF NOT EXISTS background_jobs (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
kind TEXT NOT NULL,
|
||||
status background_job_status NOT NULL DEFAULT 'pending',
|
||||
payload JSONB NOT NULL DEFAULT '{}'::jsonb,
|
||||
attempts INTEGER NOT NULL DEFAULT 0,
|
||||
max_attempts INTEGER NOT NULL DEFAULT 1,
|
||||
available_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
started_at TIMESTAMPTZ,
|
||||
finished_at TIMESTAMPTZ,
|
||||
last_error TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_background_jobs_claim ON background_jobs (status, available_at, created_at);
|
||||
|
||||
-- +goose Down
|
||||
|
||||
DROP INDEX IF EXISTS idx_background_jobs_claim;
|
||||
DROP TABLE IF EXISTS background_jobs;
|
||||
|
||||
ALTER TABLE installations
|
||||
DROP COLUMN IF EXISTS materialization_finished_at,
|
||||
DROP COLUMN IF EXISTS materialization_started_at,
|
||||
DROP COLUMN IF EXISTS materialization_requested_at,
|
||||
DROP COLUMN IF EXISTS materialization_error,
|
||||
DROP COLUMN IF EXISTS materialization_status;
|
||||
|
||||
DROP TYPE IF EXISTS background_job_status;
|
||||
DROP TYPE IF EXISTS bootstrap_materialization_status;
|
||||
@@ -0,0 +1,159 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
const (
|
||||
materializationNotStarted = "not_started"
|
||||
materializationPending = "pending"
|
||||
materializationRunning = "running"
|
||||
materializationSucceeded = "succeeded"
|
||||
materializationFailed = "failed"
|
||||
)
|
||||
|
||||
type bootstrapStructurePrerequisites struct {
|
||||
installation InstallationRecord
|
||||
admin AdminSummary
|
||||
}
|
||||
|
||||
func (service *Service) GetInstallation(ctx context.Context) (*InstallationRecord, error) {
|
||||
record, err := scanInstallationRecord(service.db.Pool.QueryRow(ctx, `
|
||||
SELECT
|
||||
id::text,
|
||||
name,
|
||||
mode::text,
|
||||
access::text,
|
||||
protocol::text,
|
||||
host,
|
||||
is_bootstrapped,
|
||||
materialization_status::text,
|
||||
materialization_error
|
||||
FROM installations
|
||||
WHERE singleton = TRUE
|
||||
LIMIT 1;
|
||||
`))
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
func loadInstallation(ctx context.Context, tx pgx.Tx) (InstallationRecord, error) {
|
||||
return scanInstallationRecord(tx.QueryRow(ctx, `
|
||||
SELECT
|
||||
id::text,
|
||||
name,
|
||||
mode::text,
|
||||
access::text,
|
||||
protocol::text,
|
||||
host,
|
||||
is_bootstrapped,
|
||||
materialization_status::text,
|
||||
materialization_error
|
||||
FROM installations
|
||||
WHERE singleton = TRUE
|
||||
LIMIT 1;
|
||||
`))
|
||||
}
|
||||
|
||||
func updateBootstrappedInstallation(ctx context.Context, tx pgx.Tx) (InstallationRecord, error) {
|
||||
return scanInstallationRecord(tx.QueryRow(ctx, `
|
||||
UPDATE installations
|
||||
SET
|
||||
is_bootstrapped = TRUE,
|
||||
bootstrapped_at = COALESCE(bootstrapped_at, NOW()),
|
||||
materialization_status = 'pending'::bootstrap_materialization_status,
|
||||
materialization_error = NULL,
|
||||
materialization_requested_at = NOW(),
|
||||
materialization_started_at = NULL,
|
||||
materialization_finished_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE singleton = TRUE
|
||||
RETURNING
|
||||
id::text,
|
||||
name,
|
||||
mode::text,
|
||||
access::text,
|
||||
protocol::text,
|
||||
host,
|
||||
is_bootstrapped,
|
||||
materialization_status::text,
|
||||
materialization_error;
|
||||
`))
|
||||
}
|
||||
|
||||
func scanInstallationRecord(row pgx.Row) (InstallationRecord, error) {
|
||||
var record InstallationRecord
|
||||
if err := row.Scan(
|
||||
&record.ID,
|
||||
&record.Name,
|
||||
&record.Mode,
|
||||
&record.Access,
|
||||
&record.Protocol,
|
||||
&record.Host,
|
||||
&record.IsBootstrapped,
|
||||
&record.MaterializationStatus,
|
||||
&record.MaterializationError,
|
||||
); err != nil {
|
||||
return InstallationRecord{}, err
|
||||
}
|
||||
|
||||
if strings.TrimSpace(record.MaterializationStatus) == "" {
|
||||
record.MaterializationStatus = materializationNotStarted
|
||||
}
|
||||
|
||||
return record, nil
|
||||
}
|
||||
|
||||
func loadPrimaryAdmin(ctx context.Context, tx pgx.Tx) (AdminSummary, error) {
|
||||
var admin AdminSummary
|
||||
if err := tx.QueryRow(ctx, `
|
||||
SELECT id::text, email, display_name
|
||||
FROM users
|
||||
WHERE is_instance_admin = TRUE
|
||||
ORDER BY created_at ASC
|
||||
LIMIT 1;
|
||||
`).Scan(&admin.ID, &admin.Email, &admin.DisplayName); err != nil {
|
||||
return AdminSummary{}, err
|
||||
}
|
||||
|
||||
return admin, nil
|
||||
}
|
||||
|
||||
func (service *Service) loadBootstrapStructurePrerequisites(
|
||||
ctx context.Context,
|
||||
tx pgx.Tx,
|
||||
) (bootstrapStructurePrerequisites, error) {
|
||||
installation, err := loadInstallation(ctx, tx)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return bootstrapStructurePrerequisites{}, ErrInstallationNotConfigured
|
||||
}
|
||||
|
||||
return bootstrapStructurePrerequisites{}, err
|
||||
}
|
||||
|
||||
admin, err := loadPrimaryAdmin(ctx, tx)
|
||||
if err != nil {
|
||||
if errors.Is(err, pgx.ErrNoRows) {
|
||||
return bootstrapStructurePrerequisites{}, ErrAdminNotConfigured
|
||||
}
|
||||
|
||||
return bootstrapStructurePrerequisites{}, err
|
||||
}
|
||||
|
||||
return bootstrapStructurePrerequisites{
|
||||
installation: installation,
|
||||
admin: admin,
|
||||
}, nil
|
||||
}
|
||||
@@ -0,0 +1,180 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
"moku-backend/internal/jobs"
|
||||
"moku-backend/internal/posixproj"
|
||||
)
|
||||
|
||||
func (service *Service) enqueueBootstrapStructureMaterialization(
|
||||
ctx context.Context,
|
||||
installation *InstallationRecord,
|
||||
) error {
|
||||
if installation == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
jobStore := jobs.NewStore(service.db)
|
||||
if _, err := jobStore.Enqueue(ctx, jobs.EnqueueInput{
|
||||
Kind: jobs.KindBootstrapStructureMaterialize,
|
||||
Payload: jobs.BootstrapStructureMaterializePayload{
|
||||
InstallationID: installation.ID,
|
||||
},
|
||||
}); err != nil {
|
||||
failure := fmt.Sprintf("enqueue bootstrap materialization job: %v", err)
|
||||
if markErr := service.markBootstrapMaterializationFailed(ctx, installation.ID, failure); markErr != nil {
|
||||
return errors.Join(err, markErr)
|
||||
}
|
||||
|
||||
// The relational bootstrap write already committed successfully, so keep the
|
||||
// response successful and surface the enqueue problem via materialization state.
|
||||
installation.MaterializationStatus = materializationFailed
|
||||
installation.MaterializationError = &failure
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *Service) ProcessBootstrapStructureMaterialization(ctx context.Context, installationID string) error {
|
||||
trimmedInstallationID := strings.TrimSpace(installationID)
|
||||
if trimmedInstallationID == "" {
|
||||
return ErrInstallationNotConfigured
|
||||
}
|
||||
|
||||
installation, err := service.GetInstallation(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if installation == nil || installation.ID != trimmedInstallationID {
|
||||
return ErrInstallationNotConfigured
|
||||
}
|
||||
|
||||
if err := service.markBootstrapMaterializationRunning(ctx, trimmedInstallationID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if err := service.materializeBootstrapStructure(ctx, *installation); err != nil {
|
||||
failure := strings.TrimSpace(err.Error())
|
||||
if failure == "" {
|
||||
failure = "bootstrap materialization failed"
|
||||
}
|
||||
|
||||
if markErr := service.markBootstrapMaterializationFailed(ctx, trimmedInstallationID, failure); markErr != nil {
|
||||
return errors.Join(err, markErr)
|
||||
}
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
return service.markBootstrapMaterializationSucceeded(ctx, trimmedInstallationID)
|
||||
}
|
||||
|
||||
func (service *Service) materializeBootstrapStructure(ctx context.Context, installation InstallationRecord) error {
|
||||
admin, err := service.GetAdmin(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if admin == nil {
|
||||
return ErrAdminNotConfigured
|
||||
}
|
||||
|
||||
organization, err := service.loadPrimaryOrganization(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if organization == nil {
|
||||
return ErrBootstrapStructureMissing
|
||||
}
|
||||
|
||||
department, err := service.loadPrimaryDepartment(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if department == nil {
|
||||
return ErrBootstrapStructureMissing
|
||||
}
|
||||
|
||||
team, err := service.loadPrimaryTeam(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if team == nil {
|
||||
return ErrBootstrapStructureMissing
|
||||
}
|
||||
|
||||
project, err := service.loadPrimaryProject(ctx)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if project == nil {
|
||||
return ErrBootstrapStructureMissing
|
||||
}
|
||||
|
||||
if err := service.ensureBootstrapPOSIXSkeleton(
|
||||
installation,
|
||||
AdminSummary{ID: admin.ID, Email: admin.Email, DisplayName: admin.DisplayName},
|
||||
namedRecord{ID: organization.ID, Name: organization.Name, Slug: organization.Slug},
|
||||
namedRecord{ID: department.ID, Name: department.Name, Slug: department.Slug},
|
||||
namedRecord{ID: team.ID, Name: team.Name, Slug: team.Slug},
|
||||
namedRecord{ID: project.ID, Name: project.Name, Slug: project.Slug},
|
||||
); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
return service.rebuildProjection(ctx)
|
||||
}
|
||||
|
||||
func (service *Service) rebuildProjection(ctx context.Context) error {
|
||||
if err := posixproj.NewProjector(service.db, service.posixRoot).Rebuild(ctx); err != nil {
|
||||
return fmt.Errorf("rebuild POSIX projection: %w", err)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (service *Service) markBootstrapMaterializationRunning(ctx context.Context, installationID string) error {
|
||||
_, err := service.db.Pool.Exec(ctx, `
|
||||
UPDATE installations
|
||||
SET
|
||||
materialization_status = 'running'::bootstrap_materialization_status,
|
||||
materialization_error = NULL,
|
||||
materialization_started_at = NOW(),
|
||||
materialization_finished_at = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1::uuid;
|
||||
`, strings.TrimSpace(installationID))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (service *Service) markBootstrapMaterializationSucceeded(ctx context.Context, installationID string) error {
|
||||
_, err := service.db.Pool.Exec(ctx, `
|
||||
UPDATE installations
|
||||
SET
|
||||
materialization_status = 'succeeded'::bootstrap_materialization_status,
|
||||
materialization_error = NULL,
|
||||
materialization_finished_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1::uuid;
|
||||
`, strings.TrimSpace(installationID))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (service *Service) markBootstrapMaterializationFailed(ctx context.Context, installationID, failure string) error {
|
||||
_, err := service.db.Pool.Exec(ctx, `
|
||||
UPDATE installations
|
||||
SET
|
||||
materialization_status = 'failed'::bootstrap_materialization_status,
|
||||
materialization_error = $2,
|
||||
materialization_finished_at = NOW(),
|
||||
updated_at = NOW()
|
||||
WHERE id = $1::uuid;
|
||||
`, strings.TrimSpace(installationID), strings.TrimSpace(failure))
|
||||
|
||||
return err
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package bootstrap
|
||||
|
||||
import "context"
|
||||
|
||||
func (service *Service) GetState(ctx context.Context) (BootstrapState, error) {
|
||||
installation, err := service.GetInstallation(ctx)
|
||||
if err != nil {
|
||||
return BootstrapState{}, err
|
||||
}
|
||||
|
||||
admin, err := service.GetAdmin(ctx)
|
||||
if err != nil {
|
||||
return BootstrapState{}, err
|
||||
}
|
||||
|
||||
structure, err := service.GetStructure(ctx)
|
||||
if err != nil {
|
||||
return BootstrapState{}, err
|
||||
}
|
||||
|
||||
return BootstrapState{
|
||||
Installation: installation,
|
||||
Admin: admin,
|
||||
Structure: structure,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) GetAppShellState(ctx context.Context) (AppShellState, error) {
|
||||
installation, err := service.GetInstallation(ctx)
|
||||
if err != nil {
|
||||
return AppShellState{}, err
|
||||
}
|
||||
|
||||
admin, err := service.GetAdmin(ctx)
|
||||
if err != nil {
|
||||
return AppShellState{}, err
|
||||
}
|
||||
|
||||
organizations, err := service.listOrganizations(ctx)
|
||||
if err != nil {
|
||||
return AppShellState{}, err
|
||||
}
|
||||
|
||||
departments, err := service.listDepartments(ctx)
|
||||
if err != nil {
|
||||
return AppShellState{}, err
|
||||
}
|
||||
|
||||
teams, err := service.listTeams(ctx)
|
||||
if err != nil {
|
||||
return AppShellState{}, err
|
||||
}
|
||||
|
||||
projects, err := service.listProjects(ctx)
|
||||
if err != nil {
|
||||
return AppShellState{}, err
|
||||
}
|
||||
|
||||
workspaces, err := service.listWorkspaces(ctx)
|
||||
if err != nil {
|
||||
return AppShellState{}, err
|
||||
}
|
||||
|
||||
return AppShellState{
|
||||
Installation: installation,
|
||||
Admin: admin,
|
||||
Organizations: organizations,
|
||||
Departments: departments,
|
||||
Teams: teams,
|
||||
Projects: projects,
|
||||
Workspaces: workspaces,
|
||||
}, nil
|
||||
}
|
||||
+2319
-163
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,639 @@
|
||||
package bootstrap
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type fakeRow struct {
|
||||
scan func(dest ...any) error
|
||||
}
|
||||
|
||||
func (row fakeRow) Scan(dest ...any) error {
|
||||
return row.scan(dest...)
|
||||
}
|
||||
|
||||
func TestScanInstallationRecordDefaultsMaterializationStatus(t *testing.T) {
|
||||
record, err := scanInstallationRecord(fakeRow{scan: func(dest ...any) error {
|
||||
*(dest[0].(*string)) = "installation-1"
|
||||
*(dest[1].(*string)) = "MangoPig"
|
||||
*(dest[2].(*string)) = "personal"
|
||||
*(dest[3].(*string)) = "local"
|
||||
*(dest[4].(*string)) = "http"
|
||||
*(dest[5].(*string)) = "localhost"
|
||||
*(dest[6].(*bool)) = true
|
||||
*(dest[7].(*string)) = ""
|
||||
*(dest[8].(**string)) = nil
|
||||
return nil
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("scanInstallationRecord: %v", err)
|
||||
}
|
||||
|
||||
if record.MaterializationStatus != materializationNotStarted {
|
||||
t.Fatalf("expected default materialization status %q, got %q", materializationNotStarted, record.MaterializationStatus)
|
||||
}
|
||||
if record.MaterializationError != nil {
|
||||
t.Fatalf("expected nil materialization error, got %#v", record.MaterializationError)
|
||||
}
|
||||
}
|
||||
|
||||
func TestScanInstallationRecordPreservesMaterializationFields(t *testing.T) {
|
||||
failure := "projection rebuild failed"
|
||||
|
||||
record, err := scanInstallationRecord(fakeRow{scan: func(dest ...any) error {
|
||||
*(dest[0].(*string)) = "installation-2"
|
||||
*(dest[1].(*string)) = "MangoPig"
|
||||
*(dest[2].(*string)) = "personal"
|
||||
*(dest[3].(*string)) = "local"
|
||||
*(dest[4].(*string)) = "http"
|
||||
*(dest[5].(*string)) = "localhost"
|
||||
*(dest[6].(*bool)) = true
|
||||
*(dest[7].(*string)) = materializationFailed
|
||||
*(dest[8].(**string)) = &failure
|
||||
return nil
|
||||
}})
|
||||
if err != nil {
|
||||
t.Fatalf("scanInstallationRecord: %v", err)
|
||||
}
|
||||
|
||||
if record.MaterializationStatus != materializationFailed {
|
||||
t.Fatalf("expected materialization status %q, got %q", materializationFailed, record.MaterializationStatus)
|
||||
}
|
||||
if record.MaterializationError == nil || *record.MaterializationError != failure {
|
||||
t.Fatalf("expected materialization error %q, got %#v", failure, record.MaterializationError)
|
||||
}
|
||||
}
|
||||
|
||||
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"),
|
||||
filepath.Join(rootPath, "users", "personals", "personal-ronald", "settings.json"),
|
||||
filepath.Join(rootPath, "users", "personals", "personal-ronald", "layout.json"),
|
||||
filepath.Join(rootPath, "users", "personals", "personal-ronald", "home.json"),
|
||||
filepath.Join(rootPath, "users", "personals", "personal-ronald", "tree"),
|
||||
}
|
||||
|
||||
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"])
|
||||
}
|
||||
|
||||
personalSettings := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "users", "personals", "personal-ronald", "settings.json"))
|
||||
if personalSettings["type"] != "personal" {
|
||||
t.Fatalf("expected personal settings type personal, got %#v", personalSettings["type"])
|
||||
}
|
||||
if personalSettings["name"] != "Ronald" {
|
||||
t.Fatalf("expected personal name Ronald, got %#v", personalSettings["name"])
|
||||
}
|
||||
if personalSettings["slug"] != "ronald" {
|
||||
t.Fatalf("expected personal slug ronald, got %#v", personalSettings["slug"])
|
||||
}
|
||||
|
||||
personalHome := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, "users", "personals", "personal-ronald", "home.json"))
|
||||
if personalHome["type"] != "personal-home" {
|
||||
t.Fatalf("expected personal home type personal-home, got %#v", personalHome["type"])
|
||||
}
|
||||
if personalHome["title"] != "Ronald's Home" {
|
||||
t.Fatalf("expected personal home title Ronald's Home, got %#v", personalHome["title"])
|
||||
}
|
||||
}
|
||||
|
||||
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 strings.TrimSpace(asStringForTest(folderPayload["id"])) == "" {
|
||||
t.Fatalf("expected created folder to have stable id, got %#v", folderPayload["id"])
|
||||
}
|
||||
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 TestRenameProjectHierarchyFolderOnDiskRenamesFolderShape(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, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Design System")
|
||||
if err != nil {
|
||||
t.Fatalf("createProjectHierarchyFolderOnDisk root folder: %v", err)
|
||||
}
|
||||
|
||||
nestedPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", createdPath, "Research")
|
||||
if err != nil {
|
||||
t.Fatalf("createProjectHierarchyFolderOnDisk nested folder: %v", err)
|
||||
}
|
||||
|
||||
previousPath, renamedPath, err := service.renameProjectHierarchyFolderOnDisk("primary-project", createdPath, "Platform Design")
|
||||
if err != nil {
|
||||
t.Fatalf("renameProjectHierarchyFolderOnDisk: %v", err)
|
||||
}
|
||||
if previousPath != createdPath {
|
||||
t.Fatalf("expected previous path %s, got %s", createdPath, previousPath)
|
||||
}
|
||||
if renamedPath != "projects/project-primary-project/children/folder-platform-design" {
|
||||
t.Fatalf("unexpected renamed path: %s", renamedPath)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(rootPath, filepath.FromSlash(createdPath))); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected previous folder path to be gone, got err=%v", err)
|
||||
}
|
||||
|
||||
renamedFolderPath := filepath.Join(rootPath, filepath.FromSlash(renamedPath))
|
||||
if _, err := os.Stat(filepath.Join(renamedFolderPath, "children", filepath.Base(nestedPath))); err != nil {
|
||||
t.Fatalf("expected nested child folder to move with renamed parent: %v", err)
|
||||
}
|
||||
|
||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(renamedFolderPath, "folder.json"))
|
||||
if strings.TrimSpace(asStringForTest(folderPayload["id"])) == "" {
|
||||
t.Fatalf("expected renamed folder to preserve stable id, got %#v", folderPayload["id"])
|
||||
}
|
||||
if folderPayload["name"] != "Platform Design" {
|
||||
t.Fatalf("expected renamed folder name Platform Design, got %#v", folderPayload["name"])
|
||||
}
|
||||
if folderPayload["slug"] != "platform-design" {
|
||||
t.Fatalf("expected renamed folder slug platform-design, got %#v", folderPayload["slug"])
|
||||
}
|
||||
if folderPayload["type"] != "folder" {
|
||||
t.Fatalf("expected renamed folder type folder, got %#v", folderPayload["type"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRenameProjectTreeFolderOnDiskRenamesFolderShape(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, _, err := service.createProjectTreeFolderOnDisk("primary-project", "", "Docs")
|
||||
if err != nil {
|
||||
t.Fatalf("createProjectTreeFolderOnDisk root folder: %v", err)
|
||||
}
|
||||
|
||||
previousPath, renamedPath, err := service.renameProjectTreeFolderOnDisk("primary-project", createdPath, "Specifications")
|
||||
if err != nil {
|
||||
t.Fatalf("renameProjectTreeFolderOnDisk: %v", err)
|
||||
}
|
||||
if previousPath != createdPath {
|
||||
t.Fatalf("expected previous path %s, got %s", createdPath, previousPath)
|
||||
}
|
||||
if renamedPath != "projects/project-primary-project/tree/folder-specifications" {
|
||||
t.Fatalf("unexpected renamed path: %s", renamedPath)
|
||||
}
|
||||
|
||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, filepath.FromSlash(renamedPath), "folder.json"))
|
||||
if folderPayload["name"] != "Specifications" {
|
||||
t.Fatalf("expected renamed folder name Specifications, got %#v", folderPayload["name"])
|
||||
}
|
||||
if folderPayload["slug"] != "specifications" {
|
||||
t.Fatalf("expected renamed folder slug specifications, got %#v", folderPayload["slug"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveProjectHierarchyFolderOnDiskMovesFolderToNewParent(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)
|
||||
}
|
||||
|
||||
designPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Design")
|
||||
if err != nil {
|
||||
t.Fatalf("create design folder: %v", err)
|
||||
}
|
||||
operationsPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Operations")
|
||||
if err != nil {
|
||||
t.Fatalf("create operations folder: %v", err)
|
||||
}
|
||||
researchPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", designPath, "Research")
|
||||
if err != nil {
|
||||
t.Fatalf("create research folder: %v", err)
|
||||
}
|
||||
nestedPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", researchPath, "Interview Notes")
|
||||
if err != nil {
|
||||
t.Fatalf("create nested folder: %v", err)
|
||||
}
|
||||
|
||||
previousPath, movedPath, err := service.moveProjectHierarchyFolderOnDisk("primary-project", researchPath, operationsPath)
|
||||
if err != nil {
|
||||
t.Fatalf("moveProjectHierarchyFolderOnDisk: %v", err)
|
||||
}
|
||||
if previousPath != researchPath {
|
||||
t.Fatalf("expected previous path %s, got %s", researchPath, previousPath)
|
||||
}
|
||||
if movedPath != "projects/project-primary-project/children/folder-operations/children/folder-research" {
|
||||
t.Fatalf("unexpected moved path: %s", movedPath)
|
||||
}
|
||||
|
||||
if _, err := os.Stat(filepath.Join(rootPath, filepath.FromSlash(researchPath))); !os.IsNotExist(err) {
|
||||
t.Fatalf("expected previous folder path to be gone, got err=%v", err)
|
||||
}
|
||||
|
||||
movedFolderPath := filepath.Join(rootPath, filepath.FromSlash(movedPath))
|
||||
if _, err := os.Stat(filepath.Join(movedFolderPath, "children", filepath.Base(nestedPath))); err != nil {
|
||||
t.Fatalf("expected nested child folder to move with moved parent: %v", err)
|
||||
}
|
||||
|
||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(movedFolderPath, "folder.json"))
|
||||
if strings.TrimSpace(asStringForTest(folderPayload["id"])) == "" {
|
||||
t.Fatalf("expected moved folder to preserve stable id, got %#v", folderPayload["id"])
|
||||
}
|
||||
if folderPayload["name"] != "Research" {
|
||||
t.Fatalf("expected moved folder name Research, got %#v", folderPayload["name"])
|
||||
}
|
||||
if folderPayload["slug"] != "research" {
|
||||
t.Fatalf("expected moved folder slug research, got %#v", folderPayload["slug"])
|
||||
}
|
||||
if folderPayload["type"] != "folder" {
|
||||
t.Fatalf("expected moved folder type folder, got %#v", folderPayload["type"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveProjectTreeFolderOnDiskMovesFolderToNewParent(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)
|
||||
}
|
||||
|
||||
docsPath, _, err := service.createProjectTreeFolderOnDisk("primary-project", "", "Docs")
|
||||
if err != nil {
|
||||
t.Fatalf("create docs folder: %v", err)
|
||||
}
|
||||
archivePath, _, err := service.createProjectTreeFolderOnDisk("primary-project", "", "Archive")
|
||||
if err != nil {
|
||||
t.Fatalf("create archive folder: %v", err)
|
||||
}
|
||||
|
||||
previousPath, movedPath, err := service.moveProjectTreeFolderOnDisk("primary-project", docsPath, archivePath)
|
||||
if err != nil {
|
||||
t.Fatalf("moveProjectTreeFolderOnDisk: %v", err)
|
||||
}
|
||||
if previousPath != docsPath {
|
||||
t.Fatalf("expected previous path %s, got %s", docsPath, previousPath)
|
||||
}
|
||||
if movedPath != "projects/project-primary-project/tree/folder-archive/children/folder-docs" {
|
||||
t.Fatalf("unexpected moved path: %s", movedPath)
|
||||
}
|
||||
|
||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(rootPath, filepath.FromSlash(movedPath), "folder.json"))
|
||||
if folderPayload["name"] != "Docs" {
|
||||
t.Fatalf("expected moved folder name Docs, got %#v", folderPayload["name"])
|
||||
}
|
||||
if folderPayload["slug"] != "docs" {
|
||||
t.Fatalf("expected moved folder slug docs, got %#v", folderPayload["slug"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestMoveProjectHierarchyFolderOnDiskRejectsDescendantTarget(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)
|
||||
}
|
||||
|
||||
parentPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", "", "Parent")
|
||||
if err != nil {
|
||||
t.Fatalf("create parent folder: %v", err)
|
||||
}
|
||||
childPath, _, err := service.createProjectHierarchyFolderOnDisk("primary-project", parentPath, "Child")
|
||||
if err != nil {
|
||||
t.Fatalf("create child folder: %v", err)
|
||||
}
|
||||
|
||||
_, _, err = service.moveProjectHierarchyFolderOnDisk("primary-project", parentPath, childPath)
|
||||
if !errors.Is(err, ErrInvalidProjectFolderMove) {
|
||||
t.Fatalf("expected ErrInvalidProjectFolderMove, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBuildProjectHierarchyFolderTreeBuildsNestedStructure(t *testing.T) {
|
||||
rows := []projectHierarchyFolderRow{
|
||||
{ID: "folder-design-id", Path: "projects/project-primary-project/children/folder-design", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Design"},
|
||||
{ID: "folder-research-id", Path: "projects/project-primary-project/children/folder-design/children/folder-research", ParentPath: "projects/project-primary-project/children/folder-design/children", Label: "Research"},
|
||||
{ID: "folder-ops-id", 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)
|
||||
}
|
||||
if folders[0].ID != "folder-design-id" || folders[0].Path != "projects/project-primary-project/children/folder-design" {
|
||||
t.Fatalf("expected design folder to retain stable id/path, got %#v", folders[0])
|
||||
}
|
||||
if folders[0].Children[0].ID != "folder-research-id" || folders[1].ID != "folder-ops-id" {
|
||||
t.Fatalf("expected nested/top-level folder ids to be preserved, got %#v / %#v", folders[0].Children[0], folders[1])
|
||||
}
|
||||
}
|
||||
|
||||
func TestApplyProjectHierarchyFolderOrderingOrdersRootAndChildrenByStableID(t *testing.T) {
|
||||
folders := []ProjectHierarchyFolderRecord{
|
||||
{
|
||||
ID: "folder-design-id",
|
||||
Path: "projects/project-primary-project/children/folder-design",
|
||||
Label: "Design",
|
||||
Children: []ProjectHierarchyFolderRecord{
|
||||
{ID: "folder-research-id", Path: "projects/project-primary-project/children/folder-design/children/folder-research", Label: "Research"},
|
||||
{ID: "folder-assets-id", Path: "projects/project-primary-project/children/folder-design/children/folder-assets", Label: "Assets"},
|
||||
},
|
||||
},
|
||||
{ID: "folder-ops-id", Path: "projects/project-primary-project/children/folder-ops", Label: "Ops"},
|
||||
{ID: "folder-qa-id", Path: "projects/project-primary-project/children/folder-qa", Label: "QA"},
|
||||
}
|
||||
|
||||
ordered := applyProjectHierarchyFolderOrdering(folders, map[string][]string{
|
||||
projectFolderOrderRootKey: {"folder-qa-id", "folder-design-id"},
|
||||
"folder-design-id": {"folder-assets-id", "folder-research-id"},
|
||||
})
|
||||
|
||||
if len(ordered) != 3 {
|
||||
t.Fatalf("expected 3 ordered root folders, got %d", len(ordered))
|
||||
}
|
||||
if ordered[0].ID != "folder-qa-id" || ordered[1].ID != "folder-design-id" || ordered[2].ID != "folder-ops-id" {
|
||||
t.Fatalf("unexpected ordered root ids: %#v", ordered)
|
||||
}
|
||||
if len(ordered[1].Children) != 2 {
|
||||
t.Fatalf("expected design folder children to be preserved, got %#v", ordered[1].Children)
|
||||
}
|
||||
if ordered[1].Children[0].ID != "folder-assets-id" || ordered[1].Children[1].ID != "folder-research-id" {
|
||||
t.Fatalf("unexpected ordered child ids: %#v", ordered[1].Children)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInsertFolderOrderReordersWithinSameParent(t *testing.T) {
|
||||
folderOrder := map[string][]string{
|
||||
projectFolderOrderRootKey: {"folder-a", "folder-b", "folder-c"},
|
||||
}
|
||||
|
||||
insertFolderOrder(folderOrder, "", "folder-c", 0)
|
||||
|
||||
got := folderOrder[projectFolderOrderRootKey]
|
||||
if len(got) != 3 || got[0] != "folder-c" || got[1] != "folder-a" || got[2] != "folder-b" {
|
||||
t.Fatalf("unexpected reordered root children: %#v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func asStringForTest(value any) string {
|
||||
text, _ := value.(string)
|
||||
return text
|
||||
}
|
||||
|
||||
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
|
||||
PostgresURL string
|
||||
ValkeyURL string
|
||||
POSIXRoot string
|
||||
ShutdownTimeout time.Duration
|
||||
}
|
||||
|
||||
@@ -29,6 +30,7 @@ func Load() *Config {
|
||||
APIPort: getEnv("BACKEND_API_PORT", "8081"),
|
||||
PostgresURL: getEnv("DATABASE_URL", "postgres://moku:moku_dev_password@localhost:5432/moku?sslmode=disable"),
|
||||
ValkeyURL: getEnv("VALKEY_URL", "redis://localhost:6379/0"),
|
||||
POSIXRoot: getEnv("POSIX_ROOT", "../POSIX"),
|
||||
ShutdownTimeout: getDurationEnv("BACKEND_SHUTDOWN_TIMEOUT", 10*time.Second),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -341,7 +341,7 @@ func (routes apiRoutes) handleBootstrapStructureStep(w http.ResponseWriter, r *h
|
||||
}
|
||||
|
||||
func (routes apiRoutes) bootstrapService() *bootstrapservice.Service {
|
||||
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) {
|
||||
|
||||
@@ -0,0 +1,717 @@
|
||||
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"`
|
||||
ParentFolderPath string `json:"parentFolderId"`
|
||||
}
|
||||
|
||||
type renameProjectFolderRequest struct {
|
||||
FolderPath string `json:"folderId"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
|
||||
type deleteProjectFolderRequest struct {
|
||||
FolderPath string `json:"folderId"`
|
||||
}
|
||||
|
||||
// Keep the existing JSON contract for the frontend, but use clearer path-vs-stable-ID
|
||||
// names internally so the move flow is easier to reason about.
|
||||
type moveProjectFolderRequest struct {
|
||||
FolderPath string `json:"folderId"`
|
||||
FolderStableID string `json:"folderNodeId"`
|
||||
ParentFolderPath string `json:"parentFolderId"`
|
||||
ParentStableID string `json:"parentNodeId"`
|
||||
TargetIndex int `json:"targetIndex"`
|
||||
}
|
||||
|
||||
type createProjectItemRequest struct {
|
||||
Name string `json:"name"`
|
||||
ParentFolderPath string `json:"parentFolderId"`
|
||||
ItemType string `json:"itemType"`
|
||||
}
|
||||
|
||||
type deleteProjectItemRequest struct {
|
||||
ItemPath string `json:"itemId"`
|
||||
}
|
||||
|
||||
type moveProjectItemRequest struct {
|
||||
ItemPath string `json:"itemId"`
|
||||
ItemStableID string `json:"itemNodeId"`
|
||||
ParentFolderPath string `json:"parentFolderId"`
|
||||
ParentStableID string `json:"parentNodeId"`
|
||||
TargetIndex int `json:"targetIndex"`
|
||||
}
|
||||
|
||||
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.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||
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,
|
||||
ParentFolderPath: payload.ParentFolderPath,
|
||||
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.FolderPath) == "" {
|
||||
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,
|
||||
FolderPath: payload.FolderPath,
|
||||
})
|
||||
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) handleRenameProjectFolder(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 := decodeRenameProjectFolderRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.FolderPath = strings.TrimSpace(payload.FolderPath)
|
||||
payload.Name = strings.TrimSpace(payload.Name)
|
||||
if payload.FolderPath == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||
return
|
||||
}
|
||||
if payload.Name == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().RenameProjectFolder(r.Context(), bootstrapservice.RenameProjectFolderInput{
|
||||
ProjectID: projectID,
|
||||
FolderPath: payload.FolderPath,
|
||||
Name: payload.Name,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectFolderError(w, r, err, "rename")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-folder-rename",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleMoveProjectFolder(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 := decodeMoveProjectFolderRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.FolderPath = strings.TrimSpace(payload.FolderPath)
|
||||
payload.FolderStableID = strings.TrimSpace(payload.FolderStableID)
|
||||
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||
payload.ParentStableID = strings.TrimSpace(payload.ParentStableID)
|
||||
if payload.FolderPath == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().MoveProjectFolder(r.Context(), bootstrapservice.MoveProjectFolderInput{
|
||||
ProjectID: projectID,
|
||||
FolderPath: payload.FolderPath,
|
||||
FolderStableID: payload.FolderStableID,
|
||||
ParentFolderPath: payload.ParentFolderPath,
|
||||
ParentStableID: payload.ParentStableID,
|
||||
TargetIndex: payload.TargetIndex,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectFolderError(w, r, err, "move")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-folder-move",
|
||||
"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) handleProjectTree(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
|
||||
}
|
||||
|
||||
nodes, err := routes.bootstrapService().GetProjectTreeNodes(r.Context(), projectID)
|
||||
if err != nil {
|
||||
routes.writeProjectTreeError(w, r, err, "load")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": map[string]any{
|
||||
"projectId": projectID,
|
||||
"nodes": nodes,
|
||||
},
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
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.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||
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,
|
||||
ParentFolderPath: payload.ParentFolderPath,
|
||||
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.FolderPath) == "" {
|
||||
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,
|
||||
FolderPath: payload.FolderPath,
|
||||
})
|
||||
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) handleRenameProjectTreeFolder(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 := decodeRenameProjectFolderRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.FolderPath = strings.TrimSpace(payload.FolderPath)
|
||||
payload.Name = strings.TrimSpace(payload.Name)
|
||||
if payload.FolderPath == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||
return
|
||||
}
|
||||
if payload.Name == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().RenameProjectTreeFolder(r.Context(), bootstrapservice.RenameProjectFolderInput{
|
||||
ProjectID: projectID,
|
||||
FolderPath: payload.FolderPath,
|
||||
Name: payload.Name,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectFolderError(w, r, err, "rename")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-folder-rename",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleMoveProjectTreeFolder(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 := decodeMoveProjectFolderRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.FolderPath = strings.TrimSpace(payload.FolderPath)
|
||||
payload.FolderStableID = strings.TrimSpace(payload.FolderStableID)
|
||||
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||
payload.ParentStableID = strings.TrimSpace(payload.ParentStableID)
|
||||
if payload.FolderPath == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().MoveProjectTreeFolder(r.Context(), bootstrapservice.MoveProjectFolderInput{
|
||||
ProjectID: projectID,
|
||||
FolderPath: payload.FolderPath,
|
||||
FolderStableID: payload.FolderStableID,
|
||||
ParentFolderPath: payload.ParentFolderPath,
|
||||
ParentStableID: payload.ParentStableID,
|
||||
TargetIndex: payload.TargetIndex,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectFolderError(w, r, err, "move")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-folder-move",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleCreateProjectTreeItem(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 := decodeProjectItemRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.Name = strings.TrimSpace(payload.Name)
|
||||
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||
payload.ItemType = strings.TrimSpace(payload.ItemType)
|
||||
if payload.Name == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Item name is required.")
|
||||
return
|
||||
}
|
||||
if payload.ItemType == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Item type is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().CreateProjectTreeItem(r.Context(), bootstrapservice.CreateProjectItemInput{
|
||||
ProjectID: projectID,
|
||||
ParentFolderPath: payload.ParentFolderPath,
|
||||
Name: payload.Name,
|
||||
ItemType: payload.ItemType,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectTreeError(w, r, err, "persist")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusCreated, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-item-create",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleDeleteProjectTreeItem(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 := decodeDeleteProjectItemRequest(r)
|
||||
if strings.TrimSpace(payload.ItemPath) == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Item ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().DeleteProjectTreeItem(r.Context(), bootstrapservice.DeleteProjectItemInput{
|
||||
ProjectID: projectID,
|
||||
ItemPath: payload.ItemPath,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectTreeError(w, r, err, "delete")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-item-delete",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleMoveProjectTreeItem(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 := decodeMoveProjectItemRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.ItemPath = strings.TrimSpace(payload.ItemPath)
|
||||
payload.ItemStableID = strings.TrimSpace(payload.ItemStableID)
|
||||
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||
payload.ParentStableID = strings.TrimSpace(payload.ParentStableID)
|
||||
if payload.ItemPath == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Item ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().MoveProjectTreeItem(r.Context(), bootstrapservice.MoveProjectItemInput{
|
||||
ProjectID: projectID,
|
||||
ItemPath: payload.ItemPath,
|
||||
ItemStableID: payload.ItemStableID,
|
||||
ParentFolderPath: payload.ParentFolderPath,
|
||||
ParentStableID: payload.ParentStableID,
|
||||
TargetIndex: payload.TargetIndex,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectTreeError(w, r, err, "move")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-item-move",
|
||||
"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())
|
||||
case errors.Is(err, bootstrapservice.ErrInvalidProjectFolderMove):
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", 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 (routes apiRoutes) writeProjectTreeError(w http.ResponseWriter, r *http.Request, err error, operation string) {
|
||||
switch {
|
||||
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound), errors.Is(err, bootstrapservice.ErrProjectItemNotFound):
|
||||
WriteError(w, http.StatusNotFound, RequestIDFromContext(r.Context()), "not_found", err.Error())
|
||||
case errors.Is(err, bootstrapservice.ErrInvalidProjectFolderMove), errors.Is(err, bootstrapservice.ErrInvalidProjectItemMove):
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", err.Error())
|
||||
default:
|
||||
routes.cfg.Logger.Error(operation+" project tree", "error", err, "path", r.URL.Path)
|
||||
message := "Failed to " + operation + " project tree."
|
||||
if routes.cfg.Config.IsDevelopment() {
|
||||
message = message + " " + err.Error()
|
||||
}
|
||||
WriteError(w, http.StatusInternalServerError, RequestIDFromContext(r.Context()), "project_tree_"+operation+"_failed", message)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeMoveProjectFolderRequest(w http.ResponseWriter, r *http.Request) (moveProjectFolderRequest, bool) {
|
||||
var payload moveProjectFolderRequest
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func decodeDeleteProjectFolderRequest(r *http.Request) deleteProjectFolderRequest {
|
||||
return deleteProjectFolderRequest{
|
||||
FolderPath: strings.TrimSpace(r.URL.Query().Get("folderId")),
|
||||
}
|
||||
}
|
||||
|
||||
func decodeDeleteProjectItemRequest(r *http.Request) deleteProjectItemRequest {
|
||||
return deleteProjectItemRequest{
|
||||
ItemPath: strings.TrimSpace(r.URL.Query().Get("itemId")),
|
||||
}
|
||||
}
|
||||
|
||||
func decodeRenameProjectFolderRequest(w http.ResponseWriter, r *http.Request) (renameProjectFolderRequest, bool) {
|
||||
var payload renameProjectFolderRequest
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func decodeProjectItemRequest(w http.ResponseWriter, r *http.Request) (createProjectItemRequest, bool) {
|
||||
var payload createProjectItemRequest
|
||||
|
||||
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
|
||||
}
|
||||
|
||||
func decodeMoveProjectItemRequest(w http.ResponseWriter, r *http.Request) (moveProjectItemRequest, bool) {
|
||||
var payload moveProjectItemRequest
|
||||
|
||||
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,22 @@ func (routes apiRoutes) Register(router chi.Router) {
|
||||
apiRouter.Get("/app-shell", routes.handleAppShellState)
|
||||
apiRouter.Get("/organizations", routes.handleOrganizations)
|
||||
apiRouter.Get("/workspaces", routes.handleWorkspaces)
|
||||
apiRouter.Route("/projects/{projectId}", func(projectRouter chi.Router) {
|
||||
projectRouter.Get("/folders", routes.handleProjectFolders)
|
||||
projectRouter.Post("/folders", routes.handleCreateProjectFolder)
|
||||
projectRouter.Patch("/folders", routes.handleRenameProjectFolder)
|
||||
projectRouter.Patch("/folders/move", routes.handleMoveProjectFolder)
|
||||
projectRouter.Delete("/folders", routes.handleDeleteProjectFolder)
|
||||
projectRouter.Get("/tree", routes.handleProjectTree)
|
||||
projectRouter.Get("/tree/folders", routes.handleProjectTreeFolders)
|
||||
projectRouter.Post("/tree/folders", routes.handleCreateProjectTreeFolder)
|
||||
projectRouter.Patch("/tree/folders", routes.handleRenameProjectTreeFolder)
|
||||
projectRouter.Patch("/tree/folders/move", routes.handleMoveProjectTreeFolder)
|
||||
projectRouter.Delete("/tree/folders", routes.handleDeleteProjectTreeFolder)
|
||||
projectRouter.Post("/tree/items", routes.handleCreateProjectTreeItem)
|
||||
projectRouter.Patch("/tree/items/move", routes.handleMoveProjectTreeItem)
|
||||
projectRouter.Delete("/tree/items", routes.handleDeleteProjectTreeItem)
|
||||
})
|
||||
|
||||
if routes.cfg.Config.IsDevelopment() {
|
||||
apiRouter.Post("/dev/bootstrap/reset", routes.handleDevelopmentBootstrapReset)
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
package jobs
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
|
||||
"moku-backend/internal/database"
|
||||
)
|
||||
|
||||
const (
|
||||
KindBootstrapStructureMaterialize = "bootstrap.structure.materialize"
|
||||
)
|
||||
|
||||
type Status string
|
||||
|
||||
const (
|
||||
StatusPending Status = "pending"
|
||||
StatusRunning Status = "running"
|
||||
StatusSucceeded Status = "succeeded"
|
||||
StatusFailed Status = "failed"
|
||||
)
|
||||
|
||||
type BootstrapStructureMaterializePayload struct {
|
||||
InstallationID string `json:"installationId"`
|
||||
}
|
||||
|
||||
type Job struct {
|
||||
ID string
|
||||
Kind string
|
||||
Status Status
|
||||
Payload json.RawMessage
|
||||
Attempts int
|
||||
MaxAttempts int
|
||||
AvailableAt time.Time
|
||||
StartedAt *time.Time
|
||||
FinishedAt *time.Time
|
||||
LastError *string
|
||||
CreatedAt time.Time
|
||||
UpdatedAt time.Time
|
||||
}
|
||||
|
||||
type EnqueueInput struct {
|
||||
Kind string
|
||||
Payload any
|
||||
AvailableAt time.Time
|
||||
MaxAttempts int
|
||||
}
|
||||
|
||||
type Store struct {
|
||||
db *database.DB
|
||||
}
|
||||
|
||||
func NewStore(db *database.DB) *Store {
|
||||
return &Store{db: db}
|
||||
}
|
||||
|
||||
func (store *Store) Enqueue(ctx context.Context, input EnqueueInput) (Job, error) {
|
||||
payload := json.RawMessage([]byte(`{}`))
|
||||
if input.Payload != nil {
|
||||
encoded, err := json.Marshal(input.Payload)
|
||||
if err != nil {
|
||||
return Job{}, err
|
||||
}
|
||||
payload = encoded
|
||||
}
|
||||
|
||||
availableAt := input.AvailableAt
|
||||
if availableAt.IsZero() {
|
||||
availableAt = time.Now().UTC()
|
||||
}
|
||||
|
||||
maxAttempts := input.MaxAttempts
|
||||
if maxAttempts < 1 {
|
||||
maxAttempts = 1
|
||||
}
|
||||
|
||||
return scanJob(store.db.Pool.QueryRow(ctx, `
|
||||
INSERT INTO background_jobs (kind, status, payload, attempts, max_attempts, available_at)
|
||||
VALUES ($1, 'pending'::background_job_status, $2::jsonb, 0, $3, $4)
|
||||
RETURNING
|
||||
id::text,
|
||||
kind,
|
||||
status::text,
|
||||
payload,
|
||||
attempts,
|
||||
max_attempts,
|
||||
available_at,
|
||||
started_at,
|
||||
finished_at,
|
||||
last_error,
|
||||
created_at,
|
||||
updated_at;
|
||||
`, strings.TrimSpace(input.Kind), payload, maxAttempts, availableAt))
|
||||
}
|
||||
|
||||
func (store *Store) ClaimNext(ctx context.Context) (*Job, error) {
|
||||
job, err := scanJob(store.db.Pool.QueryRow(ctx, `
|
||||
WITH next_job AS (
|
||||
SELECT id
|
||||
FROM background_jobs
|
||||
WHERE status = 'pending'::background_job_status
|
||||
AND available_at <= NOW()
|
||||
ORDER BY created_at ASC
|
||||
LIMIT 1
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
UPDATE background_jobs AS jobs
|
||||
SET
|
||||
status = 'running'::background_job_status,
|
||||
attempts = jobs.attempts + 1,
|
||||
started_at = NOW(),
|
||||
finished_at = NULL,
|
||||
last_error = NULL,
|
||||
updated_at = NOW()
|
||||
FROM next_job
|
||||
WHERE jobs.id = next_job.id
|
||||
RETURNING
|
||||
jobs.id::text,
|
||||
jobs.kind,
|
||||
jobs.status::text,
|
||||
jobs.payload,
|
||||
jobs.attempts,
|
||||
jobs.max_attempts,
|
||||
jobs.available_at,
|
||||
jobs.started_at,
|
||||
jobs.finished_at,
|
||||
jobs.last_error,
|
||||
jobs.created_at,
|
||||
jobs.updated_at;
|
||||
`))
|
||||
if err != nil {
|
||||
if err == pgx.ErrNoRows {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
return nil, err
|
||||
}
|
||||
|
||||
return &job, nil
|
||||
}
|
||||
|
||||
func (store *Store) MarkSucceeded(ctx context.Context, jobID string) error {
|
||||
_, err := store.db.Pool.Exec(ctx, `
|
||||
UPDATE background_jobs
|
||||
SET
|
||||
status = 'succeeded'::background_job_status,
|
||||
finished_at = NOW(),
|
||||
last_error = NULL,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1::uuid;
|
||||
`, strings.TrimSpace(jobID))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func (store *Store) MarkFailed(ctx context.Context, jobID, failure string) error {
|
||||
_, err := store.db.Pool.Exec(ctx, `
|
||||
UPDATE background_jobs
|
||||
SET
|
||||
status = 'failed'::background_job_status,
|
||||
finished_at = NOW(),
|
||||
last_error = $2,
|
||||
updated_at = NOW()
|
||||
WHERE id = $1::uuid;
|
||||
`, strings.TrimSpace(jobID), strings.TrimSpace(failure))
|
||||
|
||||
return err
|
||||
}
|
||||
|
||||
func scanJob(row pgx.Row) (Job, error) {
|
||||
var job Job
|
||||
var status string
|
||||
if err := row.Scan(
|
||||
&job.ID,
|
||||
&job.Kind,
|
||||
&status,
|
||||
&job.Payload,
|
||||
&job.Attempts,
|
||||
&job.MaxAttempts,
|
||||
&job.AvailableAt,
|
||||
&job.StartedAt,
|
||||
&job.FinishedAt,
|
||||
&job.LastError,
|
||||
&job.CreatedAt,
|
||||
&job.UpdatedAt,
|
||||
); err != nil {
|
||||
return Job{}, err
|
||||
}
|
||||
|
||||
job.Status = Status(status)
|
||||
return job, nil
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,124 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"moku-backend/internal/jobs"
|
||||
)
|
||||
|
||||
type JobStore interface {
|
||||
ClaimNext(ctx context.Context) (*jobs.Job, error)
|
||||
MarkSucceeded(ctx context.Context, jobID string) error
|
||||
MarkFailed(ctx context.Context, jobID, failure string) error
|
||||
}
|
||||
|
||||
type Handler func(ctx context.Context, job jobs.Job) error
|
||||
|
||||
type Runner struct {
|
||||
store JobStore
|
||||
logger *slog.Logger
|
||||
pollInterval time.Duration
|
||||
handlers map[string]Handler
|
||||
}
|
||||
|
||||
func NewRunner(store JobStore, logger *slog.Logger, pollInterval time.Duration) *Runner {
|
||||
interval := pollInterval
|
||||
if interval <= 0 {
|
||||
interval = time.Second
|
||||
}
|
||||
|
||||
return &Runner{
|
||||
store: store,
|
||||
logger: logger,
|
||||
pollInterval: interval,
|
||||
handlers: make(map[string]Handler),
|
||||
}
|
||||
}
|
||||
|
||||
func (runner *Runner) Register(kind string, handler Handler) {
|
||||
runner.handlers[strings.TrimSpace(kind)] = handler
|
||||
}
|
||||
|
||||
func (runner *Runner) Run(ctx context.Context) error {
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return nil
|
||||
default:
|
||||
}
|
||||
|
||||
job, err := runner.store.ClaimNext(ctx)
|
||||
if err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
runner.logger.Error("worker claim failed", "error", err)
|
||||
|
||||
if err := waitForNextPoll(ctx, runner.pollInterval); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
if job == nil {
|
||||
if err := waitForNextPoll(ctx, runner.pollInterval); err != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
continue
|
||||
}
|
||||
|
||||
handler, ok := runner.handlers[job.Kind]
|
||||
if !ok {
|
||||
failure := fmt.Sprintf("no handler registered for job kind %q", job.Kind)
|
||||
if err := runner.store.MarkFailed(ctx, job.ID, failure); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runner.logger.Error("worker job failed", "jobID", job.ID, "kind", job.Kind, "error", failure)
|
||||
continue
|
||||
}
|
||||
|
||||
if err := handler(ctx, *job); err != nil {
|
||||
if ctx.Err() != nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
failure := strings.TrimSpace(err.Error())
|
||||
if failure == "" {
|
||||
failure = "job handler returned an empty error"
|
||||
}
|
||||
|
||||
if markErr := runner.store.MarkFailed(ctx, job.ID, failure); markErr != nil {
|
||||
return markErr
|
||||
}
|
||||
|
||||
runner.logger.Error("worker job failed", "jobID", job.ID, "kind", job.Kind, "error", failure)
|
||||
continue
|
||||
}
|
||||
|
||||
if err := runner.store.MarkSucceeded(ctx, job.ID); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
runner.logger.Info("worker job succeeded", "jobID", job.ID, "kind", job.Kind)
|
||||
}
|
||||
}
|
||||
|
||||
func waitForNextPoll(ctx context.Context, interval time.Duration) error {
|
||||
timer := time.NewTimer(interval)
|
||||
defer timer.Stop()
|
||||
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-timer.C:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
package worker
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
"log/slog"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"moku-backend/internal/jobs"
|
||||
)
|
||||
|
||||
func TestRunnerProcessesRegisteredJob(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
store := &fakeJobStore{
|
||||
job: &jobs.Job{
|
||||
ID: "job-1",
|
||||
Kind: jobs.KindBootstrapStructureMaterialize,
|
||||
Payload: []byte(`{"installationId":"installation-1"}`),
|
||||
},
|
||||
cancel: cancel,
|
||||
}
|
||||
runner := NewRunner(store, slog.New(slog.NewTextHandler(io.Discard, nil)), 0)
|
||||
|
||||
handlerCalled := false
|
||||
runner.Register(jobs.KindBootstrapStructureMaterialize, func(ctx context.Context, job jobs.Job) error {
|
||||
handlerCalled = true
|
||||
if job.ID != "job-1" {
|
||||
t.Fatalf("expected job id job-1, got %s", job.ID)
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
if err := runner.Run(ctx); err != nil {
|
||||
t.Fatalf("runner returned error: %v", err)
|
||||
}
|
||||
|
||||
if !handlerCalled {
|
||||
t.Fatal("expected handler to be called")
|
||||
}
|
||||
if len(store.succeeded) != 1 || store.succeeded[0] != "job-1" {
|
||||
t.Fatalf("expected job to be marked succeeded once, got %#v", store.succeeded)
|
||||
}
|
||||
if len(store.failed) != 0 {
|
||||
t.Fatalf("expected no failed jobs, got %#v", store.failed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerMarksFailedWhenHandlerErrors(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
store := &fakeJobStore{
|
||||
job: &jobs.Job{
|
||||
ID: "job-2",
|
||||
Kind: jobs.KindBootstrapStructureMaterialize,
|
||||
},
|
||||
cancel: cancel,
|
||||
}
|
||||
runner := NewRunner(store, slog.New(slog.NewTextHandler(io.Discard, nil)), 0)
|
||||
runner.Register(jobs.KindBootstrapStructureMaterialize, func(ctx context.Context, job jobs.Job) error {
|
||||
return errors.New("boom")
|
||||
})
|
||||
|
||||
if err := runner.Run(ctx); err != nil {
|
||||
t.Fatalf("runner returned error: %v", err)
|
||||
}
|
||||
|
||||
if len(store.succeeded) != 0 {
|
||||
t.Fatalf("expected no succeeded jobs, got %#v", store.succeeded)
|
||||
}
|
||||
if len(store.failed) != 1 {
|
||||
t.Fatalf("expected one failed job, got %#v", store.failed)
|
||||
}
|
||||
if store.failed[0].jobID != "job-2" {
|
||||
t.Fatalf("expected failed job id job-2, got %#v", store.failed[0])
|
||||
}
|
||||
if !strings.Contains(store.failed[0].failure, "boom") {
|
||||
t.Fatalf("expected failure to mention handler error, got %#v", store.failed[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerMarksFailedWhenHandlerMissing(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
store := &fakeJobStore{
|
||||
job: &jobs.Job{
|
||||
ID: "job-3",
|
||||
Kind: "unknown.kind",
|
||||
},
|
||||
cancel: cancel,
|
||||
}
|
||||
runner := NewRunner(store, slog.New(slog.NewTextHandler(io.Discard, nil)), 0)
|
||||
|
||||
if err := runner.Run(ctx); err != nil {
|
||||
t.Fatalf("runner returned error: %v", err)
|
||||
}
|
||||
|
||||
if len(store.failed) != 1 {
|
||||
t.Fatalf("expected one failed job, got %#v", store.failed)
|
||||
}
|
||||
if !strings.Contains(store.failed[0].failure, "no handler registered") {
|
||||
t.Fatalf("expected missing handler failure, got %#v", store.failed[0])
|
||||
}
|
||||
}
|
||||
|
||||
func TestRunnerRetriesClaimErrors(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
defer cancel()
|
||||
|
||||
store := &fakeJobStore{
|
||||
claimErrors: []error{errors.New("relation \"background_jobs\" does not exist")},
|
||||
job: &jobs.Job{
|
||||
ID: "job-4",
|
||||
Kind: jobs.KindBootstrapStructureMaterialize,
|
||||
},
|
||||
cancel: cancel,
|
||||
}
|
||||
runner := NewRunner(store, slog.New(slog.NewTextHandler(io.Discard, nil)), time.Millisecond)
|
||||
|
||||
handlerCalled := false
|
||||
runner.Register(jobs.KindBootstrapStructureMaterialize, func(ctx context.Context, job jobs.Job) error {
|
||||
handlerCalled = true
|
||||
return nil
|
||||
})
|
||||
|
||||
if err := runner.Run(ctx); err != nil {
|
||||
t.Fatalf("runner returned error: %v", err)
|
||||
}
|
||||
|
||||
if !handlerCalled {
|
||||
t.Fatal("expected handler to be called after claim retry")
|
||||
}
|
||||
if store.claimAttempts < 2 {
|
||||
t.Fatalf("expected at least two claim attempts, got %d", store.claimAttempts)
|
||||
}
|
||||
if len(store.succeeded) != 1 || store.succeeded[0] != "job-4" {
|
||||
t.Fatalf("expected job to be marked succeeded once, got %#v", store.succeeded)
|
||||
}
|
||||
if len(store.failed) != 0 {
|
||||
t.Fatalf("expected no failed jobs, got %#v", store.failed)
|
||||
}
|
||||
}
|
||||
|
||||
type fakeJobStore struct {
|
||||
mu sync.Mutex
|
||||
job *jobs.Job
|
||||
claimed bool
|
||||
claimErrors []error
|
||||
claimAttempts int
|
||||
succeeded []string
|
||||
failed []fakeFailure
|
||||
cancel context.CancelFunc
|
||||
}
|
||||
|
||||
type fakeFailure struct {
|
||||
jobID string
|
||||
failure string
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) ClaimNext(ctx context.Context) (*jobs.Job, error) {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
store.claimAttempts++
|
||||
|
||||
if len(store.claimErrors) > 0 {
|
||||
err := store.claimErrors[0]
|
||||
store.claimErrors = store.claimErrors[1:]
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if store.claimed || store.job == nil {
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
store.claimed = true
|
||||
job := *store.job
|
||||
return &job, nil
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) MarkSucceeded(ctx context.Context, jobID string) error {
|
||||
store.mu.Lock()
|
||||
store.succeeded = append(store.succeeded, jobID)
|
||||
store.mu.Unlock()
|
||||
|
||||
if store.cancel != nil {
|
||||
store.cancel()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *fakeJobStore) MarkFailed(ctx context.Context, jobID, failure string) error {
|
||||
store.mu.Lock()
|
||||
store.failed = append(store.failed, fakeFailure{jobID: jobID, failure: failure})
|
||||
store.mu.Unlock()
|
||||
|
||||
if store.cancel != nil {
|
||||
store.cancel()
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -9,18 +9,22 @@ migrate-up:
|
||||
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:
|
||||
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.
|
||||
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.
|
||||
fmt:
|
||||
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:
|
||||
DATABASE_URL: postgres://moku:moku_dev_password@postgres:5432/moku?sslmode=disable
|
||||
VALKEY_URL: redis://valkey:6379/0
|
||||
POSIX_ROOT: /posix
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -13,6 +14,7 @@ x-backend-service: &backend-service
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ../Backend:/app
|
||||
- ../POSIX:/posix
|
||||
- moku_work_backend_go_pkg:/go/pkg/mod
|
||||
- moku_work_backend_go_build:/root/.cache/go-build
|
||||
|
||||
|
||||
@@ -5,11 +5,14 @@ x-backend-service: &backend-service
|
||||
environment:
|
||||
DATABASE_URL: postgres://moku:moku_dev_password@postgres:5432/moku?sslmode=disable
|
||||
VALKEY_URL: redis://valkey:6379/0
|
||||
POSIX_ROOT: /posix
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
valkey:
|
||||
condition: service_healthy
|
||||
volumes:
|
||||
- ../POSIX:/posix
|
||||
|
||||
services:
|
||||
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.
|
||||
+112
-50
@@ -4,87 +4,149 @@
|
||||
|
||||
### 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
|
||||
- [ ] Stack-Decisions
|
||||
- [ ] Proxy
|
||||
- [ ] Local-Prod-NGINX-Proxy
|
||||
- [ ] Static-Frontend-Serving
|
||||
- [ ] First-Request-Web-Loader
|
||||
- [ ] Bootstrap-Document
|
||||
- [ ] Route-Intent-Handoff
|
||||
- [ ] Tiny-First-Paint-Budget
|
||||
- [ ] Dev-and-Prod-Builds
|
||||
- [x] Project-Structure
|
||||
- [x] Stack-Decisions
|
||||
- [x] Proxy
|
||||
- [x] Local-Dev-Vite-Proxy
|
||||
- [x] Local-Prod-NGINX-Proxy
|
||||
- [x] First-Request-Web-Loader
|
||||
- [x] Bootstrap-Document
|
||||
- [x] Route-Intent-Handoff
|
||||
- [x] Tiny-First-Paint-Budget
|
||||
- [x] Dev-and-Prod-Builds
|
||||
- [x] Local-Dev-Just-Commands
|
||||
- [x] Local-Dev-Docker-Compose
|
||||
- [ ] Local-Prod-Just-Commands
|
||||
- [ ] Local-Prod-Docker-Compose
|
||||
- [ ] Frontend-Production-Dockerfile
|
||||
- [ ] Frontend-docker-bake
|
||||
- [x] Local-Prod-Just-Commands
|
||||
- [x] Local-Prod-Docker-Compose
|
||||
- [x] Frontend-Production-Dockerfile
|
||||
- [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
|
||||
- [ ] Session-Flow
|
||||
- [ ] Login-Logout-Foundation
|
||||
- [ ] Authentication
|
||||
- [ ] User
|
||||
- [ ] Base-Model
|
||||
- [ ] Current-User-Implementation
|
||||
- [ ] 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
|
||||
- [ ] Folders-and-Subfolders
|
||||
- [ ] Boards
|
||||
- [ ] Dashboard
|
||||
- [ ] Organization
|
||||
- [ ] Base-Model
|
||||
- [ ] Access-Rules-and-Membership
|
||||
- [ ] Workspace
|
||||
- [ ] Folders-and-Subfolders
|
||||
- [ ] API
|
||||
- [ ] Real-Organizations-Read-Endpoint
|
||||
- [ ] Real-Workspaces-Read-Endpoint
|
||||
- [ ] Tree-Mutation-Endpoints
|
||||
- [ ] Project-Creation-Endpoint
|
||||
|
||||
#### Frontend
|
||||
#### Frontend — Done Foundations
|
||||
|
||||
- [x] Foundation
|
||||
- [x] Typography
|
||||
- [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
|
||||
- [ ] Button
|
||||
- [ ] IconButton
|
||||
- [ ] Input
|
||||
- [ ] Surface
|
||||
- [ ] Nav-Bar
|
||||
- [ ] 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
|
||||
|
||||
**Goal:** First real work surface.
|
||||
|
||||
- [ ] 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
|
||||
**Goal:** Build the plugin app system on top of the base platform. And core app plugins like calendar, board, docs and text channels
|
||||
|
||||
### Version 0.3.0
|
||||
|
||||
**Goal:** Documents and system hardening.
|
||||
|
||||
- [ ] Document
|
||||
- [ ] Accessibility-Rules
|
||||
- [ ] Motion-Foundation
|
||||
**Goal:** Communications and Collaboration (Email System, Reminder System, and Live Collaboration on Documents)
|
||||
|
||||
### Version 0.4.0
|
||||
|
||||
- [ ] Gantt-Board
|
||||
- [ ] Calendar
|
||||
- [ ] Timeline
|
||||
**Goal:** Introduce the POSIX-based file system drive direction with OnlyOffice + S3 blob storage + Per File Versioning
|
||||
|
||||
### 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
|
||||
VALKEY_URL=redis://localhost:6379/0
|
||||
POSIX_ROOT=../POSIX
|
||||
|
||||
VITE_API_BASE_URL=/v1
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Path: Frontend/src/app.tsx
|
||||
|
||||
import type { JSX } from "solid-js";
|
||||
import { AppShell } from "./components/shell/AppShell/AppShell";
|
||||
import { AppShell } from "./components/app-shell/AppShell/AppShell";
|
||||
import "./styles/main.scss";
|
||||
import "./styles/user-overrides.scss";
|
||||
|
||||
|
||||
+19
-10
@@ -1,17 +1,19 @@
|
||||
// Path: Frontend/src/components/shell/AppShell/AppShell.tsx
|
||||
// Path: Frontend/src/components/app-shell/AppShell/AppShell.tsx
|
||||
|
||||
import { createSignal, onCleanup, onMount, Show, type JSX } from "solid-js";
|
||||
import { getDocumentTheme, setTheme, type Theme } from "../../../theme/runtime";
|
||||
import { WorkspaceHome } from "../../workspace-home/WorkspaceHome/WorkspaceHome";
|
||||
import { getDocumentTheme, setTheme, type Theme } from "../../../helper/themeRuntime";
|
||||
import { BootstrapWizard } from "../../bootstrap/BootstrapWizard/BootstrapWizard";
|
||||
import { WorkspaceHome } from "../../workspace-home/WorkspaceHome";
|
||||
import { AppShellDataProvider, useAppShellData } from "../data/app-shell.context";
|
||||
import { LeftRail } from "../LeftRail/LeftRail";
|
||||
import { LeftRail } from "../../workspace-navigation/LeftRail/LeftRail";
|
||||
import { MobileBottomNav } from "../MobileBottomNav/MobileBottomNav";
|
||||
import { MobileWorkspaceBrowser } from "../MobileWorkspaceBrowser/MobileWorkspaceBrowser";
|
||||
import { MobileWorkspaceBrowser } from "../../workspace-navigation/MobileWorkspaceBrowser/MobileWorkspaceBrowser";
|
||||
import { ServerDock } from "../ServerDock/ServerDock";
|
||||
import { NotificationsMenu } from "../TopBar/NotificationsMenu";
|
||||
import { ProfileMenu } from "../TopBar/ProfileMenu";
|
||||
import { TopBar } from "../TopBar/TopBar";
|
||||
import { WorkspaceSidebar } from "../WorkspaceSidebar/WorkspaceSidebar";
|
||||
import { NotificationsMenu } from "../../top-bar/TopBar/NotificationsMenu";
|
||||
import { ProfileMenu } from "../../top-bar/TopBar/ProfileMenu";
|
||||
import { TopBar } from "../../top-bar/TopBar/TopBar";
|
||||
import { WorkspaceTopBar } from "../../workspace-navigation/WorkspaceTopBar/WorkspaceTopBar";
|
||||
import { WorkspaceSidebar } from "../../workspace-navigation/WorkspaceSidebar/WorkspaceSidebar";
|
||||
import styles from "./AppShell.module.scss";
|
||||
|
||||
type MobileWorkspaceView = "notifications" | "profile" | null;
|
||||
@@ -80,6 +82,8 @@ const AppShellContent = (): JSX.Element => {
|
||||
setActiveMobileWorkspaceView(null);
|
||||
};
|
||||
|
||||
const workspaceBreadcrumb = (): string => `${appShellData.activeServer().name} / ${appShellData.activeProject().name} / Home`;
|
||||
|
||||
return (
|
||||
<div class={styles.shell} data-ui="app-shell" data-app-shell-status={appShellData.status()}>
|
||||
<TopBar
|
||||
@@ -124,12 +128,16 @@ const AppShellContent = (): JSX.Element => {
|
||||
<Show
|
||||
when={isMobileViewport() && activeMobileWorkspaceView() !== null}
|
||||
fallback={
|
||||
<WorkspaceHome
|
||||
<>
|
||||
<WorkspaceTopBar
|
||||
sidebarCollapsed={isSidebarCollapsed()}
|
||||
breadcrumb={workspaceBreadcrumb()}
|
||||
onToggleSidebarCollapse={(): void => {
|
||||
setIsSidebarCollapsed((collapsed) => !collapsed);
|
||||
}}
|
||||
/>
|
||||
<WorkspaceHome />
|
||||
</>
|
||||
}
|
||||
>
|
||||
<div class={styles.mobileWorkspaceView} data-slot="mobile-workspace-view" data-view={activeMobileWorkspaceView() ?? undefined}>
|
||||
@@ -162,6 +170,7 @@ const AppShellContent = (): JSX.Element => {
|
||||
setIsMobileWorkspaceBrowserOpen(false);
|
||||
}}
|
||||
/>
|
||||
<BootstrapWizard />
|
||||
</div>
|
||||
);
|
||||
};
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
// Path: Frontend/src/components/shell/MobileBottomNav/MobileBottomNav.tsx
|
||||
// Path: Frontend/src/components/app-shell/MobileBottomNav/MobileBottomNav.tsx
|
||||
|
||||
import { For, type JSX } from "solid-js";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
// Path: Frontend/src/components/shell/ServerDock/ServerDock.tsx
|
||||
// Path: Frontend/src/components/app-shell/ServerDock/ServerDock.tsx
|
||||
|
||||
import { For, Show, type JSX } from "solid-js";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
@@ -0,0 +1,169 @@
|
||||
// Path: Frontend/src/components/app-shell/data/app-shell.builders.ts
|
||||
|
||||
import {
|
||||
activeDepartment as fallbackActiveDepartment,
|
||||
activeProject as fallbackActiveProject,
|
||||
activeServer as fallbackActiveServer,
|
||||
activeUserProfile as fallbackActiveUserProfile,
|
||||
departmentItems as fallbackDepartmentItems,
|
||||
organizationAdminDockActions,
|
||||
personalDockActions,
|
||||
projectItems as fallbackProjectItems,
|
||||
railItems as fallbackRailItems,
|
||||
workspaceTree as fallbackWorkspaceTree,
|
||||
type ActiveDepartment,
|
||||
type ActiveProject,
|
||||
type ActiveServer,
|
||||
type ActiveUserProfile,
|
||||
type DepartmentItem,
|
||||
type ProjectItem,
|
||||
type RailItem,
|
||||
type WorkspaceTreeNode,
|
||||
} from "./shell.data";
|
||||
import type { AppShellPayload } from "./app-shell.types";
|
||||
|
||||
const buildAbbreviation = (name: string, fallback: string): string => {
|
||||
const parts = name
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
|
||||
if (parts.length === 0) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const abbreviation = parts
|
||||
.slice(0, 2)
|
||||
.map((part) => part[0]?.toUpperCase() ?? "")
|
||||
.join("");
|
||||
|
||||
return abbreviation || fallback;
|
||||
};
|
||||
|
||||
export const buildRailItems = (payload: AppShellPayload | null): readonly RailItem[] => {
|
||||
if (!payload?.installation || payload.organizations.length === 0) {
|
||||
return fallbackRailItems;
|
||||
}
|
||||
|
||||
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) => ({
|
||||
id: organization.id,
|
||||
label: serverName || organization.name,
|
||||
abbreviation: buildAbbreviation(serverName || organization.name, kind === "personal" ? "P" : "O"),
|
||||
kind,
|
||||
active: index === 0,
|
||||
}));
|
||||
};
|
||||
|
||||
export const buildActiveServer = (payload: AppShellPayload | null): ActiveServer => {
|
||||
const installation = payload?.installation;
|
||||
const organization = payload?.organizations[0];
|
||||
|
||||
if (!installation || !organization) {
|
||||
return fallbackActiveServer;
|
||||
}
|
||||
|
||||
const kind = installation.mode === "personal" ? "personal" : "organization";
|
||||
const serverName = installation.name || organization.name || installation.host;
|
||||
|
||||
return {
|
||||
id: installation.id,
|
||||
name: serverName || fallbackActiveServer.name,
|
||||
abbreviation: buildAbbreviation(serverName, kind === "personal" ? "P" : "O"),
|
||||
kind,
|
||||
connectedLabel: kind === "organization" ? `${payload?.teams.length ?? 0} connected` : undefined,
|
||||
subtitle: kind === "personal" ? installation.host || payload?.admin?.homeTitle || "Personal home" : undefined,
|
||||
dockActions: kind === "personal" ? personalDockActions : organizationAdminDockActions,
|
||||
};
|
||||
};
|
||||
|
||||
export const buildProjectItems = (payload: AppShellPayload | null): readonly ProjectItem[] => {
|
||||
if (!payload?.projects.length) {
|
||||
return fallbackProjectItems;
|
||||
}
|
||||
|
||||
return payload.projects.map((project, index) => ({
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
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,
|
||||
}));
|
||||
};
|
||||
|
||||
export const buildActiveProject = (payload: AppShellPayload | null): ActiveProject => {
|
||||
const firstProject = payload?.projects[0];
|
||||
|
||||
if (!firstProject) {
|
||||
return fallbackActiveProject;
|
||||
}
|
||||
|
||||
return {
|
||||
id: firstProject.id,
|
||||
name: firstProject.name,
|
||||
};
|
||||
};
|
||||
|
||||
export const buildDepartmentItems = (payload: AppShellPayload | null): readonly DepartmentItem[] => {
|
||||
if (!payload?.departments.length) {
|
||||
return fallbackDepartmentItems;
|
||||
}
|
||||
|
||||
return payload.departments.map((department, index) => ({
|
||||
id: department.id,
|
||||
name: department.name,
|
||||
teams: payload.teams.filter((team) => team.departmentId === department.id).map((team) => team.name),
|
||||
active: index === 0,
|
||||
}));
|
||||
};
|
||||
|
||||
export const buildActiveDepartment = (payload: AppShellPayload | null): ActiveDepartment => {
|
||||
const firstDepartment = payload?.departments[0];
|
||||
|
||||
if (!firstDepartment) {
|
||||
return fallbackActiveDepartment;
|
||||
}
|
||||
|
||||
const firstTeamName = payload?.teams.find((team) => team.departmentId === firstDepartment.id)?.name ?? "";
|
||||
|
||||
return {
|
||||
id: firstDepartment.id,
|
||||
name: firstDepartment.name,
|
||||
teamName: firstTeamName,
|
||||
};
|
||||
};
|
||||
|
||||
export const buildWorkspaceTree = (payload: AppShellPayload | null): readonly WorkspaceTreeNode[] => {
|
||||
if (!payload?.projects.length) {
|
||||
return fallbackWorkspaceTree;
|
||||
}
|
||||
|
||||
return [];
|
||||
};
|
||||
|
||||
export const buildActiveUserProfile = (payload: AppShellPayload | null): ActiveUserProfile => {
|
||||
if (!payload?.admin) {
|
||||
return fallbackActiveUserProfile;
|
||||
}
|
||||
|
||||
const organizationName = payload.installation?.name || payload.organizations[0]?.name || fallbackActiveServer.name;
|
||||
const departmentName = payload.departments[0]?.name;
|
||||
|
||||
return {
|
||||
name: payload.admin.displayName,
|
||||
email: payload.admin.email,
|
||||
roleLabel: payload.admin.isInstanceAdmin ? "Instance admin" : "Member",
|
||||
contextLabel: departmentName ? `${organizationName} • ${departmentName}` : organizationName,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,97 @@
|
||||
// Path: Frontend/src/components/app-shell/data/app-shell.context.tsx
|
||||
|
||||
import {
|
||||
createContext,
|
||||
createMemo,
|
||||
createSignal,
|
||||
onMount,
|
||||
useContext,
|
||||
type JSX,
|
||||
} from "solid-js";
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
import {
|
||||
buildActiveDepartment,
|
||||
buildActiveProject,
|
||||
buildActiveServer,
|
||||
buildActiveUserProfile,
|
||||
buildDepartmentItems,
|
||||
buildProjectItems,
|
||||
buildRailItems,
|
||||
buildWorkspaceTree,
|
||||
} from "./app-shell.builders";
|
||||
import type { AppShellContextValue, AppShellPayload } from "./app-shell.types";
|
||||
import { normalizeAppShellPayload } from "./app-shell.types";
|
||||
|
||||
const AppShellContext = createContext<AppShellContextValue>();
|
||||
|
||||
export const AppShellDataProvider = (props: { children: JSX.Element }): JSX.Element => {
|
||||
const [status, setStatus] = createSignal<"idle" | "loading" | "success" | "error">("idle");
|
||||
const [error, setError] = createSignal("");
|
||||
const [payload, setPayload] = createSignal<AppShellPayload | null>(null);
|
||||
|
||||
const load = async (): Promise<void> => {
|
||||
setStatus("loading");
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const response = await fetch(`${resolveAPIBase()}/app-shell`, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
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) {
|
||||
throw new Error(errorMessage || "Failed to load app shell state.");
|
||||
}
|
||||
|
||||
setPayload(normalizeAppShellPayload(body.data));
|
||||
setStatus("success");
|
||||
} catch (loadError) {
|
||||
setStatus("error");
|
||||
setError(loadError instanceof Error ? loadError.message : "Failed to load app shell state.");
|
||||
}
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
void load();
|
||||
});
|
||||
|
||||
const value: AppShellContextValue = {
|
||||
status,
|
||||
error,
|
||||
installation: createMemo(() => payload()?.installation),
|
||||
railItems: createMemo(() => buildRailItems(payload())),
|
||||
activeServer: createMemo(() => buildActiveServer(payload())),
|
||||
activeProject: createMemo(() => buildActiveProject(payload())),
|
||||
activeDepartment: createMemo(() => buildActiveDepartment(payload())),
|
||||
projectItems: createMemo(() => buildProjectItems(payload())),
|
||||
departmentItems: createMemo(() => buildDepartmentItems(payload())),
|
||||
workspaceTree: createMemo(() => buildWorkspaceTree(payload())),
|
||||
activeUserProfile: createMemo(() => buildActiveUserProfile(payload())),
|
||||
reload: load,
|
||||
};
|
||||
|
||||
return <AppShellContext.Provider value={value}>{props.children}</AppShellContext.Provider>;
|
||||
};
|
||||
|
||||
export const useAppShellData = (): AppShellContextValue => {
|
||||
const context = useContext(AppShellContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useAppShellData must be used within AppShellDataProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
@@ -0,0 +1,130 @@
|
||||
// Path: Frontend/src/components/app-shell/data/app-shell.types.ts
|
||||
|
||||
import type { Accessor } from "solid-js";
|
||||
import type {
|
||||
ActiveDepartment,
|
||||
ActiveProject,
|
||||
ActiveServer,
|
||||
ActiveUserProfile,
|
||||
DepartmentItem,
|
||||
ProjectItem,
|
||||
RailItem,
|
||||
WorkspaceTreeNode,
|
||||
} from "./shell.data";
|
||||
|
||||
export type AppShellInstallation = {
|
||||
id: string;
|
||||
name: string;
|
||||
mode: "personal" | "organizational" | string;
|
||||
access: string;
|
||||
protocol: string;
|
||||
host: string;
|
||||
isBootstrapped: boolean;
|
||||
materializationStatus: "not_started" | "pending" | "running" | "succeeded" | "failed" | string;
|
||||
materializationError?: string;
|
||||
};
|
||||
|
||||
export type AppShellAdmin = {
|
||||
id: string;
|
||||
email: string;
|
||||
displayName: string;
|
||||
isInstanceAdmin: boolean;
|
||||
homeTitle: string;
|
||||
};
|
||||
|
||||
export type AppShellOrganization = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
export type AppShellDepartment = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
export type AppShellTeam = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
departmentId?: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
export type AppShellProject = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
departmentId?: string;
|
||||
teamId?: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
export type AppShellWorkspace = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
kind: "organization" | "department" | "team" | "project" | string;
|
||||
departmentId?: string;
|
||||
teamId?: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
export type AppShellPayload = {
|
||||
installation?: AppShellInstallation;
|
||||
admin?: AppShellAdmin;
|
||||
organizations: AppShellOrganization[];
|
||||
departments: AppShellDepartment[];
|
||||
teams: AppShellTeam[];
|
||||
projects: AppShellProject[];
|
||||
workspaces: AppShellWorkspace[];
|
||||
};
|
||||
|
||||
export type AppShellContextValue = {
|
||||
status: Accessor<"idle" | "loading" | "success" | "error">;
|
||||
error: Accessor<string>;
|
||||
installation: Accessor<AppShellInstallation | undefined>;
|
||||
railItems: Accessor<readonly RailItem[]>;
|
||||
activeServer: Accessor<ActiveServer>;
|
||||
activeProject: Accessor<ActiveProject>;
|
||||
activeDepartment: Accessor<ActiveDepartment>;
|
||||
projectItems: Accessor<readonly ProjectItem[]>;
|
||||
departmentItems: Accessor<readonly DepartmentItem[]>;
|
||||
workspaceTree: Accessor<readonly WorkspaceTreeNode[]>;
|
||||
activeUserProfile: Accessor<ActiveUserProfile>;
|
||||
reload: () => Promise<void>;
|
||||
};
|
||||
|
||||
export const normalizeInstallation = (
|
||||
installation: AppShellInstallation | null | undefined,
|
||||
): AppShellInstallation | undefined => {
|
||||
if (!installation) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const materializationStatus = installation.materializationStatus?.trim()
|
||||
? installation.materializationStatus
|
||||
: installation.isBootstrapped
|
||||
? "succeeded"
|
||||
: "not_started";
|
||||
const materializationError = installation.materializationError?.trim() || undefined;
|
||||
|
||||
return {
|
||||
...installation,
|
||||
materializationStatus,
|
||||
materializationError,
|
||||
};
|
||||
};
|
||||
|
||||
export const normalizeAppShellPayload = (payload: AppShellPayload | null | undefined): AppShellPayload => ({
|
||||
installation: normalizeInstallation(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 : [],
|
||||
});
|
||||
@@ -0,0 +1,174 @@
|
||||
// Path: Frontend/src/components/app-shell/data/shell.context-menu.ts
|
||||
|
||||
import { getWorkspaceCreateActions, getWorkspaceItemTypeDefinition } from "./shell.registry";
|
||||
import type {
|
||||
ActiveProject,
|
||||
ProjectContextMenuAction,
|
||||
ProjectContextMenuSection,
|
||||
ProjectItem,
|
||||
ProjectMenuTarget,
|
||||
WorkspaceContextMenuSection,
|
||||
WorkspaceContextMenuTarget,
|
||||
WorkspaceStaticItem,
|
||||
WorkspaceTreeNode,
|
||||
} from "./shell.types";
|
||||
|
||||
export { getWorkspaceContextMenuEyebrow } from "./shell.registry";
|
||||
|
||||
export const createWorkspaceSurfaceTarget = (workspace: ActiveProject): WorkspaceContextMenuTarget => ({
|
||||
id: `workspace-${workspace.id}`,
|
||||
label: workspace.name,
|
||||
kind: "workspace",
|
||||
});
|
||||
|
||||
export const createWorkspaceStaticTarget = (item: WorkspaceStaticItem): WorkspaceContextMenuTarget => ({
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
kind: item.contextKind,
|
||||
});
|
||||
|
||||
export const createWorkspaceTreeTarget = (node: WorkspaceTreeNode): WorkspaceContextMenuTarget => ({
|
||||
id: node.id,
|
||||
label: node.label,
|
||||
...(node.kind === "folder"
|
||||
? { kind: "folder" as const }
|
||||
: {
|
||||
kind: "item" as const,
|
||||
itemType: node.itemType,
|
||||
}),
|
||||
});
|
||||
|
||||
export const getWorkspaceContextMenuSections = (
|
||||
target: WorkspaceContextMenuTarget,
|
||||
): readonly WorkspaceContextMenuSection[] => {
|
||||
const createActions = getWorkspaceCreateActions();
|
||||
const createSubmenuAction = {
|
||||
id: "create",
|
||||
label: "Create",
|
||||
children: createActions,
|
||||
} as const;
|
||||
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
return [
|
||||
{ id: "create", label: undefined, items: [createSubmenuAction] },
|
||||
{
|
||||
id: "workspace",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: "rename-workspace", label: "Rename workspace", shortcut: { key: "enter" } },
|
||||
{ id: "copy-workspace-link", label: "Copy link", shortcut: { modifiers: ["meta"], key: "c" } },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
case "home":
|
||||
return [
|
||||
{ id: "create", label: undefined, items: [createSubmenuAction] },
|
||||
{ id: "workspace", label: undefined, items: [{ id: "open-home", label: "Open home", shortcut: { key: "enter" } }] },
|
||||
] as const;
|
||||
case "settings":
|
||||
return [
|
||||
{
|
||||
id: "settings",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: "open-settings", label: "Open settings", shortcut: { key: "enter" } },
|
||||
{ id: "copy-settings-link", label: "Copy link", shortcut: { modifiers: ["meta"], key: "c" } },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
case "folder":
|
||||
return [
|
||||
{ id: "open", items: [{ id: "open-folder", label: "Open folder", shortcut: { key: "enter" } }, { id: "rename-folder", label: "Rename", shortcut: { modifiers: ["meta"], key: "r" } }] },
|
||||
{ id: "create", label: undefined, items: [createSubmenuAction] },
|
||||
{
|
||||
id: "organize",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: "move-folder", label: "Move…", shortcut: { modifiers: ["meta"], key: "m" } },
|
||||
{ id: "delete-folder", label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
case "item": {
|
||||
const definition = getWorkspaceItemTypeDefinition(target.itemType);
|
||||
const actionPrefix = definition.actionPrefix;
|
||||
const nounLabel = definition.noun;
|
||||
|
||||
return [
|
||||
{
|
||||
id: `${actionPrefix}-primary`,
|
||||
items: [
|
||||
{ id: `open-${actionPrefix}`, label: `Open ${nounLabel}`, shortcut: { key: "enter" } },
|
||||
{ id: `rename-${actionPrefix}`, label: "Rename", shortcut: { modifiers: ["meta"], key: "r" } },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "organize",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: `move-${actionPrefix}`, label: "Move…", shortcut: { modifiers: ["meta"], key: "m" } },
|
||||
{ id: `delete-${actionPrefix}`, label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const getProjectCreateActions = (): readonly ProjectContextMenuAction[] =>
|
||||
[
|
||||
{ id: "new-project", label: "New project" },
|
||||
{ id: "new-folder", label: "New folder" },
|
||||
] as const;
|
||||
|
||||
const getProjectFolderDangerActions = (): readonly ProjectContextMenuAction[] =>
|
||||
[
|
||||
{ id: "rename-folder", label: "Rename", shortcut: { modifiers: ["meta"], key: "r" } },
|
||||
{ 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;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,6 @@
|
||||
// Path: Frontend/src/components/app-shell/data/shell.data.ts
|
||||
|
||||
export * from "./shell.types";
|
||||
export * from "./shell.registry";
|
||||
export * from "./shell.scaffold";
|
||||
export * from "./shell.context-menu";
|
||||
@@ -0,0 +1,100 @@
|
||||
// Path: Frontend/src/components/app-shell/data/shell.registry.ts
|
||||
|
||||
import { FileText, LayoutGrid } from "../../../lib/icons";
|
||||
import type {
|
||||
ShellIcon,
|
||||
WorkspaceContextMenuAction,
|
||||
WorkspaceContextMenuTarget,
|
||||
WorkspaceItemTypeDefinition,
|
||||
WorkspaceItemTypeId,
|
||||
WorkspaceTreeNode,
|
||||
} from "./shell.types";
|
||||
|
||||
export const firstPartyWorkspaceItemTypes: readonly WorkspaceItemTypeDefinition[] = [
|
||||
{
|
||||
id: "core.doc",
|
||||
label: "Doc",
|
||||
shortLabel: "Doc",
|
||||
icon: FileText,
|
||||
noun: "doc",
|
||||
actionPrefix: "doc",
|
||||
defaultCreateLabel: "New doc",
|
||||
includeInWorkspaceCreate: true,
|
||||
description: "Rich text documents and notes.",
|
||||
},
|
||||
{
|
||||
id: "core.board.kanban",
|
||||
label: "Kanban board",
|
||||
shortLabel: "Board",
|
||||
icon: LayoutGrid,
|
||||
noun: "board",
|
||||
actionPrefix: "board",
|
||||
defaultCreateLabel: "New board",
|
||||
includeInWorkspaceCreate: true,
|
||||
description: "Default board-style workspace item.",
|
||||
},
|
||||
{
|
||||
id: "core.board.list",
|
||||
label: "List board",
|
||||
shortLabel: "Board",
|
||||
icon: LayoutGrid,
|
||||
noun: "board",
|
||||
actionPrefix: "list-board",
|
||||
defaultCreateLabel: "New list board",
|
||||
description: "Alternate first-party board view prepared for the future registry.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const workspaceItemTypeMap = new Map<WorkspaceItemTypeId, WorkspaceItemTypeDefinition>(
|
||||
firstPartyWorkspaceItemTypes.map((definition) => [definition.id, definition]),
|
||||
);
|
||||
|
||||
const createUnknownWorkspaceItemTypeDefinition = (
|
||||
itemType: WorkspaceItemTypeId,
|
||||
): WorkspaceItemTypeDefinition => ({
|
||||
id: itemType,
|
||||
label: "Item",
|
||||
shortLabel: "Item",
|
||||
icon: FileText,
|
||||
noun: "item",
|
||||
actionPrefix: "item",
|
||||
defaultCreateLabel: "New item",
|
||||
description: "Fallback definition for unknown or future workspace item types.",
|
||||
});
|
||||
|
||||
export const getWorkspaceItemTypeDefinition = (itemType: WorkspaceItemTypeId): WorkspaceItemTypeDefinition => {
|
||||
return workspaceItemTypeMap.get(itemType) ?? createUnknownWorkspaceItemTypeDefinition(itemType);
|
||||
};
|
||||
|
||||
export const getWorkspaceNodeIcon = (node: WorkspaceTreeNode): ShellIcon =>
|
||||
node.kind === "folder" ? node.icon : getWorkspaceItemTypeDefinition(node.itemType).icon;
|
||||
|
||||
export const getWorkspaceCreateActions = (): readonly WorkspaceContextMenuAction[] => [
|
||||
{ id: "new-folder", label: "New folder", shortcut: { modifiers: ["alt"], key: "f" } },
|
||||
...firstPartyWorkspaceItemTypes
|
||||
.filter((definition) => definition.includeInWorkspaceCreate)
|
||||
.map((definition) => ({
|
||||
id: `create-${definition.actionPrefix}`,
|
||||
label: definition.defaultCreateLabel,
|
||||
shortcut:
|
||||
definition.id === "core.board.kanban"
|
||||
? ({ modifiers: ["alt"], key: "b" } as const)
|
||||
: definition.id === "core.doc"
|
||||
? ({ modifiers: ["alt"], key: "d" } as const)
|
||||
: undefined,
|
||||
})),
|
||||
];
|
||||
|
||||
export const getWorkspaceContextMenuEyebrow = (target: WorkspaceContextMenuTarget): string => {
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
case "home":
|
||||
return "Workspace";
|
||||
case "settings":
|
||||
return "Configuration";
|
||||
case "folder":
|
||||
return "Folder";
|
||||
case "item":
|
||||
return getWorkspaceItemTypeDefinition(target.itemType).shortLabel;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,222 @@
|
||||
// Path: Frontend/src/components/app-shell/data/shell.scaffold.ts
|
||||
|
||||
import {
|
||||
Bell,
|
||||
CircleHelp,
|
||||
FileText,
|
||||
Folder,
|
||||
Home,
|
||||
Keyboard,
|
||||
LayoutGrid,
|
||||
ListCollapse,
|
||||
LogOut,
|
||||
Repeat,
|
||||
Search,
|
||||
Settings,
|
||||
Shield,
|
||||
User,
|
||||
} from "../../../lib/icons";
|
||||
import type {
|
||||
ActiveDepartment,
|
||||
ActiveProject,
|
||||
ActiveServer,
|
||||
ActiveUserProfile,
|
||||
DepartmentItem,
|
||||
MobileBottomNavItem,
|
||||
NotificationItem,
|
||||
ProfileMenuSection,
|
||||
ProjectItem,
|
||||
RailItem,
|
||||
ServerDockAction,
|
||||
SidebarHeaderAction,
|
||||
TopBarAction,
|
||||
WorkspaceStaticItem,
|
||||
WorkspaceTreeNode,
|
||||
} from "./shell.types";
|
||||
|
||||
export const personalDockActions: readonly ServerDockAction[] = [
|
||||
{ id: "account", label: "Account", icon: User },
|
||||
{ id: "settings", label: "Settings", icon: Settings },
|
||||
] as const;
|
||||
|
||||
export const organizationAdminDockActions: readonly ServerDockAction[] = [
|
||||
{ id: "members", label: "Members", icon: User },
|
||||
{ id: "server", label: "Server", icon: Settings },
|
||||
] as const;
|
||||
|
||||
export const railItems: readonly RailItem[] = [
|
||||
{ id: "personal-server", label: "Personal Server Name", abbreviation: "P", kind: "personal" },
|
||||
{ id: "organization-server", label: "Organization Name", abbreviation: "O", kind: "organization", active: true },
|
||||
{ id: "design-review", label: "Design Review", abbreviation: "D", kind: "organization" },
|
||||
] as const;
|
||||
|
||||
export const activeServer: ActiveServer = {
|
||||
id: "organization-server",
|
||||
name: "Organization Name",
|
||||
abbreviation: "O",
|
||||
kind: "organization",
|
||||
connectedLabel: "12 connected",
|
||||
dockActions: organizationAdminDockActions,
|
||||
};
|
||||
|
||||
export const activeProject: ActiveProject = {
|
||||
id: "general",
|
||||
name: "General",
|
||||
};
|
||||
|
||||
export const activeDepartment: ActiveDepartment = {
|
||||
id: "product",
|
||||
name: "Product",
|
||||
teamName: "Design Systems",
|
||||
};
|
||||
|
||||
export const projectItems: readonly ProjectItem[] = [
|
||||
{
|
||||
id: "general",
|
||||
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;
|
||||
|
||||
export const departmentItems: readonly DepartmentItem[] = [
|
||||
{ id: "product", name: "Product", teams: ["Design Systems", "Research Ops"], active: true },
|
||||
{ id: "engineering", name: "Engineering", teams: ["Platform", "Realtime Collaboration"] },
|
||||
{ id: "operations", name: "Operations", teams: ["Shared Services", "People Ops"] },
|
||||
] as const;
|
||||
|
||||
export const workspaceStaticItems: readonly WorkspaceStaticItem[] = [
|
||||
{ id: "home", label: "Home", icon: Home, active: true, contextKind: "home" },
|
||||
{ id: "workspace-settings", label: "Settings", icon: Settings, contextKind: "settings" },
|
||||
] as const;
|
||||
|
||||
export const workspaceTree: readonly WorkspaceTreeNode[] = [
|
||||
{
|
||||
id: "product-workspace",
|
||||
label: "Product",
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{ id: "roadmap-board", label: "Roadmap", kind: "item", itemType: "core.board.kanban", active: true },
|
||||
{ id: "launch-brief", label: "Launch Brief", kind: "item", itemType: "core.doc" },
|
||||
{
|
||||
id: "research-folder",
|
||||
label: "Research",
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{ id: "interviews-doc", label: "Interviews", kind: "item", itemType: "core.doc" },
|
||||
{ id: "signals-board", label: "Signals", kind: "item", itemType: "core.board.kanban", meta: "2" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "design-folder",
|
||||
label: "Design",
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{ id: "system-doc", label: "Design System", kind: "item", itemType: "core.doc" },
|
||||
{ id: "review-board", label: "Review Queue", kind: "item", itemType: "core.board.kanban" },
|
||||
],
|
||||
},
|
||||
{ id: "general-notes", label: "General Notes", kind: "item", itemType: "core.doc" },
|
||||
] as const;
|
||||
|
||||
export const workspaceSidebarHeaderActions: readonly SidebarHeaderAction[] = [
|
||||
{ id: "search-workspace", label: "Search workspace", icon: Search },
|
||||
{ id: "toggle-workspace-folders", label: "Collapse all folders", icon: ListCollapse },
|
||||
] as const;
|
||||
|
||||
export const mobileBottomNavItems: readonly MobileBottomNavItem[] = [
|
||||
{ id: "home", label: "Home", icon: Home, active: true },
|
||||
{ id: "search", label: "Search", icon: Search },
|
||||
{ id: "browse", label: "Browse", icon: Folder },
|
||||
] as const;
|
||||
|
||||
export const topBarActions: readonly TopBarAction[] = [{ id: "search", label: "Search", icon: Search }] as const;
|
||||
|
||||
export const notificationItems: readonly NotificationItem[] = [
|
||||
{
|
||||
id: "comment-design-systems",
|
||||
title: "New comment on Design Systems",
|
||||
contextLabel: "Product • Review thread updated",
|
||||
timeLabel: "2m ago",
|
||||
unread: true,
|
||||
},
|
||||
{
|
||||
id: "sprint-platform",
|
||||
title: "Sprint updated in Platform",
|
||||
contextLabel: "Engineering • Scope changed",
|
||||
timeLabel: "15m ago",
|
||||
unread: true,
|
||||
},
|
||||
{
|
||||
id: "member-joined",
|
||||
title: "New member joined Operations",
|
||||
contextLabel: "Organization Name • Access granted",
|
||||
timeLabel: "1h ago",
|
||||
},
|
||||
{
|
||||
id: "daily-summary",
|
||||
title: "Daily summary is ready",
|
||||
contextLabel: "General • 8 updates across boards",
|
||||
timeLabel: "Today, 8:00 AM",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const unreadNotificationCount = notificationItems.filter((item) => item.unread).length;
|
||||
|
||||
export const activeUserProfile: ActiveUserProfile = {
|
||||
name: "Demo Account",
|
||||
email: "demo@moku.work",
|
||||
roleLabel: "Founder · Product",
|
||||
contextLabel: "Organization Name • Design Systems",
|
||||
};
|
||||
|
||||
export const profileMenuSections: readonly ProfileMenuSection[] = [
|
||||
{
|
||||
id: "account",
|
||||
items: [
|
||||
{ id: "profile", label: "Profile", icon: User },
|
||||
{ id: "account-settings", label: "Account Settings", icon: Settings },
|
||||
{ id: "notifications", label: "Notifications", icon: Bell },
|
||||
{ id: "security", label: "Security", icon: Shield },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "preferences",
|
||||
items: [
|
||||
{ id: "keyboard-shortcuts", label: "Keyboard Shortcuts", icon: Keyboard },
|
||||
{ id: "theme-preferences", label: "Theme Preferences", icon: Settings },
|
||||
{ id: "help-support", label: "Help & Support", icon: CircleHelp },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "session",
|
||||
items: [
|
||||
{ id: "switch-account", label: "Switch Account", icon: Repeat },
|
||||
{ id: "sign-out", label: "Sign Out", icon: LogOut, tone: "danger" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
@@ -0,0 +1,233 @@
|
||||
// Path: Frontend/src/components/app-shell/data/shell.types.ts
|
||||
|
||||
import type { Component } from "solid-js";
|
||||
|
||||
export type ShellIconProps = {
|
||||
class?: string;
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
};
|
||||
|
||||
export type ShellIcon = Component<ShellIconProps>;
|
||||
|
||||
export type RailItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
abbreviation: string;
|
||||
kind: "personal" | "organization";
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type ServerDockAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
};
|
||||
|
||||
export type ActiveServer = {
|
||||
id: string;
|
||||
name: string;
|
||||
abbreviation: string;
|
||||
kind: "personal" | "organization";
|
||||
connectedLabel?: string;
|
||||
subtitle?: string;
|
||||
dockActions: readonly ServerDockAction[];
|
||||
};
|
||||
|
||||
export type ActiveProject = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type ActiveDepartment = {
|
||||
id: string;
|
||||
name: string;
|
||||
teamName: string;
|
||||
};
|
||||
|
||||
export type DepartmentItem = {
|
||||
id: string;
|
||||
name: string;
|
||||
teams: readonly string[];
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type ProjectItem = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
groupLabel?: string;
|
||||
parentLabel?: string;
|
||||
meta?: string;
|
||||
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 = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
active?: boolean;
|
||||
meta?: string;
|
||||
};
|
||||
|
||||
export type WorkspaceStaticKind = "workspace" | "home" | "settings";
|
||||
|
||||
export type WorkspaceItemTypeId = string;
|
||||
|
||||
export type WorkspaceStaticItem = SidebarItem & {
|
||||
contextKind: WorkspaceStaticKind;
|
||||
};
|
||||
|
||||
export type WorkspaceFolderNode = {
|
||||
id: string;
|
||||
path?: string;
|
||||
label: string;
|
||||
kind: "folder";
|
||||
icon: ShellIcon;
|
||||
active?: boolean;
|
||||
meta?: string;
|
||||
children?: readonly WorkspaceTreeNode[];
|
||||
};
|
||||
|
||||
export type WorkspaceItemNode = {
|
||||
id: string;
|
||||
path?: string;
|
||||
label: string;
|
||||
kind: "item";
|
||||
itemType: WorkspaceItemTypeId;
|
||||
active?: boolean;
|
||||
meta?: string;
|
||||
children?: undefined;
|
||||
};
|
||||
|
||||
export type WorkspaceTreeNode = WorkspaceFolderNode | WorkspaceItemNode;
|
||||
|
||||
export type WorkspaceItemTypeDefinition = {
|
||||
id: WorkspaceItemTypeId;
|
||||
label: string;
|
||||
shortLabel: string;
|
||||
icon: ShellIcon;
|
||||
noun: string;
|
||||
actionPrefix: string;
|
||||
defaultCreateLabel: string;
|
||||
includeInWorkspaceCreate?: boolean;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
export type SidebarHeaderAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
};
|
||||
|
||||
export type TopBarAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
};
|
||||
|
||||
export type MobileBottomNavItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type WorkspaceContextMenuTarget =
|
||||
| {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: WorkspaceStaticKind;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: "folder";
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: "item";
|
||||
itemType: WorkspaceItemTypeId;
|
||||
};
|
||||
|
||||
export type WorkspaceContextMenuAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
tone?: "default" | "danger";
|
||||
shortcut?: WorkspaceContextMenuShortcut;
|
||||
children?: readonly WorkspaceContextMenuAction[];
|
||||
};
|
||||
|
||||
export type WorkspaceContextMenuShortcutModifier = "meta" | "alt" | "shift";
|
||||
|
||||
export type WorkspaceContextMenuShortcutKey = "b" | "c" | "d" | "delete" | "enter" | "f" | "m" | "r";
|
||||
|
||||
export type WorkspaceContextMenuShortcut = {
|
||||
modifiers?: readonly WorkspaceContextMenuShortcutModifier[];
|
||||
key: WorkspaceContextMenuShortcutKey;
|
||||
};
|
||||
|
||||
export type WorkspaceContextMenuSection = {
|
||||
id: string;
|
||||
label?: string;
|
||||
items: readonly WorkspaceContextMenuAction[];
|
||||
};
|
||||
|
||||
export type NotificationItem = {
|
||||
id: string;
|
||||
title: string;
|
||||
contextLabel: string;
|
||||
timeLabel: string;
|
||||
unread?: boolean;
|
||||
};
|
||||
|
||||
export type ProfileMenuAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
tone?: "default" | "danger";
|
||||
};
|
||||
|
||||
export type ProfileMenuSection = {
|
||||
id: string;
|
||||
items: readonly ProfileMenuAction[];
|
||||
};
|
||||
|
||||
export type ActiveUserProfile = {
|
||||
name: string;
|
||||
email: string;
|
||||
roleLabel: string;
|
||||
contextLabel: string;
|
||||
};
|
||||
@@ -0,0 +1,173 @@
|
||||
// Path: Frontend/src/components/bootstrap/BootstrapWizard/BootstrapWizard.data.ts
|
||||
|
||||
export type BootstrapStepKey = "persona" | "instance" | "mode" | "admin" | "structure";
|
||||
|
||||
export type BootstrapStepDefinition = {
|
||||
id: BootstrapStepKey;
|
||||
title: string;
|
||||
buttonLabel: string;
|
||||
};
|
||||
|
||||
export type InstanceForm = {
|
||||
protocol: "http" | "https";
|
||||
access: "local" | "remote";
|
||||
host: string;
|
||||
};
|
||||
|
||||
export type ModeForm = {
|
||||
mode: "personal" | "organizational";
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type AdminForm = {
|
||||
displayName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
export type StructureForm = {
|
||||
departmentName: string;
|
||||
teamName: string;
|
||||
projectName: string;
|
||||
};
|
||||
|
||||
export type BootstrapPersona = "personal" | "enthusiast" | "team" | "organization";
|
||||
|
||||
export type BootstrapPersonaDefinition = {
|
||||
id: BootstrapPersona;
|
||||
title: string;
|
||||
isAvailable: boolean;
|
||||
bestFor: string;
|
||||
bullets: readonly string[];
|
||||
defaults: {
|
||||
protocol: InstanceForm["protocol"];
|
||||
access: InstanceForm["access"];
|
||||
host: string;
|
||||
mode: ModeForm["mode"];
|
||||
namePlaceholder: string;
|
||||
departmentName: string;
|
||||
teamName: string;
|
||||
projectName: string;
|
||||
};
|
||||
};
|
||||
|
||||
export const bootstrapStepDefinitions: readonly BootstrapStepDefinition[] = [
|
||||
{ id: "persona", title: "What are you setting up your server for?", buttonLabel: "Continue" },
|
||||
{ id: "instance", title: "Connection details", buttonLabel: "Save and continue" },
|
||||
{ id: "mode", title: "Server identity", buttonLabel: "Save and continue" },
|
||||
{ id: "admin", title: "Admin account", buttonLabel: "Save and continue" },
|
||||
{ id: "structure", title: "Initial structure", buttonLabel: "Submit" },
|
||||
];
|
||||
|
||||
export const defaultInstanceForm: InstanceForm = {
|
||||
protocol: "http",
|
||||
access: "local",
|
||||
host: "localhost",
|
||||
};
|
||||
|
||||
export const defaultModeForm: ModeForm = {
|
||||
mode: "personal",
|
||||
name: "",
|
||||
};
|
||||
|
||||
export const defaultAdminForm: AdminForm = {
|
||||
displayName: "Admin",
|
||||
email: "admin@example.com",
|
||||
password: "",
|
||||
};
|
||||
|
||||
export const personalStructureDefaults = {
|
||||
departmentName: "Default",
|
||||
teamName: "Personal",
|
||||
};
|
||||
|
||||
export const organizationalStructureDefaults = {
|
||||
departmentName: "Department",
|
||||
teamName: "Team",
|
||||
};
|
||||
|
||||
export const defaultStructureForm: StructureForm = {
|
||||
...personalStructureDefaults,
|
||||
projectName: "Project",
|
||||
};
|
||||
|
||||
export const bootstrapPersonaDefinitions: readonly BootstrapPersonaDefinition[] = [
|
||||
{
|
||||
id: "personal",
|
||||
title: "Personal",
|
||||
isAvailable: true,
|
||||
bestFor: "Best for low maintenance, personal use",
|
||||
bullets: ["Preconfigured for personal use", "Low setup time", "Easy to manage"],
|
||||
defaults: {
|
||||
protocol: "http",
|
||||
access: "local",
|
||||
host: "localhost",
|
||||
mode: "personal",
|
||||
namePlaceholder: "Personal Server",
|
||||
departmentName: "Default",
|
||||
teamName: "Personal",
|
||||
projectName: "Project",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "enthusiast",
|
||||
title: "Self Hosted Enthusiast",
|
||||
isAvailable: true,
|
||||
bestFor: "Best for people who want to customize their server",
|
||||
bullets: ["Networking knowledge", "Comfortable with tinkering", "Willing to troubleshoot issues"],
|
||||
defaults: {
|
||||
protocol: "https",
|
||||
access: "remote",
|
||||
host: "moku.local",
|
||||
mode: "personal",
|
||||
namePlaceholder: "Personal Server",
|
||||
departmentName: "Default",
|
||||
teamName: "Personal",
|
||||
projectName: "Project",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "team",
|
||||
title: "Team",
|
||||
isAvailable: true,
|
||||
bestFor: "Best for low maintenance but for small team",
|
||||
bullets: ["Built-in collaboration with low setup time", "Keeps the shared structure simple", "Good for a small product, design, or delivery team"],
|
||||
defaults: {
|
||||
protocol: "http",
|
||||
access: "local",
|
||||
host: "localhost",
|
||||
mode: "organizational",
|
||||
namePlaceholder: "Team Server",
|
||||
departmentName: "Default",
|
||||
teamName: "Core Team",
|
||||
projectName: "Project",
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "organization",
|
||||
title: "Organization",
|
||||
isAvailable: true,
|
||||
bestFor: "Best for multiple teams and shared ownership",
|
||||
bullets: ["SME to Organization", "Fine grained access control", "Better fit for teams with multiple departments"],
|
||||
defaults: {
|
||||
protocol: "https",
|
||||
access: "remote",
|
||||
host: "workspace.example.com",
|
||||
mode: "organizational",
|
||||
namePlaceholder: "Organization server name",
|
||||
departmentName: "Operations",
|
||||
teamName: "Platform Team",
|
||||
projectName: "Moku",
|
||||
},
|
||||
},
|
||||
];
|
||||
|
||||
export const workspaceHomeFieldTooltips = {
|
||||
protocol: "Usually people use http for a local-only setup and https when the server will be reached over a domain or reverse proxy.",
|
||||
access: "Usually people use local when Moku is only reached on the same machine or LAN, and remote when they plan to reach it from another network or public domain.",
|
||||
host: "Examples people usually set here are localhost, moku.local, or a real domain like workspace.example.com depending on how they plan to reach the server.",
|
||||
serverName: "This is the friendly name people usually give the server itself, for example Personal Server, Ronald's Server, Homelab, Studio, or Workspace.",
|
||||
department: "Departments are the highest-level grouping for work. People usually use names like Default, Operations, Product, Design, or Engineering.",
|
||||
team: "Teams sit inside a department. Common examples are Personal, Platform Team, Core Team, Delivery, or Design Systems.",
|
||||
project: "Projects are the workspace or initiative people work inside. Common examples are Project, Shared Workspace, Moku, Client Portal, or Website Redesign.",
|
||||
} as const;
|
||||
@@ -0,0 +1,469 @@
|
||||
// Path: Frontend/src/components/bootstrap/BootstrapWizard/BootstrapWizard.hook.ts
|
||||
|
||||
import { createEffect, createMemo, createSignal, onCleanup } from "solid-js";
|
||||
import { createStore } from "solid-js/store";
|
||||
import {
|
||||
bootstrapPersonaDefinitions,
|
||||
bootstrapStepDefinitions,
|
||||
defaultAdminForm,
|
||||
defaultInstanceForm,
|
||||
defaultModeForm,
|
||||
defaultStructureForm,
|
||||
organizationalStructureDefaults,
|
||||
personalStructureDefaults,
|
||||
type AdminForm,
|
||||
type BootstrapPersona,
|
||||
type BootstrapPersonaDefinition,
|
||||
type BootstrapStepDefinition,
|
||||
type BootstrapStepKey,
|
||||
type InstanceForm,
|
||||
type ModeForm,
|
||||
type StructureForm,
|
||||
} from "./BootstrapWizard.data";
|
||||
import { submitBootstrapStepRequest } from "./bootstrapWizard.api";
|
||||
|
||||
type AppShellBootstrapAdapter = {
|
||||
installation: () => { isBootstrapped?: boolean; materializationStatus?: string; materializationError?: string } | undefined;
|
||||
status: () => string;
|
||||
reload: () => Promise<void>;
|
||||
};
|
||||
|
||||
export type BootstrapSubmissionState = {
|
||||
status: "idle" | "submitting" | "success" | "error";
|
||||
error: string;
|
||||
};
|
||||
|
||||
export type MaterializationState = "not_started" | "pending" | "running" | "succeeded" | "failed";
|
||||
|
||||
export type FieldTooltipState = {
|
||||
text: string;
|
||||
left: number;
|
||||
top: number;
|
||||
placement: "top" | "bottom";
|
||||
};
|
||||
|
||||
const initialSubmissionState = (): BootstrapSubmissionState => ({
|
||||
status: "idle",
|
||||
error: "",
|
||||
});
|
||||
|
||||
const materializationPollIntervalMs = 2000;
|
||||
|
||||
export const useBootstrapWizard = (appShellData: AppShellBootstrapAdapter) => {
|
||||
const [instanceForm, setInstanceForm] = createStore<InstanceForm>({ ...defaultInstanceForm });
|
||||
const [modeForm, setModeForm] = createStore<ModeForm>({ ...defaultModeForm });
|
||||
const [adminForm, setAdminForm] = createStore<AdminForm>({ ...defaultAdminForm });
|
||||
const [structureForm, setStructureForm] = createStore<StructureForm>({ ...defaultStructureForm });
|
||||
const [selectedPersona, setSelectedPersona] = createSignal<BootstrapPersona>("enthusiast");
|
||||
const [hasChosenPersona, setHasChosenPersona] = createSignal(false);
|
||||
const [stepState, setStepState] = createStore<Record<BootstrapStepKey, BootstrapSubmissionState>>({
|
||||
persona: initialSubmissionState(),
|
||||
instance: initialSubmissionState(),
|
||||
mode: initialSubmissionState(),
|
||||
admin: initialSubmissionState(),
|
||||
structure: initialSubmissionState(),
|
||||
});
|
||||
const [isBootstrapStateResolved, setIsBootstrapStateResolved] = createSignal(false);
|
||||
const [isBootstrapComplete, setIsBootstrapComplete] = createSignal(false);
|
||||
const [isWizardOpen, setIsWizardOpen] = createSignal(false);
|
||||
const [isFinishingBootstrapFlow, setIsFinishingBootstrapFlow] = createSignal(false);
|
||||
const [currentStepIndex, setCurrentStepIndex] = createSignal(0);
|
||||
const [fieldTooltip, setFieldTooltip] = createSignal<FieldTooltipState | null>(null);
|
||||
|
||||
const installation = createMemo(() => appShellData.installation());
|
||||
const materializationState = createMemo<MaterializationState>(() => {
|
||||
const status = installation()?.materializationStatus;
|
||||
|
||||
switch (status) {
|
||||
case "pending":
|
||||
case "running":
|
||||
case "failed":
|
||||
case "succeeded":
|
||||
case "not_started":
|
||||
return status;
|
||||
default:
|
||||
return installation()?.isBootstrapped ? "succeeded" : "not_started";
|
||||
}
|
||||
});
|
||||
const isBootstrapPersisted = createMemo(() => installation()?.isBootstrapped ?? false);
|
||||
const isMaterializationInFlight = createMemo(() => materializationState() === "pending" || materializationState() === "running");
|
||||
const hasMaterializationFailed = createMemo(() => materializationState() === "failed");
|
||||
const showBootstrapFinishingState = createMemo(() => isFinishingBootstrapFlow() && (isMaterializationInFlight() || hasMaterializationFailed()));
|
||||
const materializationStatusLabel = createMemo(() => {
|
||||
switch (materializationState()) {
|
||||
case "pending":
|
||||
return "Materialization queued";
|
||||
case "running":
|
||||
return "Materialization running";
|
||||
case "failed":
|
||||
return "Materialization failed";
|
||||
case "succeeded":
|
||||
return "Ready";
|
||||
default:
|
||||
return "Not started";
|
||||
}
|
||||
});
|
||||
const materializationMessage = createMemo(() => {
|
||||
if (isMaterializationInFlight()) {
|
||||
return "Your bootstrap is saved. The worker is still creating the POSIX skeleton and rebuilding the app shell index.";
|
||||
}
|
||||
|
||||
if (hasMaterializationFailed()) {
|
||||
return installation()?.materializationError || "Bootstrap saved, but background materialization did not finish cleanly.";
|
||||
}
|
||||
|
||||
return "";
|
||||
});
|
||||
const personaDefinition = createMemo<BootstrapPersonaDefinition>(() => bootstrapPersonaDefinitions.find((persona) => persona.id === selectedPersona()) ?? bootstrapPersonaDefinitions[0]!);
|
||||
const selectedPersonaIsAvailable = createMemo(() => personaDefinition().isAvailable);
|
||||
const usesCondensedBootstrapFlow = createMemo(() => selectedPersona() === "personal" || selectedPersona() === "team");
|
||||
const activeBootstrapSteps = createMemo<readonly BootstrapStepDefinition[]>(() => {
|
||||
if (usesCondensedBootstrapFlow()) {
|
||||
return [bootstrapStepDefinitions[0]!, bootstrapStepDefinitions[2]!, bootstrapStepDefinitions[3]!];
|
||||
}
|
||||
|
||||
return bootstrapStepDefinitions;
|
||||
});
|
||||
const activeWizardSteps = createMemo(() => activeBootstrapSteps().filter((step) => step.id !== "persona"));
|
||||
|
||||
createEffect(() => {
|
||||
const defaults = personaDefinition().defaults;
|
||||
|
||||
setInstanceForm({
|
||||
protocol: defaults.protocol,
|
||||
access: defaults.access,
|
||||
host: defaults.host,
|
||||
});
|
||||
setModeForm("mode", defaults.mode);
|
||||
setStructureForm({
|
||||
departmentName: defaults.departmentName,
|
||||
teamName: defaults.teamName,
|
||||
projectName: defaults.projectName,
|
||||
});
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
if (modeForm.mode === "personal") {
|
||||
setStructureForm("departmentName", personalStructureDefaults.departmentName);
|
||||
setStructureForm("teamName", personalStructureDefaults.teamName);
|
||||
return;
|
||||
}
|
||||
|
||||
if (structureForm.departmentName === personalStructureDefaults.departmentName) {
|
||||
setStructureForm("departmentName", organizationalStructureDefaults.departmentName);
|
||||
}
|
||||
|
||||
if (structureForm.teamName === personalStructureDefaults.teamName) {
|
||||
setStructureForm("teamName", organizationalStructureDefaults.teamName);
|
||||
}
|
||||
});
|
||||
|
||||
const resetWizardState = (): void => {
|
||||
setSelectedPersona("enthusiast");
|
||||
setHasChosenPersona(false);
|
||||
setInstanceForm({ ...defaultInstanceForm });
|
||||
setModeForm({ ...defaultModeForm });
|
||||
setAdminForm({ ...defaultAdminForm });
|
||||
setStructureForm({ ...defaultStructureForm });
|
||||
setStepState({
|
||||
persona: initialSubmissionState(),
|
||||
instance: initialSubmissionState(),
|
||||
mode: initialSubmissionState(),
|
||||
admin: initialSubmissionState(),
|
||||
structure: initialSubmissionState(),
|
||||
});
|
||||
setCurrentStepIndex(0);
|
||||
setIsFinishingBootstrapFlow(false);
|
||||
};
|
||||
|
||||
createEffect(() => {
|
||||
const shellStatus = appShellData.status();
|
||||
|
||||
if (shellStatus === "idle" || shellStatus === "loading") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shellStatus !== "success") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isBootstrapPersisted()) {
|
||||
setIsFinishingBootstrapFlow(false);
|
||||
resetWizardState();
|
||||
}
|
||||
|
||||
setIsBootstrapComplete(isBootstrapPersisted() && !isMaterializationInFlight());
|
||||
setIsWizardOpen(!isBootstrapPersisted() || showBootstrapFinishingState());
|
||||
setIsBootstrapStateResolved(true);
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
if (!isFinishingBootstrapFlow()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isMaterializationInFlight() || hasMaterializationFailed()) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsFinishingBootstrapFlow(false);
|
||||
setIsWizardOpen(false);
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
if (!isBootstrapPersisted() || !isMaterializationInFlight()) {
|
||||
return;
|
||||
}
|
||||
|
||||
let cancelled = false;
|
||||
let timeoutId: number | undefined;
|
||||
|
||||
const scheduleReload = (): void => {
|
||||
timeoutId = window.setTimeout(async () => {
|
||||
if (cancelled) {
|
||||
return;
|
||||
}
|
||||
|
||||
await appShellData.reload();
|
||||
|
||||
if (!cancelled && isBootstrapPersisted() && isMaterializationInFlight()) {
|
||||
scheduleReload();
|
||||
}
|
||||
}, materializationPollIntervalMs);
|
||||
};
|
||||
|
||||
scheduleReload();
|
||||
|
||||
onCleanup(() => {
|
||||
cancelled = true;
|
||||
|
||||
if (timeoutId !== undefined) {
|
||||
window.clearTimeout(timeoutId);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const bootstrapNamePlaceholder = (): string => personaDefinition().defaults.namePlaceholder;
|
||||
const bootstrapStepCount = createMemo(() => activeWizardSteps().length);
|
||||
const currentStep = createMemo<BootstrapStepDefinition>(() => activeBootstrapSteps()[currentStepIndex()] ?? activeBootstrapSteps()[0] ?? bootstrapStepDefinitions[0]!);
|
||||
const currentWizardStepIndex = createMemo(() => {
|
||||
const visibleIndex = activeWizardSteps().findIndex((step) => step.id === currentStep().id);
|
||||
|
||||
return visibleIndex >= 0 ? visibleIndex : 0;
|
||||
});
|
||||
const wizardProgressPercent = createMemo(() => {
|
||||
const totalSteps = bootstrapStepCount();
|
||||
const activeIndex = Math.max(currentWizardStepIndex(), 0);
|
||||
|
||||
if (totalSteps <= 1) {
|
||||
return 100;
|
||||
}
|
||||
|
||||
return (activeIndex / (totalSteps - 1)) * 100;
|
||||
});
|
||||
const wizardProgressFillWidth = createMemo(() => {
|
||||
if (currentStepIndex() <= 0) {
|
||||
return `${wizardProgressPercent()}%`;
|
||||
}
|
||||
|
||||
return `calc(${wizardProgressPercent()}% + ((var(--control-size-md) - var(--space-2)) / 2))`;
|
||||
});
|
||||
const currentStepState = createMemo<BootstrapSubmissionState>(() => stepState[currentStep().id]);
|
||||
const isFirstStep = (): boolean => currentStepIndex() === 0;
|
||||
const isLastStep = (): boolean => currentStepIndex() === activeBootstrapSteps().length - 1;
|
||||
const canDismissWizard = (): boolean => isBootstrapPersisted() && !isMaterializationInFlight();
|
||||
|
||||
createEffect(() => {
|
||||
setCurrentStepIndex((index) => Math.min(index, activeBootstrapSteps().length - 1));
|
||||
});
|
||||
|
||||
const submitStep = async (step: BootstrapStepKey, payload: unknown): Promise<boolean> => {
|
||||
setStepState(step, { status: "submitting", error: "" });
|
||||
|
||||
try {
|
||||
await submitBootstrapStepRequest(step, payload);
|
||||
|
||||
setStepState(step, {
|
||||
status: "success",
|
||||
error: "",
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
setStepState(step, {
|
||||
status: "error",
|
||||
error: error instanceof Error ? error.message : `Bootstrap ${step} request failed.`,
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const payloadForStep = (step: BootstrapStepKey): unknown => {
|
||||
switch (step) {
|
||||
case "instance":
|
||||
return instanceForm;
|
||||
case "mode":
|
||||
return modeForm;
|
||||
case "admin":
|
||||
return adminForm;
|
||||
case "structure":
|
||||
return structureForm;
|
||||
}
|
||||
};
|
||||
|
||||
const applyPersonaSelection = (persona: BootstrapPersona): void => {
|
||||
const definition = bootstrapPersonaDefinitions.find((candidate) => candidate.id === persona);
|
||||
|
||||
if (!definition?.isAvailable) {
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedPersona(persona);
|
||||
setHasChosenPersona(true);
|
||||
setStepState("persona", {
|
||||
status: "success",
|
||||
error: "",
|
||||
});
|
||||
setCurrentStepIndex((index) => Math.min(index + 1, activeBootstrapSteps().length - 1));
|
||||
};
|
||||
|
||||
const statusLabel = (state: BootstrapSubmissionState): string => {
|
||||
switch (state.status) {
|
||||
case "submitting":
|
||||
return "Sending";
|
||||
case "error":
|
||||
return "Request failed";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
};
|
||||
|
||||
const submitCurrentStep = async (): Promise<void> => {
|
||||
const step = currentStep().id;
|
||||
|
||||
if (step === "persona") {
|
||||
applyPersonaSelection(selectedPersona());
|
||||
return;
|
||||
}
|
||||
|
||||
if (step === "mode" && usesCondensedBootstrapFlow() && stepState.instance.status !== "success") {
|
||||
const didPersistInstanceDefaults = await submitStep("instance", instanceForm);
|
||||
|
||||
if (!didPersistInstanceDefaults) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const didSucceed = await submitStep(step, payloadForStep(step));
|
||||
|
||||
if (!didSucceed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (step === "admin" && usesCondensedBootstrapFlow()) {
|
||||
const didPersistStructureDefaults = await submitStep("structure", structureForm);
|
||||
|
||||
if (!didPersistStructureDefaults) {
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (isLastStep()) {
|
||||
await appShellData.reload();
|
||||
|
||||
const shouldShowFinishingState = isBootstrapPersisted() && (isMaterializationInFlight() || hasMaterializationFailed());
|
||||
setIsFinishingBootstrapFlow(shouldShowFinishingState);
|
||||
setIsBootstrapComplete(isBootstrapPersisted() && !isMaterializationInFlight());
|
||||
setIsWizardOpen(!isBootstrapPersisted() || shouldShowFinishingState);
|
||||
setIsBootstrapStateResolved(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentStepIndex((index) => Math.min(index + 1, activeBootstrapSteps().length - 1));
|
||||
};
|
||||
|
||||
const showFieldTooltip = (target: HTMLElement, text: string): void => {
|
||||
const rect = target.getBoundingClientRect();
|
||||
const placement = rect.top > 96 ? "top" : "bottom";
|
||||
const viewportPadding = 20;
|
||||
const left = Math.min(Math.max(rect.left + rect.width / 2, viewportPadding), window.innerWidth - viewportPadding);
|
||||
const top = placement === "top" ? rect.top - 10 : rect.bottom + 10;
|
||||
|
||||
setFieldTooltip({ text, left, top, placement });
|
||||
};
|
||||
|
||||
const hideFieldTooltip = (): void => {
|
||||
setFieldTooltip(null);
|
||||
};
|
||||
|
||||
const stepStatusLabel = (step: BootstrapStepDefinition): string => {
|
||||
const state = stepState[step.id];
|
||||
|
||||
if (state.status === "success") {
|
||||
return "Done";
|
||||
}
|
||||
|
||||
if (state.status === "error") {
|
||||
return "Needs retry";
|
||||
}
|
||||
|
||||
return "";
|
||||
};
|
||||
|
||||
return {
|
||||
instanceForm,
|
||||
setInstanceForm,
|
||||
modeForm,
|
||||
setModeForm,
|
||||
adminForm,
|
||||
setAdminForm,
|
||||
structureForm,
|
||||
setStructureForm,
|
||||
selectedPersona,
|
||||
setSelectedPersona,
|
||||
hasChosenPersona,
|
||||
stepState,
|
||||
isBootstrapStateResolved,
|
||||
isBootstrapComplete,
|
||||
isWizardOpen,
|
||||
setIsWizardOpen,
|
||||
isFinishingBootstrapFlow,
|
||||
setIsFinishingBootstrapFlow,
|
||||
fieldTooltip,
|
||||
materializationState,
|
||||
isMaterializationInFlight,
|
||||
hasMaterializationFailed,
|
||||
showBootstrapFinishingState,
|
||||
materializationStatusLabel,
|
||||
materializationMessage,
|
||||
personaDefinition,
|
||||
selectedPersonaIsAvailable,
|
||||
usesCondensedBootstrapFlow,
|
||||
activeWizardSteps,
|
||||
bootstrapNamePlaceholder,
|
||||
bootstrapStepCount,
|
||||
currentStep,
|
||||
currentWizardStepIndex,
|
||||
wizardProgressFillWidth,
|
||||
currentStepState,
|
||||
isFirstStep,
|
||||
canDismissWizard,
|
||||
resetWizardState,
|
||||
handleCurrentStepSubmit: (event: SubmitEvent & { currentTarget: HTMLFormElement; target: Element }): void => {
|
||||
event.preventDefault();
|
||||
void submitCurrentStep();
|
||||
},
|
||||
applyPersonaSelection,
|
||||
statusLabel,
|
||||
showFieldTooltip,
|
||||
hideFieldTooltip,
|
||||
stepStatusLabel,
|
||||
navigateBack: (): void => {
|
||||
setCurrentStepIndex((index) => Math.max(index - 1, 0));
|
||||
},
|
||||
navigateToVisibleStep: (index: number): void => {
|
||||
setCurrentStepIndex(index + 1);
|
||||
},
|
||||
};
|
||||
};
|
||||
+442
-45
@@ -1,3 +1,5 @@
|
||||
/* Path: Frontend/src/components/bootstrap/BootstrapWizard/BootstrapWizard.module.scss */
|
||||
|
||||
.viewport,
|
||||
.wizardLayer {
|
||||
--workspace-content-max-width: var(--content-width-wide);
|
||||
@@ -92,6 +94,21 @@
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.heroStatus {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
justify-items: start;
|
||||
}
|
||||
|
||||
.heroStatusMessage {
|
||||
max-width: 64ch;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.heroStatusMessage[data-status="failed"] {
|
||||
color: var(--color-danger-text, var(--color-text));
|
||||
}
|
||||
|
||||
.title {
|
||||
@include text-display;
|
||||
font-family: var(--font-family-display);
|
||||
@@ -194,6 +211,19 @@
|
||||
background: color-mix(in srgb, var(--color-success-surface, var(--color-surface-secondary)) 80%, transparent);
|
||||
}
|
||||
|
||||
.statusBadge[data-status="pending"],
|
||||
.statusBadge[data-status="running"] {
|
||||
color: var(--bootstrap-accent);
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 38%, transparent);
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 10%, var(--color-surface-secondary));
|
||||
}
|
||||
|
||||
.statusBadge[data-status="failed"] {
|
||||
color: var(--color-danger-text, var(--color-text));
|
||||
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border)) 68%, transparent);
|
||||
background: color-mix(in srgb, var(--color-danger-surface, var(--color-surface-secondary)) 80%, transparent);
|
||||
}
|
||||
|
||||
.statusBadge[data-status="error"] {
|
||||
color: var(--color-danger-text, var(--color-text));
|
||||
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border)) 68%, transparent);
|
||||
@@ -240,11 +270,249 @@
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fieldLabelRow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.fieldInfoButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--color-text-muted);
|
||||
cursor: help;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.fieldInfoButton:hover,
|
||||
.fieldInfoButton:focus-visible {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fieldTooltip {
|
||||
position: fixed;
|
||||
z-index: calc(var(--z-modal, 1000) + 4);
|
||||
pointer-events: none;
|
||||
transform: translateX(-50%);
|
||||
max-width: min(18rem, calc(100vw - 2rem));
|
||||
}
|
||||
|
||||
.fieldTooltip[data-placement="top"] {
|
||||
transform: translate(-50%, -100%);
|
||||
}
|
||||
|
||||
.fieldTooltip[data-placement="bottom"] {
|
||||
transform: translate(-50%, 0);
|
||||
}
|
||||
|
||||
.fieldTooltipBubble {
|
||||
position: relative;
|
||||
padding: 0.45rem 0.6rem;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
border-radius: var(--radius-md);
|
||||
background: color-mix(in srgb, var(--color-surface-elevated, var(--color-surface)) 96%, black 4%);
|
||||
box-shadow: var(--shadow-soft);
|
||||
color: var(--color-text);
|
||||
white-space: normal;
|
||||
text-align: left;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.fieldTooltipBubble::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
width: 0.55rem;
|
||||
height: 0.55rem;
|
||||
background: color-mix(in srgb, var(--color-surface-elevated, var(--color-surface)) 96%, black 4%);
|
||||
transform: translateX(-50%) rotate(45deg);
|
||||
}
|
||||
|
||||
.fieldTooltip[data-placement="top"] .fieldTooltipBubble::after {
|
||||
top: calc(100% - 0.3rem);
|
||||
border-right: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
}
|
||||
|
||||
.fieldTooltip[data-placement="bottom"] .fieldTooltipBubble::after {
|
||||
bottom: calc(100% - 0.3rem);
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
border-left: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
}
|
||||
|
||||
.fieldHelp {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.personaIntro {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.personaGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.personaCard {
|
||||
appearance: none;
|
||||
position: relative;
|
||||
display: grid;
|
||||
padding: var(--space-3);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
border-radius: var(--radius-xl);
|
||||
background: color-mix(in srgb, var(--color-surface-secondary) 84%, transparent);
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
transition:
|
||||
transform 180ms var(--easing-standard),
|
||||
border-color 160ms var(--easing-standard),
|
||||
background 160ms var(--easing-standard),
|
||||
box-shadow 160ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.personaCard:hover,
|
||||
.personaCard:focus-visible,
|
||||
.personaCard[data-selected="true"] {
|
||||
transform: translateY(-1px);
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 32%, var(--color-border));
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 7%, var(--color-surface));
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
.personaCard:focus-visible {
|
||||
outline: none;
|
||||
box-shadow:
|
||||
var(--shadow-soft),
|
||||
0 0 0 3px color-mix(in srgb, var(--bootstrap-accent) 16%, transparent);
|
||||
}
|
||||
|
||||
.personaCard[data-available="false"] {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.personaCard[data-available="false"]:hover,
|
||||
.personaCard[data-available="false"]:focus-visible,
|
||||
.personaCard[data-available="false"][data-selected="true"] {
|
||||
transform: none;
|
||||
border-color: color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
background: color-mix(in srgb, var(--color-surface-secondary) 84%, transparent);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.personaCardMedia {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
justify-self: center;
|
||||
align-self: center;
|
||||
width: min(100%, 16rem);
|
||||
aspect-ratio: 1 / 1;
|
||||
border: 1px dashed color-mix(in srgb, var(--color-border-strong) 40%, transparent);
|
||||
border-radius: calc(var(--radius-xl) - var(--space-1));
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
color-mix(in srgb, var(--color-surface-elevated) 92%, transparent),
|
||||
color-mix(in srgb, var(--color-surface-secondary) 88%, transparent)
|
||||
);
|
||||
transition:
|
||||
filter 180ms var(--easing-standard),
|
||||
opacity 180ms var(--easing-standard),
|
||||
transform 180ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.personaCardBody {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
align-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3);
|
||||
pointer-events: none;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.personaCardTitle {
|
||||
@include text-title;
|
||||
margin: 0;
|
||||
max-width: min(100%, 14rem);
|
||||
padding: 0.35rem 0.65rem;
|
||||
border-radius: var(--radius-md);
|
||||
background: color-mix(in srgb, var(--color-surface) 84%, transparent);
|
||||
backdrop-filter: blur(10px);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.personaCardDetails {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
max-height: 0;
|
||||
opacity: 0;
|
||||
overflow: hidden;
|
||||
align-self: end;
|
||||
padding: var(--space-3);
|
||||
border-radius: var(--radius-lg);
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
color-mix(in srgb, var(--color-surface) 18%, transparent),
|
||||
color-mix(in srgb, var(--color-surface) 92%, transparent)
|
||||
);
|
||||
backdrop-filter: blur(12px);
|
||||
transition:
|
||||
max-height 180ms var(--easing-standard),
|
||||
opacity 160ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.personaCard:hover .personaCardMedia,
|
||||
.personaCard:focus-visible .personaCardMedia,
|
||||
.personaCard[data-selected="true"] .personaCardMedia {
|
||||
filter: brightness(0.72);
|
||||
opacity: 0.92;
|
||||
transform: scale(0.985);
|
||||
}
|
||||
|
||||
.personaCard:hover .personaCardDetails,
|
||||
.personaCard:focus-visible .personaCardDetails,
|
||||
.personaCard[data-selected="true"] .personaCardDetails {
|
||||
max-height: 12rem;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.personaCard[data-available="false"]:hover .personaCardMedia,
|
||||
.personaCard[data-available="false"]:focus-visible .personaCardMedia,
|
||||
.personaCard[data-available="false"][data-selected="true"] .personaCardMedia {
|
||||
filter: brightness(0.82);
|
||||
opacity: 0.96;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.personaBestFor,
|
||||
.personaBulletList {
|
||||
margin: 0;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.personaBulletList {
|
||||
padding-left: 1rem;
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.personaAvailability {
|
||||
@include text-caption;
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select {
|
||||
min-height: var(--control-size-md);
|
||||
@@ -342,7 +610,7 @@
|
||||
.primaryButton:hover,
|
||||
.secondaryButton:hover,
|
||||
.wizardCloseButton:hover,
|
||||
.wizardStepButton:hover {
|
||||
.wizardProgressStep:hover {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
@@ -417,72 +685,93 @@
|
||||
|
||||
.wizardBody {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(17rem, 20rem) minmax(0, 1fr);
|
||||
gap: var(--space-4);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.wizardSidebar {
|
||||
.wizardProgress {
|
||||
position: relative;
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
.wizardSidebarSection {
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.wizardSteps {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
.wizardProgressTrack {
|
||||
position: absolute;
|
||||
left: calc((var(--control-size-md) - var(--space-2)) / 2);
|
||||
right: calc((var(--control-size-md) - var(--space-2)) / 2);
|
||||
top: calc((var(--control-size-md) - var(--space-2)) / 2);
|
||||
height: 2px;
|
||||
background: color-mix(in srgb, var(--color-border) 72%, transparent);
|
||||
transform: translateY(-50%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.wizardStepButton {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
.wizardProgressFill {
|
||||
height: 100%;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 72%, white 8%);
|
||||
transition: width 220ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.wizardProgressSteps {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
text-align: left;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
background: color-mix(in srgb, var(--color-surface-secondary) 84%, transparent);
|
||||
justify-content: space-between;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.wizardStepButton[data-active="true"] {
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 42%, transparent);
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 10%, var(--color-surface));
|
||||
.wizardProgressStep {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 0 0 auto;
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
justify-items: center;
|
||||
text-align: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.wizardStepButton:disabled {
|
||||
opacity: 0.56;
|
||||
.wizardProgressStep:disabled {
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.wizardStepIndex {
|
||||
.wizardProgressIndex {
|
||||
width: calc(var(--control-size-md) - var(--space-2));
|
||||
height: calc(var(--control-size-md) - var(--space-2));
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--color-surface) 80%, transparent);
|
||||
border-radius: 999px;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
background: color-mix(in srgb, var(--color-surface) 92%, transparent);
|
||||
color: var(--color-text-muted);
|
||||
transition:
|
||||
border-color 160ms var(--easing-standard),
|
||||
background 160ms var(--easing-standard),
|
||||
color 160ms var(--easing-standard),
|
||||
box-shadow 160ms var(--easing-standard),
|
||||
transform 180ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.wizardProgressStep[data-active="true"] .wizardProgressIndex,
|
||||
.wizardProgressStep[data-complete="true"] .wizardProgressIndex {
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 42%, transparent);
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 12%, var(--color-surface));
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.wizardStepCopy {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 0.125rem;
|
||||
.wizardProgressStep[data-active="true"] .wizardProgressIndex {
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bootstrap-accent) 14%, transparent);
|
||||
}
|
||||
|
||||
.wizardStepCopy strong {
|
||||
@include text-label;
|
||||
}
|
||||
|
||||
.wizardStepCopy small {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
.wizardProgressStep:not(:disabled):hover .wizardProgressIndex,
|
||||
.wizardProgressStep:not(:disabled):focus-visible .wizardProgressIndex {
|
||||
transform: translateY(-1px);
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 36%, var(--color-border));
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.wizardStepPanel {
|
||||
@@ -490,7 +779,116 @@
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.wizardFinishPanel {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
justify-items: stretch;
|
||||
padding: var(--space-2) 0 0;
|
||||
min-height: min(14rem, 32dvh);
|
||||
align-content: center;
|
||||
}
|
||||
|
||||
.wizardFinishShell {
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
width: min(100%, 40rem);
|
||||
padding: 0;
|
||||
border: 0;
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.wizardFinishStatusRow {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
gap: var(--space-3);
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.wizardFinishIndicator {
|
||||
width: 2.5rem;
|
||||
height: 2.5rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 999px;
|
||||
border: 1px solid color-mix(in srgb, var(--bootstrap-accent) 18%, transparent);
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 8%, transparent);
|
||||
}
|
||||
|
||||
.wizardFinishIndicator[data-status="failed"] {
|
||||
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border)) 44%, transparent);
|
||||
background: color-mix(in srgb, var(--color-danger-surface, var(--color-surface-secondary)) 36%, transparent);
|
||||
}
|
||||
|
||||
.wizardFinishSpinner {
|
||||
width: 1.25rem;
|
||||
height: 1.25rem;
|
||||
border-radius: 999px;
|
||||
border: 2px solid color-mix(in srgb, var(--bootstrap-accent) 18%, transparent);
|
||||
border-top-color: var(--bootstrap-accent);
|
||||
animation: wizardFinishSpin 900ms linear infinite;
|
||||
}
|
||||
|
||||
.wizardFinishIndicator[data-status="failed"] .wizardFinishSpinner {
|
||||
border: 2px solid color-mix(in srgb, var(--color-danger-border, var(--color-border)) 22%, transparent);
|
||||
border-top-color: var(--color-danger-text, var(--color-text));
|
||||
animation: none;
|
||||
transform: rotate(45deg);
|
||||
border-radius: var(--radius-sm);
|
||||
width: 1rem;
|
||||
height: 1rem;
|
||||
}
|
||||
|
||||
.wizardFinishCopy {
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.wizardFinishTitle {
|
||||
@include text-title;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.wizardFinishDescription,
|
||||
.wizardFinishMessage,
|
||||
.wizardFinishHint {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.wizardFinishMessage[data-status="failed"] {
|
||||
color: var(--color-danger-text, var(--color-text));
|
||||
}
|
||||
|
||||
.wizardFinishHint {
|
||||
@include text-caption;
|
||||
}
|
||||
|
||||
.wizardFinishActions {
|
||||
display: flex;
|
||||
gap: var(--space-3);
|
||||
flex-wrap: wrap;
|
||||
padding-top: var(--space-1);
|
||||
}
|
||||
|
||||
@keyframes wizardFinishSpin {
|
||||
from {
|
||||
transform: rotate(0deg);
|
||||
}
|
||||
|
||||
to {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
@include respond-down(tablet) {
|
||||
.personaGrid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.summaryGrid,
|
||||
.wizardBody {
|
||||
grid-template-columns: 1fr;
|
||||
@@ -536,21 +934,20 @@
|
||||
}
|
||||
|
||||
.wizardHeader,
|
||||
.wizardBody,
|
||||
.wizardSidebar {
|
||||
.wizardBody {
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.wizardSteps {
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(10rem, 1fr);
|
||||
.wizardProgressSteps {
|
||||
justify-content: flex-start;
|
||||
gap: var(--space-8);
|
||||
overflow-x: auto;
|
||||
padding-bottom: var(--space-1);
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.wizardStepButton {
|
||||
min-width: 10rem;
|
||||
.wizardProgressStep {
|
||||
min-width: calc(var(--control-size-md) - var(--space-2));
|
||||
}
|
||||
|
||||
.wizardFormActions {
|
||||
@@ -0,0 +1,287 @@
|
||||
// Path: Frontend/src/components/bootstrap/BootstrapWizard/BootstrapWizard.parts.tsx
|
||||
|
||||
import { For, Show, type JSX } from "solid-js";
|
||||
import { CircleHelp } from "../../../lib/icons";
|
||||
import {
|
||||
organizationalStructureDefaults,
|
||||
workspaceHomeFieldTooltips,
|
||||
type AdminForm,
|
||||
type BootstrapPersona,
|
||||
type BootstrapPersonaDefinition,
|
||||
type BootstrapStepDefinition,
|
||||
type BootstrapStepKey,
|
||||
type InstanceForm,
|
||||
type ModeForm,
|
||||
type StructureForm,
|
||||
} from "./BootstrapWizard.data";
|
||||
import styles from "./BootstrapWizard.module.scss";
|
||||
|
||||
type BootstrapSubmissionState = {
|
||||
status: "idle" | "submitting" | "success" | "error";
|
||||
error: string;
|
||||
};
|
||||
|
||||
type MaterializationState = "not_started" | "pending" | "running" | "succeeded" | "failed";
|
||||
|
||||
type TooltipHandlers = {
|
||||
onShowTooltip: (target: HTMLElement, text: string) => void;
|
||||
onHideTooltip: () => void;
|
||||
};
|
||||
|
||||
type FieldLabelWithTooltipProps = TooltipHandlers & {
|
||||
label: string;
|
||||
tooltip?: string;
|
||||
};
|
||||
|
||||
export const FieldLabelWithTooltip = (props: FieldLabelWithTooltipProps): JSX.Element => (
|
||||
<span class={styles.fieldLabelRow}>
|
||||
<span class={styles.fieldLabel}>{props.label}</span>
|
||||
<Show when={props.tooltip}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.fieldInfoButton}
|
||||
aria-label={`${props.label} help: ${props.tooltip}`}
|
||||
onMouseEnter={(event): void => props.onShowTooltip(event.currentTarget, props.tooltip!)}
|
||||
onMouseLeave={props.onHideTooltip}
|
||||
onFocus={(event): void => props.onShowTooltip(event.currentTarget, props.tooltip!)}
|
||||
onBlur={props.onHideTooltip}
|
||||
>
|
||||
<CircleHelp size={14} strokeWidth={2} />
|
||||
</button>
|
||||
</Show>
|
||||
</span>
|
||||
);
|
||||
|
||||
type BootstrapFinishingStateProps = {
|
||||
materializationState: MaterializationState;
|
||||
statusLabel: string;
|
||||
message: string;
|
||||
isInFlight: boolean;
|
||||
hasFailed: boolean;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export const BootstrapFinishingState = (props: BootstrapFinishingStateProps): JSX.Element => (
|
||||
<div class={styles.wizardFinishPanel} data-slot="bootstrap-wizard-finishing-state">
|
||||
<div class={styles.wizardFinishShell}>
|
||||
<div class={styles.wizardFinishStatusRow}>
|
||||
<div class={styles.wizardFinishIndicator} data-status={props.materializationState} aria-hidden="true">
|
||||
<div class={styles.wizardFinishSpinner} />
|
||||
</div>
|
||||
<div class={styles.wizardFinishCopy}>
|
||||
<span class={styles.wizardStepEyebrow}>Bootstrap status</span>
|
||||
<h3 class={styles.wizardFinishTitle}>Finishing setup</h3>
|
||||
<p class={styles.wizardFinishDescription}>
|
||||
We saved your initial bootstrap. The server is finishing the last background setup steps now.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class={styles.statusBadge} data-status={props.materializationState}>{props.statusLabel}</div>
|
||||
<Show when={props.message}>
|
||||
<p class={styles.wizardFinishMessage} data-status={props.materializationState}>{props.message}</p>
|
||||
</Show>
|
||||
<Show when={props.isInFlight}>
|
||||
<p class={styles.wizardFinishHint}>This window will close automatically when setup is complete.</p>
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={props.hasFailed}>
|
||||
<div class={styles.wizardFinishActions}>
|
||||
<button type="button" class={styles.secondaryButton} onClick={props.onClose}>Close</button>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
);
|
||||
|
||||
type BootstrapWizardProgressProps = {
|
||||
steps: readonly BootstrapStepDefinition[];
|
||||
currentStepId: BootstrapStepKey;
|
||||
currentWizardStepIndex: number;
|
||||
stepState: Record<BootstrapStepKey, BootstrapSubmissionState>;
|
||||
bootstrapStepCount: number;
|
||||
wizardProgressFillWidth: string;
|
||||
stepStatusLabel: (step: BootstrapStepDefinition) => string;
|
||||
onSelectStep: (index: number) => void;
|
||||
};
|
||||
|
||||
export const BootstrapWizardProgress = (props: BootstrapWizardProgressProps): JSX.Element => (
|
||||
<div class={styles.wizardProgress} data-slot="bootstrap-wizard-progress">
|
||||
<div class={styles.wizardProgressTrack} aria-hidden="true">
|
||||
<div class={styles.wizardProgressFill} style={{ width: props.wizardProgressFillWidth }} />
|
||||
</div>
|
||||
<nav class={styles.wizardProgressSteps} aria-label="Bootstrap steps" style={{ "--wizard-progress-step-count": props.bootstrapStepCount }}>
|
||||
<For each={props.steps}>
|
||||
{(step, index): JSX.Element => (
|
||||
<button
|
||||
type="button"
|
||||
class={styles.wizardProgressStep}
|
||||
data-active={step.id === props.currentStepId ? "true" : "false"}
|
||||
data-complete={props.stepState[step.id].status === "success" ? "true" : "false"}
|
||||
disabled={index() > props.currentWizardStepIndex}
|
||||
onClick={(): void => {
|
||||
if (index() <= props.currentWizardStepIndex) {
|
||||
props.onSelectStep(index());
|
||||
}
|
||||
}}
|
||||
aria-label={`Step ${index() + 1}${props.stepStatusLabel(step) ? `, ${props.stepStatusLabel(step)}` : ""}`}
|
||||
>
|
||||
<span class={styles.wizardProgressIndex}>{index() + 1}</span>
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</nav>
|
||||
</div>
|
||||
);
|
||||
|
||||
type BootstrapPersonaStepProps = {
|
||||
personas: readonly BootstrapPersonaDefinition[];
|
||||
hasChosenPersona: boolean;
|
||||
selectedPersona: BootstrapPersona;
|
||||
selectedPersonaIsAvailable: boolean;
|
||||
onSelectPersona: (persona: BootstrapPersona) => void;
|
||||
};
|
||||
|
||||
export const BootstrapPersonaStep = (props: BootstrapPersonaStepProps): JSX.Element => (
|
||||
<>
|
||||
<div class={styles.personaGrid}>
|
||||
<For each={props.personas}>
|
||||
{(persona): JSX.Element => (
|
||||
<button
|
||||
type="button"
|
||||
class={styles.personaCard}
|
||||
data-selected={props.hasChosenPersona && persona.id === props.selectedPersona ? "true" : "false"}
|
||||
data-available={persona.isAvailable ? "true" : "false"}
|
||||
aria-pressed={props.hasChosenPersona && persona.id === props.selectedPersona}
|
||||
onClick={(): void => props.onSelectPersona(persona.id)}
|
||||
>
|
||||
<div class={styles.personaCardMedia} aria-hidden="true" />
|
||||
<div class={styles.personaCardBody}>
|
||||
<h4 class={styles.personaCardTitle}>{persona.title}</h4>
|
||||
<div class={styles.personaCardDetails}>
|
||||
<p class={styles.personaBestFor}>{persona.bestFor}</p>
|
||||
<ul class={styles.personaBulletList}>
|
||||
<For each={persona.bullets}>{(bullet): JSX.Element => <li>{bullet}</li>}</For>
|
||||
</ul>
|
||||
<Show when={!persona.isAvailable}><p class={styles.personaAvailability}>Coming later</p></Show>
|
||||
</div>
|
||||
</div>
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
<Show when={!props.selectedPersonaIsAvailable}>
|
||||
<p class={styles.fieldHelp}>Only <strong>Self Hosted Enthusiast</strong> is wired up right now. The other setup paths will come next.</p>
|
||||
</Show>
|
||||
</>
|
||||
);
|
||||
|
||||
type BootstrapInstanceStepProps = TooltipHandlers & {
|
||||
instanceForm: InstanceForm;
|
||||
onProtocolChange: (value: InstanceForm["protocol"]) => void;
|
||||
onAccessChange: (value: InstanceForm["access"]) => void;
|
||||
onHostChange: (value: string) => void;
|
||||
};
|
||||
|
||||
export const BootstrapInstanceStep = (props: BootstrapInstanceStepProps): JSX.Element => (
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Protocol" tooltip={workspaceHomeFieldTooltips.protocol} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<select value={props.instanceForm.protocol} onInput={(event): void => props.onProtocolChange(event.currentTarget.value as InstanceForm["protocol"])}>
|
||||
<option value="http">http</option>
|
||||
<option value="https">https</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Access" tooltip={workspaceHomeFieldTooltips.access} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<select value={props.instanceForm.access} onInput={(event): void => props.onAccessChange(event.currentTarget.value as InstanceForm["access"])}>
|
||||
<option value="local">local</option>
|
||||
<option value="remote">remote</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Host" tooltip={workspaceHomeFieldTooltips.host} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<input type="text" value={props.instanceForm.host} onInput={(event): void => props.onHostChange(event.currentTarget.value)} placeholder="localhost or app.example.com" />
|
||||
</label>
|
||||
</>
|
||||
);
|
||||
|
||||
type BootstrapModeStepProps = TooltipHandlers & {
|
||||
modeForm: ModeForm;
|
||||
structureForm: StructureForm;
|
||||
usesCondensedBootstrapFlow: boolean;
|
||||
selectedPersona: BootstrapPersona;
|
||||
namePlaceholder: string;
|
||||
onNameChange: (value: string) => void;
|
||||
onProjectNameChange: (value: string) => void;
|
||||
onTeamNameChange: (value: string) => void;
|
||||
};
|
||||
|
||||
export const BootstrapModeStep = (props: BootstrapModeStepProps): JSX.Element => (
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Server name" tooltip={workspaceHomeFieldTooltips.serverName} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<input type="text" value={props.modeForm.name} required onInput={(event): void => props.onNameChange(event.currentTarget.value)} placeholder={props.namePlaceholder} />
|
||||
</label>
|
||||
<Show when={props.usesCondensedBootstrapFlow}>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Default Project" tooltip={workspaceHomeFieldTooltips.project} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<input type="text" value={props.structureForm.projectName} onInput={(event): void => props.onProjectNameChange(event.currentTarget.value)} placeholder="Project" />
|
||||
</label>
|
||||
</Show>
|
||||
<Show when={props.selectedPersona === "team"}>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Team name" tooltip={workspaceHomeFieldTooltips.team} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<input type="text" value={props.structureForm.teamName} onInput={(event): void => props.onTeamNameChange(event.currentTarget.value)} placeholder="Core Team" />
|
||||
</label>
|
||||
</Show>
|
||||
</>
|
||||
);
|
||||
|
||||
type BootstrapAdminStepProps = {
|
||||
adminForm: AdminForm;
|
||||
onDisplayNameChange: (value: string) => void;
|
||||
onEmailChange: (value: string) => void;
|
||||
onPasswordChange: (value: string) => void;
|
||||
};
|
||||
|
||||
export const BootstrapAdminStep = (props: BootstrapAdminStepProps): JSX.Element => (
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Display name</span>
|
||||
<input type="text" value={props.adminForm.displayName} onInput={(event): void => props.onDisplayNameChange(event.currentTarget.value)} placeholder="Admin" />
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Email</span>
|
||||
<input type="email" value={props.adminForm.email} onInput={(event): void => props.onEmailChange(event.currentTarget.value)} placeholder="admin@example.com" />
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Password</span>
|
||||
<input type="password" value={props.adminForm.password} onInput={(event): void => props.onPasswordChange(event.currentTarget.value)} placeholder="Create a strong password" />
|
||||
<small class={styles.fieldHelp}>Use at least 12 characters with uppercase, lowercase, numbers, and symbols.</small>
|
||||
</label>
|
||||
</>
|
||||
);
|
||||
|
||||
type BootstrapStructureStepProps = TooltipHandlers & {
|
||||
mode: ModeForm["mode"];
|
||||
structureForm: StructureForm;
|
||||
onDepartmentNameChange: (value: string) => void;
|
||||
onTeamNameChange: (value: string) => void;
|
||||
onProjectNameChange: (value: string) => void;
|
||||
};
|
||||
|
||||
export const BootstrapStructureStep = (props: BootstrapStructureStepProps): JSX.Element => (
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Department" tooltip={workspaceHomeFieldTooltips.department} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<input type="text" value={props.structureForm.departmentName} disabled={props.mode === "personal"} onInput={(event): void => props.onDepartmentNameChange(event.currentTarget.value)} placeholder={organizationalStructureDefaults.departmentName} />
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Team" tooltip={workspaceHomeFieldTooltips.team} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<input type="text" value={props.structureForm.teamName} disabled={props.mode === "personal"} onInput={(event): void => props.onTeamNameChange(event.currentTarget.value)} placeholder={organizationalStructureDefaults.teamName} />
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<FieldLabelWithTooltip label="Project" tooltip={workspaceHomeFieldTooltips.project} onShowTooltip={props.onShowTooltip} onHideTooltip={props.onHideTooltip} />
|
||||
<input type="text" value={props.structureForm.projectName} onInput={(event): void => props.onProjectNameChange(event.currentTarget.value)} placeholder="Moku" />
|
||||
</label>
|
||||
</>
|
||||
);
|
||||
@@ -0,0 +1,107 @@
|
||||
import { type JSX } from "solid-js";
|
||||
import { useAppShellData } from "../../app-shell/data/app-shell.context";
|
||||
import { useBootstrapWizard } from "./BootstrapWizard.hook";
|
||||
import { BootstrapWizardDialog } from "./BootstrapWizardDialog";
|
||||
|
||||
export const BootstrapWizard = (): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
const {
|
||||
instanceForm,
|
||||
setInstanceForm,
|
||||
modeForm,
|
||||
setModeForm,
|
||||
adminForm,
|
||||
setAdminForm,
|
||||
structureForm,
|
||||
setStructureForm,
|
||||
selectedPersona,
|
||||
hasChosenPersona,
|
||||
stepState,
|
||||
isBootstrapStateResolved,
|
||||
isWizardOpen,
|
||||
setIsWizardOpen,
|
||||
setIsFinishingBootstrapFlow,
|
||||
fieldTooltip,
|
||||
materializationState,
|
||||
isMaterializationInFlight,
|
||||
hasMaterializationFailed,
|
||||
showBootstrapFinishingState,
|
||||
materializationStatusLabel,
|
||||
materializationMessage,
|
||||
selectedPersonaIsAvailable,
|
||||
usesCondensedBootstrapFlow,
|
||||
activeWizardSteps,
|
||||
bootstrapNamePlaceholder,
|
||||
bootstrapStepCount,
|
||||
currentStep,
|
||||
currentWizardStepIndex,
|
||||
wizardProgressFillWidth,
|
||||
currentStepState,
|
||||
isFirstStep,
|
||||
canDismissWizard,
|
||||
handleCurrentStepSubmit,
|
||||
applyPersonaSelection,
|
||||
statusLabel,
|
||||
showFieldTooltip,
|
||||
hideFieldTooltip,
|
||||
stepStatusLabel,
|
||||
navigateBack,
|
||||
navigateToVisibleStep,
|
||||
} = useBootstrapWizard(appShellData);
|
||||
|
||||
return (
|
||||
<BootstrapWizardDialog
|
||||
isOpen={isBootstrapStateResolved() && isWizardOpen()}
|
||||
currentStep={currentStep()}
|
||||
currentStepState={currentStepState()}
|
||||
activeWizardSteps={activeWizardSteps()}
|
||||
currentWizardStepIndex={currentWizardStepIndex()}
|
||||
stepState={stepState}
|
||||
bootstrapStepCount={bootstrapStepCount()}
|
||||
wizardProgressFillWidth={wizardProgressFillWidth()}
|
||||
showBootstrapFinishingState={showBootstrapFinishingState()}
|
||||
materializationState={materializationState()}
|
||||
materializationStatusLabel={materializationStatusLabel()}
|
||||
materializationMessage={materializationMessage()}
|
||||
isMaterializationInFlight={isMaterializationInFlight()}
|
||||
hasMaterializationFailed={hasMaterializationFailed()}
|
||||
instanceForm={instanceForm}
|
||||
modeForm={modeForm}
|
||||
adminForm={adminForm}
|
||||
structureForm={structureForm}
|
||||
selectedPersona={selectedPersona()}
|
||||
hasChosenPersona={hasChosenPersona()}
|
||||
selectedPersonaIsAvailable={selectedPersonaIsAvailable()}
|
||||
usesCondensedBootstrapFlow={usesCondensedBootstrapFlow()}
|
||||
bootstrapNamePlaceholder={bootstrapNamePlaceholder()}
|
||||
isFirstStep={isFirstStep()}
|
||||
canDismissWizard={canDismissWizard()}
|
||||
fieldTooltip={fieldTooltip()}
|
||||
onClose={(): void => {
|
||||
setIsWizardOpen(false);
|
||||
}}
|
||||
onCloseFinishingState={(): void => {
|
||||
setIsFinishingBootstrapFlow(false);
|
||||
setIsWizardOpen(false);
|
||||
}}
|
||||
onSubmit={handleCurrentStepSubmit}
|
||||
onSelectPersona={applyPersonaSelection}
|
||||
onProtocolChange={(value): void => setInstanceForm("protocol", value)}
|
||||
onAccessChange={(value): void => setInstanceForm("access", value)}
|
||||
onHostChange={(value): void => setInstanceForm("host", value)}
|
||||
onModeNameChange={(value): void => setModeForm("name", value)}
|
||||
onProjectNameChange={(value): void => setStructureForm("projectName", value)}
|
||||
onTeamNameChange={(value): void => setStructureForm("teamName", value)}
|
||||
onAdminDisplayNameChange={(value): void => setAdminForm("displayName", value)}
|
||||
onAdminEmailChange={(value): void => setAdminForm("email", value)}
|
||||
onAdminPasswordChange={(value): void => setAdminForm("password", value)}
|
||||
onDepartmentNameChange={(value): void => setStructureForm("departmentName", value)}
|
||||
onShowTooltip={showFieldTooltip}
|
||||
onHideTooltip={hideFieldTooltip}
|
||||
statusLabel={statusLabel}
|
||||
stepStatusLabel={stepStatusLabel}
|
||||
onNavigateBack={navigateBack}
|
||||
onSelectStep={navigateToVisibleStep}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,234 @@
|
||||
// Path: Frontend/src/components/bootstrap/BootstrapWizard/BootstrapWizardDialog.tsx
|
||||
|
||||
import { Show, type JSX } from "solid-js";
|
||||
import { Portal } from "solid-js/web";
|
||||
import {
|
||||
type AdminForm,
|
||||
type BootstrapPersona,
|
||||
bootstrapPersonaDefinitions,
|
||||
type BootstrapStepDefinition,
|
||||
type BootstrapStepKey,
|
||||
type InstanceForm,
|
||||
type ModeForm,
|
||||
type StructureForm,
|
||||
} from "./BootstrapWizard.data";
|
||||
import { type BootstrapSubmissionState, type FieldTooltipState, type MaterializationState } from "./BootstrapWizard.hook";
|
||||
import {
|
||||
BootstrapAdminStep,
|
||||
BootstrapFinishingState,
|
||||
BootstrapInstanceStep,
|
||||
BootstrapModeStep,
|
||||
BootstrapPersonaStep,
|
||||
BootstrapStructureStep,
|
||||
BootstrapWizardProgress,
|
||||
} from "./BootstrapWizard.parts";
|
||||
import styles from "./BootstrapWizard.module.scss";
|
||||
|
||||
export type BootstrapWizardDialogProps = {
|
||||
isOpen: boolean;
|
||||
currentStep: BootstrapStepDefinition;
|
||||
currentStepState: BootstrapSubmissionState;
|
||||
activeWizardSteps: readonly BootstrapStepDefinition[];
|
||||
currentWizardStepIndex: number;
|
||||
stepState: Record<BootstrapStepKey, BootstrapSubmissionState>;
|
||||
bootstrapStepCount: number;
|
||||
wizardProgressFillWidth: string;
|
||||
showBootstrapFinishingState: boolean;
|
||||
materializationState: MaterializationState;
|
||||
materializationStatusLabel: string;
|
||||
materializationMessage: string;
|
||||
isMaterializationInFlight: boolean;
|
||||
hasMaterializationFailed: boolean;
|
||||
instanceForm: InstanceForm;
|
||||
modeForm: ModeForm;
|
||||
adminForm: AdminForm;
|
||||
structureForm: StructureForm;
|
||||
selectedPersona: BootstrapPersona;
|
||||
hasChosenPersona: boolean;
|
||||
selectedPersonaIsAvailable: boolean;
|
||||
usesCondensedBootstrapFlow: boolean;
|
||||
bootstrapNamePlaceholder: string;
|
||||
isFirstStep: boolean;
|
||||
canDismissWizard: boolean;
|
||||
fieldTooltip: FieldTooltipState | null;
|
||||
onClose: () => void;
|
||||
onCloseFinishingState: () => void;
|
||||
onSubmit: JSX.EventHandlerUnion<HTMLFormElement, SubmitEvent>;
|
||||
onSelectPersona: (persona: BootstrapPersona) => void;
|
||||
onProtocolChange: (value: InstanceForm["protocol"]) => void;
|
||||
onAccessChange: (value: InstanceForm["access"]) => void;
|
||||
onHostChange: (value: string) => void;
|
||||
onModeNameChange: (value: string) => void;
|
||||
onProjectNameChange: (value: string) => void;
|
||||
onTeamNameChange: (value: string) => void;
|
||||
onAdminDisplayNameChange: (value: string) => void;
|
||||
onAdminEmailChange: (value: string) => void;
|
||||
onAdminPasswordChange: (value: string) => void;
|
||||
onDepartmentNameChange: (value: string) => void;
|
||||
onShowTooltip: (target: HTMLElement, text: string) => void;
|
||||
onHideTooltip: () => void;
|
||||
statusLabel: (state: BootstrapSubmissionState) => string;
|
||||
stepStatusLabel: (step: BootstrapStepDefinition) => string;
|
||||
onNavigateBack: () => void;
|
||||
onSelectStep: (index: number) => void;
|
||||
};
|
||||
|
||||
export const BootstrapWizardDialog = (props: BootstrapWizardDialogProps): JSX.Element => (
|
||||
<Show when={props.isOpen}>
|
||||
<Portal>
|
||||
<div class={styles.wizardLayer} data-ui="bootstrap-wizard" data-step={props.currentStep.id}>
|
||||
<div class={styles.wizardBackdrop} aria-hidden="true" />
|
||||
|
||||
<section class={styles.wizardPanel} role="dialog" aria-modal="true" aria-labelledby="bootstrap-wizard-title" data-slot="bootstrap-wizard-panel">
|
||||
<header class={styles.wizardHeader} data-slot="bootstrap-wizard-header">
|
||||
<div class={styles.wizardHeaderCopy}>
|
||||
<h2 id="bootstrap-wizard-title" class={styles.wizardTitle}>
|
||||
Bootstrap Server
|
||||
</h2>
|
||||
</div>
|
||||
<Show when={props.canDismissWizard}>
|
||||
<button type="button" class={styles.wizardCloseButton} onClick={props.onClose}>
|
||||
Close
|
||||
</button>
|
||||
</Show>
|
||||
</header>
|
||||
|
||||
<Show
|
||||
when={!props.showBootstrapFinishingState}
|
||||
fallback={
|
||||
<BootstrapFinishingState
|
||||
materializationState={props.materializationState}
|
||||
statusLabel={props.materializationStatusLabel}
|
||||
message={props.materializationMessage}
|
||||
isInFlight={props.isMaterializationInFlight}
|
||||
hasFailed={props.hasMaterializationFailed}
|
||||
onClose={props.onCloseFinishingState}
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div class={styles.wizardBody}>
|
||||
<Show when={props.currentStep.id !== "persona"}>
|
||||
<BootstrapWizardProgress
|
||||
steps={props.activeWizardSteps}
|
||||
currentStepId={props.currentStep.id}
|
||||
currentWizardStepIndex={props.currentWizardStepIndex}
|
||||
stepState={props.stepState}
|
||||
bootstrapStepCount={props.bootstrapStepCount}
|
||||
wizardProgressFillWidth={props.wizardProgressFillWidth}
|
||||
stepStatusLabel={props.stepStatusLabel}
|
||||
onSelectStep={props.onSelectStep}
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<div class={styles.wizardStepPanel} data-slot="bootstrap-wizard-step-panel">
|
||||
<Show when={props.currentStep.id !== "persona" || props.statusLabel(props.currentStepState)}>
|
||||
<div class={styles.sectionHeader}>
|
||||
<Show when={props.currentStep.id !== "persona"}>
|
||||
<div>
|
||||
<span class={styles.wizardStepEyebrow}>{`Step ${props.currentWizardStepIndex + 1} of ${props.bootstrapStepCount}`}</span>
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={props.statusLabel(props.currentStepState)}>
|
||||
<div class={styles.statusBadge} data-status={props.currentStepState.status}>
|
||||
{props.statusLabel(props.currentStepState)}
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<form class={styles.form} onSubmit={props.onSubmit}>
|
||||
<Show when={props.currentStep.id === "persona"}>
|
||||
<BootstrapPersonaStep
|
||||
personas={bootstrapPersonaDefinitions}
|
||||
hasChosenPersona={props.hasChosenPersona}
|
||||
selectedPersona={props.selectedPersona}
|
||||
selectedPersonaIsAvailable={props.selectedPersonaIsAvailable}
|
||||
onSelectPersona={props.onSelectPersona}
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<Show when={props.currentStep.id === "instance"}>
|
||||
<BootstrapInstanceStep
|
||||
instanceForm={props.instanceForm}
|
||||
onProtocolChange={props.onProtocolChange}
|
||||
onAccessChange={props.onAccessChange}
|
||||
onHostChange={props.onHostChange}
|
||||
onShowTooltip={props.onShowTooltip}
|
||||
onHideTooltip={props.onHideTooltip}
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<Show when={props.currentStep.id === "mode"}>
|
||||
<BootstrapModeStep
|
||||
modeForm={props.modeForm}
|
||||
structureForm={props.structureForm}
|
||||
usesCondensedBootstrapFlow={props.usesCondensedBootstrapFlow}
|
||||
selectedPersona={props.selectedPersona}
|
||||
namePlaceholder={props.bootstrapNamePlaceholder}
|
||||
onNameChange={props.onModeNameChange}
|
||||
onProjectNameChange={props.onProjectNameChange}
|
||||
onTeamNameChange={props.onTeamNameChange}
|
||||
onShowTooltip={props.onShowTooltip}
|
||||
onHideTooltip={props.onHideTooltip}
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<Show when={props.currentStep.id === "admin"}>
|
||||
<BootstrapAdminStep
|
||||
adminForm={props.adminForm}
|
||||
onDisplayNameChange={props.onAdminDisplayNameChange}
|
||||
onEmailChange={props.onAdminEmailChange}
|
||||
onPasswordChange={props.onAdminPasswordChange}
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<Show when={props.currentStep.id === "structure"}>
|
||||
<BootstrapStructureStep
|
||||
mode={props.modeForm.mode}
|
||||
structureForm={props.structureForm}
|
||||
onDepartmentNameChange={props.onDepartmentNameChange}
|
||||
onTeamNameChange={props.onTeamNameChange}
|
||||
onProjectNameChange={props.onProjectNameChange}
|
||||
onShowTooltip={props.onShowTooltip}
|
||||
onHideTooltip={props.onHideTooltip}
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<Show when={props.currentStep.id !== "persona"}>
|
||||
<div class={styles.wizardFormActions}>
|
||||
<button type="button" class={styles.secondaryButton} disabled={props.isFirstStep} onClick={props.onNavigateBack}>
|
||||
Back
|
||||
</button>
|
||||
<button type="submit" class={styles.primaryButton} disabled={props.currentStepState.status === "submitting"}>
|
||||
{props.currentStep.buttonLabel}
|
||||
</button>
|
||||
</div>
|
||||
</Show>
|
||||
</form>
|
||||
|
||||
<Show when={props.currentStepState.error}>
|
||||
<p class={styles.errorText}>{props.currentStepState.error}</p>
|
||||
</Show>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
</section>
|
||||
|
||||
<Show when={props.fieldTooltip}>
|
||||
{(tooltip): JSX.Element => (
|
||||
<div
|
||||
class={styles.fieldTooltip}
|
||||
data-placement={tooltip().placement}
|
||||
style={{
|
||||
left: `${tooltip().left}px`,
|
||||
top: `${tooltip().top}px`,
|
||||
}}
|
||||
>
|
||||
<div class={styles.fieldTooltipBubble}>{tooltip().text}</div>
|
||||
</div>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</Portal>
|
||||
</Show>
|
||||
);
|
||||
@@ -0,0 +1,81 @@
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
import type { BootstrapStepKey } from "./BootstrapWizard.data";
|
||||
|
||||
const readBootstrapResponseBody = async (response: Response): Promise<unknown> => {
|
||||
const raw = await response.text();
|
||||
|
||||
if (!raw.trim()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
|
||||
const readBootstrapResponseError = (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(", ")})`;
|
||||
};
|
||||
|
||||
export const submitBootstrapStepRequest = async (
|
||||
step: BootstrapStepKey,
|
||||
payload: unknown,
|
||||
): Promise<void> => {
|
||||
const response = await fetch(`${resolveAPIBase()}/bootstrap/steps/${step}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await readBootstrapResponseBody(response);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(readBootstrapResponseError(step, data));
|
||||
}
|
||||
};
|
||||
-190
@@ -1,190 +0,0 @@
|
||||
.browserLayer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@include respond-down(mobile) {
|
||||
.browserLayer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
z-index: calc(var(--z-popover, 20) + 2);
|
||||
background: color-mix(in srgb, var(--color-canvas) 96%, black 4%);
|
||||
}
|
||||
|
||||
.sheet {
|
||||
min-height: 100dvh;
|
||||
display: grid;
|
||||
grid-template-rows: auto minmax(0, 1fr);
|
||||
background:
|
||||
linear-gradient(180deg, color-mix(in srgb, var(--color-surface) 84%, transparent) 0%, transparent 8rem),
|
||||
color-mix(in srgb, var(--color-canvas) 97%, black 3%);
|
||||
overflow: clip;
|
||||
}
|
||||
|
||||
.sheetHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: calc(var(--space-5) + env(safe-area-inset-top, 0px)) var(--space-4) var(--space-4);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--color-border) 84%, transparent);
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.brandBlock {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.sectionLabel {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.brandEyebrow {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
.brandTitle {
|
||||
@include text-title;
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.brandContext {
|
||||
@include text-caption;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.closeButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: var(--control-size-md);
|
||||
height: var(--control-size-md);
|
||||
padding: 0;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 92%, transparent);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--color-surface) 92%, transparent);
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.createButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
min-height: var(--control-size-md);
|
||||
padding: 0 var(--space-3);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border-strong, var(--color-border)) 82%, transparent);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--color-surface) 94%, var(--color-canvas) 6%);
|
||||
color: var(--color-text);
|
||||
box-shadow: var(--shadow-soft);
|
||||
font: inherit;
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.sheetBody {
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
gap: var(--space-5);
|
||||
padding: var(--space-5) var(--space-5) calc(var(--space-12) + var(--space-10) + env(safe-area-inset-bottom, 0px));
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.sectionBlock {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.treeList,
|
||||
.treeListItem {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.treeList {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 92%, transparent);
|
||||
}
|
||||
|
||||
.treeListNested {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.treeRow {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
min-height: calc(var(--control-size-lg) + var(--space-3));
|
||||
padding: var(--space-4) var(--space-2) var(--space-4) calc(var(--space-2) + (var(--tree-depth, 0) * var(--space-4)));
|
||||
border: 0;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--color-border) 92%, transparent);
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
color: var(--color-text);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.treeRowActive {
|
||||
color: var(--color-text);
|
||||
background: color-mix(in srgb, var(--color-surface) 72%, transparent);
|
||||
}
|
||||
|
||||
.treeRowBranch {
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.treeRowLead,
|
||||
.treeRowTrail {
|
||||
min-width: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.treeRowTrail {
|
||||
flex: 0 0 auto;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.treeLabel {
|
||||
@include text-label;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.treeMeta {
|
||||
@include text-caption;
|
||||
min-width: 1rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.treeChevron {
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.treeListNested > .treeListItem > .treeRow {
|
||||
min-height: calc(var(--control-size-lg) + var(--space-1));
|
||||
}
|
||||
}
|
||||
@@ -1,247 +0,0 @@
|
||||
import { For, Show, createSignal, type JSX } from "solid-js";
|
||||
import { ChevronRight, Plus, X } from "../../../lib/icons";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import { createLongPressGesture } from "../createLongPressGesture";
|
||||
import {
|
||||
createWorkspaceStaticTarget,
|
||||
createWorkspaceSurfaceTarget,
|
||||
createWorkspaceTreeTarget,
|
||||
getWorkspaceNodeIcon,
|
||||
workspaceStaticItems,
|
||||
type SidebarItem,
|
||||
type WorkspaceContextMenuAction,
|
||||
type WorkspaceContextMenuTarget,
|
||||
type WorkspaceStaticItem,
|
||||
type WorkspaceTreeNode,
|
||||
} from "../data/shell.data";
|
||||
import { WorkspaceMobileActionSheet } from "../WorkspaceMobileActionSheet/WorkspaceMobileActionSheet";
|
||||
import styles from "./MobileWorkspaceBrowser.module.scss";
|
||||
|
||||
type MobileWorkspaceBrowserProps = {
|
||||
open: boolean;
|
||||
onClose: VoidFunction;
|
||||
};
|
||||
|
||||
const TreeRow = (props: { node: WorkspaceTreeNode; depth?: number }): JSX.Element => {
|
||||
const depth = props.depth ?? 0;
|
||||
const Icon = getWorkspaceNodeIcon(props.node);
|
||||
const hasChildren = (props.node.children?.length ?? 0) > 0;
|
||||
|
||||
return (
|
||||
<button
|
||||
classList={{
|
||||
[styles.treeRow]: true,
|
||||
[styles.treeRowActive]: props.node.active ?? false,
|
||||
[styles.treeRowBranch]: hasChildren,
|
||||
}}
|
||||
type="button"
|
||||
style={{ "--tree-depth": `${depth}` }}
|
||||
data-slot="mobile-workspace-tree-row"
|
||||
data-kind={props.node.kind}
|
||||
data-item-type={props.node.kind === "item" ? props.node.itemType : undefined}
|
||||
data-active={props.node.active ? "true" : "false"}
|
||||
>
|
||||
<span class={styles.treeRowLead}>
|
||||
<Icon size={16} strokeWidth={2} />
|
||||
<span class={styles.treeLabel}>{props.node.label}</span>
|
||||
</span>
|
||||
|
||||
<span class={styles.treeRowTrail}>
|
||||
<Show when={props.node.meta}>
|
||||
<span class={styles.treeMeta}>{props.node.meta}</span>
|
||||
</Show>
|
||||
<Show when={hasChildren}>
|
||||
<ChevronRight size={14} strokeWidth={2} class={styles.treeChevron} />
|
||||
</Show>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
const StaticRow = (props: { item: SidebarItem }): JSX.Element => {
|
||||
const Icon = props.item.icon;
|
||||
|
||||
return (
|
||||
<button classList={{ [styles.treeRow]: true, [styles.treeRowActive]: props.item.active ?? false }} type="button" style={{ "--tree-depth": "0" }} data-slot="mobile-workspace-static-row" data-active={props.item.active ? "true" : "false"}>
|
||||
<span class={styles.treeRowLead}>
|
||||
<Icon size={16} strokeWidth={2} />
|
||||
<span class={styles.treeLabel}>{props.item.label}</span>
|
||||
</span>
|
||||
<span class={styles.treeRowTrail}>
|
||||
<Show when={props.item.meta}>
|
||||
<span class={styles.treeMeta}>{props.item.meta}</span>
|
||||
</Show>
|
||||
<ChevronRight size={14} strokeWidth={2} class={styles.treeChevron} />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
const WorkspaceStaticRow = (props: {
|
||||
item: WorkspaceStaticItem;
|
||||
onOpenActionSheet: (target: WorkspaceContextMenuTarget) => void;
|
||||
}): JSX.Element => {
|
||||
const target = createWorkspaceStaticTarget(props.item);
|
||||
const longPress = createLongPressGesture({
|
||||
onLongPress: () => {
|
||||
props.onOpenActionSheet(target);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<li
|
||||
class={styles.treeListItem}
|
||||
data-slot="mobile-workspace-static-item"
|
||||
data-target-kind={target.kind}
|
||||
onContextMenu={(event): void => {
|
||||
event.preventDefault();
|
||||
props.onOpenActionSheet(target);
|
||||
}}
|
||||
{...longPress}
|
||||
>
|
||||
<StaticRow item={props.item} />
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
const WorkspaceTreeBranch = (props: {
|
||||
nodes: readonly WorkspaceTreeNode[];
|
||||
depth?: number;
|
||||
onOpenActionSheet: (target: WorkspaceContextMenuTarget) => void;
|
||||
}): JSX.Element => {
|
||||
const depth = props.depth ?? 0;
|
||||
|
||||
return (
|
||||
<For each={props.nodes}>
|
||||
{(node): JSX.Element => {
|
||||
const target = createWorkspaceTreeTarget(node);
|
||||
const longPress = createLongPressGesture({
|
||||
onLongPress: () => {
|
||||
props.onOpenActionSheet(target);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<li
|
||||
class={styles.treeListItem}
|
||||
data-slot="mobile-workspace-tree-item"
|
||||
data-kind={node.kind}
|
||||
data-item-type={node.kind === "item" ? node.itemType : undefined}
|
||||
onContextMenu={(event): void => {
|
||||
event.preventDefault();
|
||||
props.onOpenActionSheet(target);
|
||||
}}
|
||||
{...longPress}
|
||||
>
|
||||
<TreeRow node={node} depth={depth} />
|
||||
|
||||
<Show when={node.children?.length}>
|
||||
<ul class={styles.treeListNested}>
|
||||
<WorkspaceTreeBranch nodes={node.children ?? []} depth={depth + 1} onOpenActionSheet={props.onOpenActionSheet} />
|
||||
</ul>
|
||||
</Show>
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
</For>
|
||||
);
|
||||
};
|
||||
|
||||
export const MobileWorkspaceBrowser = (props: MobileWorkspaceBrowserProps): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
const [actionSheetTarget, setActionSheetTarget] = createSignal<WorkspaceContextMenuTarget | null>(null);
|
||||
const sectionNodes = () => appShellData.workspaceTree().filter((node) => (node.children?.length ?? 0) > 0);
|
||||
const looseNodes = () => appShellData.workspaceTree().filter((node) => (node.children?.length ?? 0) === 0);
|
||||
const workspaceTarget = () => createWorkspaceSurfaceTarget(appShellData.activeProject());
|
||||
const openActionSheet = (target: WorkspaceContextMenuTarget): void => {
|
||||
setActionSheetTarget(target);
|
||||
};
|
||||
const closeActionSheet = (): void => {
|
||||
setActionSheetTarget(null);
|
||||
};
|
||||
const openWorkspaceActionSheet = (): void => {
|
||||
openActionSheet(workspaceTarget());
|
||||
};
|
||||
|
||||
const handleActionSelect = (_action: WorkspaceContextMenuAction, _target: WorkspaceContextMenuTarget): void => {
|
||||
// Mobile first pass only establishes the action-sheet IA and long-press behavior.
|
||||
};
|
||||
|
||||
const workspaceLongPress = createLongPressGesture({
|
||||
onLongPress: openWorkspaceActionSheet,
|
||||
});
|
||||
|
||||
return (
|
||||
<Show when={props.open}>
|
||||
<div class={styles.browserLayer} data-ui="mobile-workspace-browser">
|
||||
<section class={styles.sheet} aria-label="Mobile workspace browser" data-slot="mobile-workspace-sheet">
|
||||
<header class={styles.sheetHeader} data-slot="mobile-workspace-header">
|
||||
<div
|
||||
class={styles.brandBlock}
|
||||
data-slot="mobile-workspace-brand"
|
||||
onContextMenu={(event): void => {
|
||||
event.preventDefault();
|
||||
openWorkspaceActionSheet();
|
||||
}}
|
||||
{...workspaceLongPress}
|
||||
>
|
||||
{/* Long-pressing the browser header exposes workspace-level actions on mobile. */}
|
||||
<span class={styles.brandEyebrow}>Moku Work</span>
|
||||
<strong class={styles.brandTitle}>{appShellData.activeProject().name}</strong>
|
||||
<span class={styles.brandContext}>{appShellData.activeServer().name}</span>
|
||||
</div>
|
||||
|
||||
<div class={styles.headerActions} data-slot="mobile-workspace-header-actions">
|
||||
<button
|
||||
class={styles.createButton}
|
||||
type="button"
|
||||
aria-label="Create"
|
||||
data-slot="mobile-workspace-create"
|
||||
onClick={openWorkspaceActionSheet}
|
||||
>
|
||||
<Plus size={16} strokeWidth={2.25} />
|
||||
<span>Create</span>
|
||||
</button>
|
||||
|
||||
<button class={styles.closeButton} type="button" aria-label="Close workspace browser" data-slot="mobile-workspace-close" onClick={props.onClose}>
|
||||
<X size={18} strokeWidth={2} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class={styles.sheetBody} data-slot="mobile-workspace-body">
|
||||
<section class={styles.sectionBlock} data-slot="mobile-workspace-section" data-section-id="workspace">
|
||||
<span class={styles.sectionLabel}>Workspace</span>
|
||||
<ul class={styles.treeList} data-slot="mobile-workspace-list" data-section-id="workspace">
|
||||
<For each={workspaceStaticItems}>
|
||||
{(item): JSX.Element => <WorkspaceStaticRow item={item} onOpenActionSheet={openActionSheet} />}
|
||||
</For>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class={styles.sectionBlock} data-slot="mobile-workspace-section" data-section-id="items">
|
||||
<span class={styles.sectionLabel}>Items</span>
|
||||
<ul class={styles.treeList} data-slot="mobile-workspace-list" data-section-id="items">
|
||||
<WorkspaceTreeBranch nodes={sectionNodes()} onOpenActionSheet={openActionSheet} />
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<Show when={looseNodes().length > 0}>
|
||||
<section class={styles.sectionBlock} data-slot="mobile-workspace-section" data-section-id="more">
|
||||
<span class={styles.sectionLabel}>More</span>
|
||||
<ul class={styles.treeList} data-slot="mobile-workspace-list" data-section-id="more">
|
||||
<WorkspaceTreeBranch nodes={looseNodes()} onOpenActionSheet={openActionSheet} />
|
||||
</ul>
|
||||
</section>
|
||||
</Show>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<WorkspaceMobileActionSheet
|
||||
target={actionSheetTarget()}
|
||||
onClose={closeActionSheet}
|
||||
onSelect={handleActionSelect}
|
||||
/>
|
||||
</div>
|
||||
</Show>
|
||||
);
|
||||
};
|
||||
@@ -1,913 +0,0 @@
|
||||
// Path: Frontend/src/components/shell/ProjectSelector/ProjectSelector.tsx
|
||||
|
||||
import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
||||
import { ChevronDown, ChevronRight, Folder, LayoutGrid } from "../../../lib/icons";
|
||||
import { ProjectContextMenu } from "../ProjectContextMenu/ProjectContextMenu";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import {
|
||||
createProjectFolderTarget,
|
||||
createProjectSurfaceTarget,
|
||||
createProjectTarget,
|
||||
type ProjectItem,
|
||||
type ProjectMenuTarget,
|
||||
} from "../data/shell.data";
|
||||
import { createProjectContextMenuController } from "../ProjectContextMenu/createProjectContextMenuController";
|
||||
import styles from "./ProjectSelector.module.scss";
|
||||
|
||||
type ProjectSelectorProps = {
|
||||
compact?: boolean;
|
||||
isOpen: boolean;
|
||||
onToggle: () => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
type ProjectFolderNode = {
|
||||
kind: "folder";
|
||||
id: string;
|
||||
label: string;
|
||||
meta?: string;
|
||||
children: ProjectTreeNode[];
|
||||
};
|
||||
|
||||
type ProjectLeafNode = {
|
||||
kind: "project";
|
||||
item: ProjectItem;
|
||||
};
|
||||
|
||||
type ProjectTreeNode = ProjectFolderNode | ProjectLeafNode;
|
||||
|
||||
type PendingProjectFolderDraft = {
|
||||
parentId: string | null;
|
||||
depth: number;
|
||||
};
|
||||
|
||||
type ProjectDragTarget = {
|
||||
parentId: string | null;
|
||||
index: number;
|
||||
intent: "before" | "after" | "inside";
|
||||
targetNodeId?: string;
|
||||
};
|
||||
|
||||
type ProjectDragState = {
|
||||
draggedNodeId: string;
|
||||
dropTarget: ProjectDragTarget | null;
|
||||
};
|
||||
|
||||
type ProjectNodeLocation = {
|
||||
parentId: string | null;
|
||||
index: number;
|
||||
node: ProjectTreeNode;
|
||||
};
|
||||
|
||||
const LONG_PRESS_MS = 320;
|
||||
|
||||
const createProjectFolderId = (): string => `project-folder-${Math.random().toString(36).slice(2, 10)}`;
|
||||
|
||||
const getProjectTreeNodeId = (node: ProjectTreeNode): string =>
|
||||
node.kind === "folder" ? node.id : node.item.id;
|
||||
|
||||
const buildProjectTree = (items: readonly ProjectItem[]): ProjectTreeNode[] =>
|
||||
items.map((item) => ({
|
||||
kind: "project",
|
||||
item,
|
||||
}));
|
||||
|
||||
const cloneProjectTreeNode = (node: ProjectTreeNode): ProjectTreeNode => {
|
||||
if (node.kind === "project") {
|
||||
return {
|
||||
kind: "project",
|
||||
item: { ...node.item },
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
kind: "folder",
|
||||
id: node.id,
|
||||
label: node.label,
|
||||
meta: node.meta,
|
||||
children: node.children.map(cloneProjectTreeNode),
|
||||
};
|
||||
};
|
||||
|
||||
const insertProjectFolderNode = (
|
||||
nodes: readonly ProjectTreeNode[],
|
||||
parentId: string | null,
|
||||
folder: ProjectFolderNode,
|
||||
): ProjectTreeNode[] => {
|
||||
if (parentId === null) {
|
||||
return [...nodes, folder];
|
||||
}
|
||||
|
||||
return nodes.map((node) => {
|
||||
if (node.kind !== "folder") {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node.id === parentId) {
|
||||
return {
|
||||
...node,
|
||||
children: [...node.children, folder],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...node,
|
||||
children: insertProjectFolderNode(node.children, parentId, folder),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const findProjectNodeLocation = (
|
||||
nodes: readonly ProjectTreeNode[],
|
||||
nodeId: string,
|
||||
parentId: string | null = null,
|
||||
): ProjectNodeLocation | null => {
|
||||
for (let index = 0; index < nodes.length; index += 1) {
|
||||
const node = nodes[index];
|
||||
|
||||
if (getProjectTreeNodeId(node) === nodeId) {
|
||||
return { parentId, index, node };
|
||||
}
|
||||
|
||||
if (node.kind === "folder") {
|
||||
const nestedLocation = findProjectNodeLocation(node.children, nodeId, node.id);
|
||||
|
||||
if (nestedLocation) {
|
||||
return nestedLocation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const findProjectNodeDepth = (nodes: readonly ProjectTreeNode[], nodeId: string, depth = 0): number | null => {
|
||||
for (const node of nodes) {
|
||||
if (getProjectTreeNodeId(node) === nodeId) {
|
||||
return depth;
|
||||
}
|
||||
|
||||
if (node.kind === "folder") {
|
||||
const nestedDepth = findProjectNodeDepth(node.children, nodeId, depth + 1);
|
||||
|
||||
if (nestedDepth !== null) {
|
||||
return nestedDepth;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const projectTreeContainsNode = (nodes: readonly ProjectTreeNode[], nodeId: string): boolean => {
|
||||
for (const node of nodes) {
|
||||
if (getProjectTreeNodeId(node) === nodeId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (node.kind === "folder" && projectTreeContainsNode(node.children, nodeId)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const removeProjectTreeNode = (
|
||||
nodes: readonly ProjectTreeNode[],
|
||||
nodeId: string,
|
||||
): { nodes: ProjectTreeNode[]; removed: ProjectTreeNode | null } => {
|
||||
const nextNodes: ProjectTreeNode[] = [];
|
||||
let removed: ProjectTreeNode | null = null;
|
||||
|
||||
for (const node of nodes) {
|
||||
if (getProjectTreeNodeId(node) === nodeId) {
|
||||
removed = node;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (node.kind === "folder") {
|
||||
const result = removeProjectTreeNode(node.children, nodeId);
|
||||
|
||||
if (result.removed) {
|
||||
removed = result.removed;
|
||||
nextNodes.push({
|
||||
...node,
|
||||
children: result.nodes,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
nextNodes.push(node);
|
||||
}
|
||||
|
||||
return { nodes: nextNodes, removed };
|
||||
};
|
||||
|
||||
const insertProjectTreeNode = (
|
||||
nodes: readonly ProjectTreeNode[],
|
||||
parentId: string | null,
|
||||
index: number,
|
||||
nodeToInsert: ProjectTreeNode,
|
||||
): ProjectTreeNode[] => {
|
||||
if (parentId === null) {
|
||||
const nextNodes = [...nodes];
|
||||
nextNodes.splice(Math.max(0, Math.min(index, nextNodes.length)), 0, nodeToInsert);
|
||||
return nextNodes;
|
||||
}
|
||||
|
||||
return nodes.map((node) => {
|
||||
if (node.kind !== "folder") {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node.id === parentId) {
|
||||
const nextChildren = [...node.children];
|
||||
nextChildren.splice(Math.max(0, Math.min(index, nextChildren.length)), 0, nodeToInsert);
|
||||
return {
|
||||
...node,
|
||||
children: nextChildren,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...node,
|
||||
children: insertProjectTreeNode(node.children, parentId, index, nodeToInsert),
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const moveProjectTreeNode = (
|
||||
nodes: readonly ProjectTreeNode[],
|
||||
draggedNodeId: string,
|
||||
dropTarget: ProjectDragTarget,
|
||||
): ProjectTreeNode[] => {
|
||||
const location = findProjectNodeLocation(nodes, draggedNodeId);
|
||||
|
||||
if (!location) {
|
||||
return [...nodes];
|
||||
}
|
||||
|
||||
if (
|
||||
location.node.kind === "folder" &&
|
||||
dropTarget.parentId !== null &&
|
||||
(projectTreeContainsNode(location.node.children, dropTarget.parentId) || dropTarget.parentId === location.node.id)
|
||||
) {
|
||||
return [...nodes];
|
||||
}
|
||||
|
||||
let normalizedIndex = dropTarget.index;
|
||||
|
||||
if (dropTarget.parentId === location.parentId && dropTarget.index > location.index) {
|
||||
normalizedIndex -= 1;
|
||||
}
|
||||
|
||||
if (dropTarget.parentId === location.parentId && normalizedIndex === location.index) {
|
||||
return [...nodes];
|
||||
}
|
||||
|
||||
const removalResult = removeProjectTreeNode(nodes, draggedNodeId);
|
||||
|
||||
if (!removalResult.removed) {
|
||||
return [...nodes];
|
||||
}
|
||||
|
||||
return insertProjectTreeNode(removalResult.nodes, dropTarget.parentId, normalizedIndex, removalResult.removed);
|
||||
};
|
||||
|
||||
const ProjectFolderDraftRow = (props: {
|
||||
depth: number;
|
||||
value: string;
|
||||
onInput: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
onCancel: () => void;
|
||||
}): JSX.Element => {
|
||||
let inputRef: HTMLInputElement | undefined;
|
||||
|
||||
queueMicrotask(() => inputRef?.focus());
|
||||
|
||||
return (
|
||||
<li>
|
||||
<div class={styles.treeInputRow} style={{ "--tree-depth": String(props.depth) }}>
|
||||
<Folder class={styles.icon} size={18} strokeWidth={2} />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
class={styles.treeInput}
|
||||
value={props.value}
|
||||
placeholder="Folder name"
|
||||
onInput={(event): void => props.onInput(event.currentTarget.value)}
|
||||
onBlur={props.onSubmit}
|
||||
onKeyDown={(event): void => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
event.currentTarget.blur();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
props.onCancel();
|
||||
event.currentTarget.blur();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
const ProjectFolderBranch = (props: {
|
||||
nodes: readonly ProjectTreeNode[];
|
||||
depth: number;
|
||||
parentId: string | null;
|
||||
selectedProjectId: string;
|
||||
isFolderCollapsed: (folderId: string) => boolean;
|
||||
onToggleFolder: (folderId: string) => void;
|
||||
onSelectProject: (projectId: string) => void;
|
||||
onOpenFolderMenu: (event: MouseEvent, folder: ProjectFolderNode) => void;
|
||||
onOpenProjectMenu: (event: MouseEvent, item: ProjectItem) => void;
|
||||
onNodePointerDown: (event: PointerEvent, nodeId: string) => void;
|
||||
onNodePointerMove: (event: PointerEvent, parentId: string | null, index: number, node: ProjectTreeNode) => void;
|
||||
pendingFolderDraft: PendingProjectFolderDraft | null;
|
||||
pendingFolderName: string;
|
||||
onPendingFolderNameChange: (value: string) => void;
|
||||
onSubmitPendingFolder: () => void;
|
||||
onCancelPendingFolder: () => void;
|
||||
dragState: ProjectDragState | null;
|
||||
}): JSX.Element => (
|
||||
<ul class={styles.treeList} role="list">
|
||||
<Show when={props.nodes.length === 0 && props.pendingFolderDraft?.parentId !== props.parentId}>
|
||||
<li>
|
||||
<div class={styles.treeEmptySlot} style={{ "--tree-depth": String(props.depth) }} />
|
||||
</li>
|
||||
</Show>
|
||||
|
||||
<For each={props.nodes}>
|
||||
{(node, indexAccessor): JSX.Element => {
|
||||
const nodeId = (): string => getProjectTreeNodeId(node);
|
||||
const isDraggedNode = (): boolean => props.dragState?.draggedNodeId === nodeId();
|
||||
const dropIntent = (): ProjectDragTarget["intent"] | null => {
|
||||
if (props.dragState?.dropTarget?.targetNodeId !== nodeId()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return props.dragState.dropTarget.intent;
|
||||
};
|
||||
|
||||
if (node.kind === "folder") {
|
||||
const isCollapsed = (): boolean => props.isFolderCollapsed(node.id);
|
||||
|
||||
return (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
classList={{
|
||||
[styles.treeItem]: true,
|
||||
[styles.treeItemFolder]: true,
|
||||
[styles.treeItemDragging]: isDraggedNode(),
|
||||
[styles.treeItemDropBefore]: dropIntent() === "before",
|
||||
[styles.treeItemDropAfter]: dropIntent() === "after",
|
||||
[styles.treeItemDropInside]: dropIntent() === "inside",
|
||||
}}
|
||||
style={{ "--tree-depth": String(props.depth) }}
|
||||
aria-expanded={!isCollapsed()}
|
||||
onClick={() => {
|
||||
if (props.dragState || suppressNextTreeClick()) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onToggleFolder(node.id);
|
||||
}}
|
||||
onContextMenu={(event): void => props.onOpenFolderMenu(event, node)}
|
||||
onPointerDown={(event): void => props.onNodePointerDown(event, node.id)}
|
||||
onPointerMove={(event): void =>
|
||||
props.onNodePointerMove(event, props.parentId, indexAccessor(), node)
|
||||
}
|
||||
onPointerEnter={(event): void =>
|
||||
props.onNodePointerMove(event, props.parentId, indexAccessor(), node)
|
||||
}
|
||||
>
|
||||
<ChevronRight
|
||||
classList={{
|
||||
[styles.folderChevron]: true,
|
||||
[styles.folderChevronOpen]: !isCollapsed(),
|
||||
}}
|
||||
size={16}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
<Folder class={styles.icon} size={18} strokeWidth={2} />
|
||||
<span class={styles.label}>{node.label}</span>
|
||||
<Show when={node.meta}>
|
||||
<span class={styles.itemMeta}>{node.meta}</span>
|
||||
</Show>
|
||||
</button>
|
||||
|
||||
<Show when={!isCollapsed() && (node.children.length > 0 || props.pendingFolderDraft?.parentId === node.id)}>
|
||||
<ProjectFolderBranch
|
||||
nodes={node.children}
|
||||
depth={props.depth + 1}
|
||||
parentId={node.id}
|
||||
selectedProjectId={props.selectedProjectId}
|
||||
isFolderCollapsed={props.isFolderCollapsed}
|
||||
onToggleFolder={props.onToggleFolder}
|
||||
onSelectProject={props.onSelectProject}
|
||||
onOpenFolderMenu={props.onOpenFolderMenu}
|
||||
onOpenProjectMenu={props.onOpenProjectMenu}
|
||||
onNodePointerDown={props.onNodePointerDown}
|
||||
onNodePointerMove={props.onNodePointerMove}
|
||||
pendingFolderDraft={props.pendingFolderDraft}
|
||||
pendingFolderName={props.pendingFolderName}
|
||||
onPendingFolderNameChange={props.onPendingFolderNameChange}
|
||||
onSubmitPendingFolder={props.onSubmitPendingFolder}
|
||||
onCancelPendingFolder={props.onCancelPendingFolder}
|
||||
dragState={props.dragState}
|
||||
/>
|
||||
</Show>
|
||||
</li>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
classList={{
|
||||
[styles.treeItem]: true,
|
||||
[styles.treeItemActive]: props.selectedProjectId === node.item.id,
|
||||
[styles.treeItemDragging]: isDraggedNode(),
|
||||
[styles.treeItemDropBefore]: dropIntent() === "before",
|
||||
[styles.treeItemDropAfter]: dropIntent() === "after",
|
||||
}}
|
||||
style={{ "--tree-depth": String(props.depth) }}
|
||||
onClick={(): void => {
|
||||
if (props.dragState || suppressNextTreeClick()) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onSelectProject(node.item.id);
|
||||
}}
|
||||
onContextMenu={(event): void => props.onOpenProjectMenu(event, node.item)}
|
||||
onPointerDown={(event): void => props.onNodePointerDown(event, node.item.id)}
|
||||
onPointerMove={(event): void =>
|
||||
props.onNodePointerMove(event, props.parentId, indexAccessor(), node)
|
||||
}
|
||||
onPointerEnter={(event): void =>
|
||||
props.onNodePointerMove(event, props.parentId, indexAccessor(), node)
|
||||
}
|
||||
>
|
||||
<LayoutGrid class={styles.icon} size={18} strokeWidth={2} />
|
||||
<span class={styles.label}>{node.item.name}</span>
|
||||
<Show when={node.item.meta}>
|
||||
<span class={styles.itemMeta}>{node.item.meta}</span>
|
||||
</Show>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
</For>
|
||||
|
||||
<Show when={props.pendingFolderDraft?.parentId === props.parentId}>
|
||||
<ProjectFolderDraftRow
|
||||
depth={props.pendingFolderDraft?.depth ?? props.depth}
|
||||
value={props.pendingFolderName}
|
||||
onInput={props.onPendingFolderNameChange}
|
||||
onSubmit={props.onSubmitPendingFolder}
|
||||
onCancel={props.onCancelPendingFolder}
|
||||
/>
|
||||
</Show>
|
||||
</ul>
|
||||
);
|
||||
|
||||
export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
const [selectedProject, setSelectedProject] = createSignal(appShellData.activeProject());
|
||||
const [drawerTop, setDrawerTop] = createSignal<number>(0);
|
||||
const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]);
|
||||
const [projectTreeNodes, setProjectTreeNodes] = createSignal<ProjectTreeNode[]>(
|
||||
buildProjectTree(appShellData.projectItems()),
|
||||
);
|
||||
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingProjectFolderDraft | null>(null);
|
||||
const [pendingFolderName, setPendingFolderName] = createSignal("");
|
||||
const [dragState, setDragState] = createSignal<ProjectDragState | null>(null);
|
||||
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
||||
let rootRef: HTMLDivElement | undefined;
|
||||
let triggerRef: HTMLButtonElement | undefined;
|
||||
let contextMenuRef: HTMLDivElement | undefined;
|
||||
let longPressTimer: number | undefined;
|
||||
let suppressClickTimer: number | undefined;
|
||||
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],
|
||||
);
|
||||
};
|
||||
|
||||
createEffect(() => {
|
||||
setSelectedProject(appShellData.activeProject());
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
setProjectTreeNodes(buildProjectTree(appShellData.projectItems()));
|
||||
setCollapsedFolderIds([]);
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
setDragState(null);
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const target = event.target;
|
||||
|
||||
if (target instanceof Node && rootRef.contains(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (target instanceof Node && contextMenuRef?.contains(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onClose();
|
||||
};
|
||||
|
||||
const handlePointerUp = (): void => {
|
||||
clearLongPressTimer();
|
||||
|
||||
const nextDragState = dragState();
|
||||
|
||||
if (!nextDragState?.dropTarget) {
|
||||
if (nextDragState) {
|
||||
suppressTreeClickTemporarily();
|
||||
}
|
||||
setDragState(null);
|
||||
return;
|
||||
}
|
||||
|
||||
suppressTreeClickTemporarily();
|
||||
setProjectTreeNodes((current) =>
|
||||
moveProjectTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget),
|
||||
);
|
||||
setDragState(null);
|
||||
};
|
||||
|
||||
const handleEscape = (event: KeyboardEvent): void => {
|
||||
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(() => {
|
||||
clearLongPressTimer();
|
||||
if (suppressClickTimer !== undefined) {
|
||||
window.clearTimeout(suppressClickTimer);
|
||||
}
|
||||
document.removeEventListener("pointerdown", handlePointerDown);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
window.removeEventListener("keydown", handleEscape);
|
||||
});
|
||||
});
|
||||
|
||||
const toggleOpen = (): void => {
|
||||
if (!props.isOpen) {
|
||||
props.onToggle();
|
||||
return;
|
||||
}
|
||||
|
||||
props.onClose();
|
||||
};
|
||||
|
||||
const selectProject = (projectId: string): void => {
|
||||
const location = findProjectNodeLocation(projectTreeNodes(), projectId);
|
||||
|
||||
if (!location || location.node.kind !== "project") {
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedProject({ id: location.node.item.id, name: location.node.item.name });
|
||||
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 = (): void => {
|
||||
const name = pendingFolderName().trim();
|
||||
const draft = pendingFolderDraft();
|
||||
|
||||
if (!draft) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!name) {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
return;
|
||||
}
|
||||
|
||||
setProjectTreeNodes((current) =>
|
||||
insertProjectFolderNode(current, draft.parentId, {
|
||||
kind: "folder",
|
||||
id: createProjectFolderId(),
|
||||
label: name,
|
||||
children: [],
|
||||
}),
|
||||
);
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
};
|
||||
|
||||
const cancelPendingFolder = (): void => {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
};
|
||||
|
||||
const handleContextActionSelect = (action: { id: string; label: string }, target: ProjectMenuTarget): void => {
|
||||
if (action.id !== "new-folder") {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (target.kind) {
|
||||
case "surface":
|
||||
beginFolderDraft(null, 0);
|
||||
return;
|
||||
case "folder":
|
||||
beginFolderDraft(target.id, (findProjectNodeDepth(projectTreeNodes(), target.id) ?? 0) + 1);
|
||||
return;
|
||||
case "project": {
|
||||
const parentId = findProjectNodeLocation(projectTreeNodes(), target.id)?.parentId ?? null;
|
||||
beginFolderDraft(parentId, parentId ? (findProjectNodeDepth(projectTreeNodes(), parentId) ?? 0) + 1 : 0);
|
||||
return;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const handleSurfaceContextMenu = (event: MouseEvent): void => {
|
||||
event.stopPropagation();
|
||||
contextMenu.openMenu(event, createProjectSurfaceTarget("Projects"));
|
||||
};
|
||||
|
||||
const handleNodePointerDown = (event: PointerEvent, nodeId: string): void => {
|
||||
if (event.button !== 0 || pendingFolderDraft()) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearLongPressTimer();
|
||||
longPressTimer = window.setTimeout(() => {
|
||||
suppressTreeClickTemporarily();
|
||||
setDragState({ draggedNodeId: nodeId, dropTarget: null });
|
||||
}, LONG_PRESS_MS);
|
||||
};
|
||||
|
||||
const handleNodePointerMove = (
|
||||
event: PointerEvent,
|
||||
parentId: string | null,
|
||||
index: number,
|
||||
node: ProjectTreeNode,
|
||||
): void => {
|
||||
const nextDragState = dragState();
|
||||
|
||||
if (!nextDragState) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (nextDragState.draggedNodeId === getProjectTreeNodeId(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bounds = event.currentTarget.getBoundingClientRect();
|
||||
const relativeY = bounds.height <= 0 ? 0.5 : (event.clientY - bounds.top) / bounds.height;
|
||||
let nextTarget: ProjectDragTarget;
|
||||
|
||||
if (node.kind === "folder") {
|
||||
if (relativeY < 0.28) {
|
||||
nextTarget = {
|
||||
parentId,
|
||||
index,
|
||||
intent: "before",
|
||||
targetNodeId: node.id,
|
||||
};
|
||||
} else if (relativeY > 0.72) {
|
||||
nextTarget = {
|
||||
parentId,
|
||||
index: index + 1,
|
||||
intent: "after",
|
||||
targetNodeId: node.id,
|
||||
};
|
||||
} else {
|
||||
nextTarget = {
|
||||
parentId: node.id,
|
||||
index: node.children.length,
|
||||
intent: "inside",
|
||||
targetNodeId: node.id,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
nextTarget = {
|
||||
parentId,
|
||||
index: relativeY < 0.5 ? index : index + 1,
|
||||
intent: relativeY < 0.5 ? "before" : "after",
|
||||
targetNodeId: node.item.id,
|
||||
};
|
||||
}
|
||||
|
||||
setDragState({
|
||||
...nextDragState,
|
||||
dropTarget: nextTarget,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={rootRef}
|
||||
classList={{
|
||||
[styles.root]: true,
|
||||
[styles.rootCompact]: !!props.compact,
|
||||
[styles.rootDragMode]: !!dragState(),
|
||||
}}
|
||||
style={{
|
||||
"--project-drawer-top": `${drawerTop()}px`,
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
ref={triggerRef}
|
||||
classList={{
|
||||
[styles.trigger]: true,
|
||||
[styles.triggerCompact]: !!props.compact,
|
||||
[styles.triggerOpen]: props.isOpen,
|
||||
}}
|
||||
aria-label={`Open project menu for ${selectedProject().name}`}
|
||||
aria-expanded={props.isOpen}
|
||||
aria-haspopup="menu"
|
||||
title={selectedProject().name}
|
||||
onClick={toggleOpen}
|
||||
>
|
||||
<span class={styles.triggerLead} aria-hidden="true">
|
||||
<Folder size={18} strokeWidth={2} />
|
||||
</span>
|
||||
{!props.compact ? (
|
||||
<span class={styles.triggerCopy}>
|
||||
<span class={styles.eyebrow}>Projects</span>
|
||||
<span class={styles.value}>{selectedProject().name}</span>
|
||||
</span>
|
||||
) : null}
|
||||
<ChevronDown
|
||||
classList={{
|
||||
[styles.triggerIcon]: true,
|
||||
[styles.triggerIconOpen]: props.isOpen,
|
||||
}}
|
||||
size={16}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</button>
|
||||
|
||||
<Show when={props.isOpen}>
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
classList={{
|
||||
[styles.scrim]: true,
|
||||
[styles.scrimOpen]: props.isOpen,
|
||||
}}
|
||||
aria-hidden={!props.isOpen}
|
||||
tabIndex={props.isOpen ? 0 : -1}
|
||||
onClick={props.onClose}
|
||||
/>
|
||||
|
||||
<div
|
||||
classList={{
|
||||
[styles.drawer]: true,
|
||||
[styles.drawerOpen]: props.isOpen,
|
||||
}}
|
||||
aria-hidden={!props.isOpen}
|
||||
onContextMenu={handleSurfaceContextMenu}
|
||||
>
|
||||
<div class={styles.drawerBody}>
|
||||
<Show when={!props.compact}>
|
||||
<div class={styles.treeSectionLabel}>Projects</div>
|
||||
</Show>
|
||||
|
||||
<ProjectFolderBranch
|
||||
nodes={projectTreeNodes()}
|
||||
depth={0}
|
||||
parentId={null}
|
||||
selectedProjectId={selectedProject().id}
|
||||
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()}
|
||||
/>
|
||||
</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>
|
||||
);
|
||||
};
|
||||
@@ -1,826 +0,0 @@
|
||||
// Path: Frontend/src/components/shell/WorkspaceSidebar/WorkspaceSidebar.tsx
|
||||
|
||||
import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
||||
import { ChevronLeft, ChevronRight, Folder } from "../../../lib/icons";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import { ProjectSelector } from "../ProjectSelector/ProjectSelector";
|
||||
import {
|
||||
createWorkspaceStaticTarget,
|
||||
createWorkspaceSurfaceTarget,
|
||||
createWorkspaceTreeTarget,
|
||||
getWorkspaceNodeIcon,
|
||||
workspaceSidebarHeaderActions,
|
||||
workspaceStaticItems,
|
||||
type WorkspaceContextMenuAction,
|
||||
type WorkspaceContextMenuTarget,
|
||||
type WorkspaceStaticItem,
|
||||
type WorkspaceTreeNode,
|
||||
} from "../data/shell.data";
|
||||
import { WorkspaceContextMenu } from "../WorkspaceContextMenu/WorkspaceContextMenu";
|
||||
import { createWorkspaceContextMenuController } from "../WorkspaceContextMenu/createWorkspaceContextMenuController";
|
||||
import styles from "./WorkspaceSidebar.module.scss";
|
||||
|
||||
type WorkspaceSidebarProps = {
|
||||
collapsed: boolean;
|
||||
railCollapsed: boolean;
|
||||
onToggleRailCollapse: () => void;
|
||||
};
|
||||
|
||||
type PendingWorkspaceFolderDraft = {
|
||||
parentId: string | null;
|
||||
depth: number;
|
||||
};
|
||||
|
||||
type WorkspaceDragTarget = {
|
||||
parentId: string | null;
|
||||
index: number;
|
||||
intent: "before" | "after" | "inside";
|
||||
targetNodeId?: string;
|
||||
};
|
||||
|
||||
type WorkspaceDragState = {
|
||||
draggedNodeId: string;
|
||||
dropTarget: WorkspaceDragTarget | null;
|
||||
};
|
||||
|
||||
type WorkspaceNodeLocation = {
|
||||
parentId: string | null;
|
||||
index: number;
|
||||
node: WorkspaceTreeNode;
|
||||
};
|
||||
|
||||
const LONG_PRESS_MS = 320;
|
||||
|
||||
const createWorkspaceFolderId = (): string => `folder-${Math.random().toString(36).slice(2, 10)}`;
|
||||
|
||||
const getWorkspaceTreeNodeId = (node: WorkspaceTreeNode): string => node.id;
|
||||
|
||||
const insertWorkspaceFolderNode = (
|
||||
nodes: readonly WorkspaceTreeNode[],
|
||||
parentId: string | null,
|
||||
folder: WorkspaceTreeNode,
|
||||
): readonly WorkspaceTreeNode[] => {
|
||||
if (parentId === null) {
|
||||
return [...nodes, folder];
|
||||
}
|
||||
|
||||
return nodes.map((node) => {
|
||||
if (node.kind !== "folder") {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node.id === parentId) {
|
||||
return {
|
||||
...node,
|
||||
children: [...(node.children ?? []), folder],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...node,
|
||||
children: node.children ? insertWorkspaceFolderNode(node.children, parentId, folder) : node.children,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const findWorkspaceFolderDepth = (nodes: readonly WorkspaceTreeNode[], folderId: string, depth = 0): number | null => {
|
||||
for (const node of nodes) {
|
||||
if (node.kind !== "folder") {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (node.id === folderId) {
|
||||
return depth;
|
||||
}
|
||||
|
||||
const nestedDepth = node.children ? findWorkspaceFolderDepth(node.children, folderId, depth + 1) : null;
|
||||
if (nestedDepth !== null) {
|
||||
return nestedDepth;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const findWorkspaceNodeLocation = (
|
||||
nodes: readonly WorkspaceTreeNode[],
|
||||
nodeId: string,
|
||||
parentId: string | null = null,
|
||||
): WorkspaceNodeLocation | null => {
|
||||
for (let index = 0; index < nodes.length; index += 1) {
|
||||
const node = nodes[index];
|
||||
|
||||
if (node.id === nodeId) {
|
||||
return { parentId, index, node };
|
||||
}
|
||||
|
||||
if (node.kind === "folder" && node.children) {
|
||||
const nestedLocation = findWorkspaceNodeLocation(node.children, nodeId, node.id);
|
||||
|
||||
if (nestedLocation) {
|
||||
return nestedLocation;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const workspaceTreeContainsNode = (nodes: readonly WorkspaceTreeNode[], nodeId: string): boolean => {
|
||||
for (const node of nodes) {
|
||||
if (node.id === nodeId) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (node.kind === "folder" && node.children && workspaceTreeContainsNode(node.children, nodeId)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
};
|
||||
|
||||
const removeWorkspaceTreeNode = (
|
||||
nodes: readonly WorkspaceTreeNode[],
|
||||
nodeId: string,
|
||||
): { nodes: WorkspaceTreeNode[]; removed: WorkspaceTreeNode | null } => {
|
||||
const nextNodes: WorkspaceTreeNode[] = [];
|
||||
let removed: WorkspaceTreeNode | null = null;
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.id === nodeId) {
|
||||
removed = node;
|
||||
continue;
|
||||
}
|
||||
|
||||
if (node.kind === "folder" && node.children) {
|
||||
const result = removeWorkspaceTreeNode(node.children, nodeId);
|
||||
|
||||
if (result.removed) {
|
||||
removed = result.removed;
|
||||
nextNodes.push({
|
||||
...node,
|
||||
children: result.nodes,
|
||||
});
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
nextNodes.push(node);
|
||||
}
|
||||
|
||||
return { nodes: nextNodes, removed };
|
||||
};
|
||||
|
||||
const insertWorkspaceTreeNode = (
|
||||
nodes: readonly WorkspaceTreeNode[],
|
||||
parentId: string | null,
|
||||
index: number,
|
||||
nodeToInsert: WorkspaceTreeNode,
|
||||
): WorkspaceTreeNode[] => {
|
||||
if (parentId === null) {
|
||||
const nextNodes = [...nodes];
|
||||
nextNodes.splice(Math.max(0, Math.min(index, nextNodes.length)), 0, nodeToInsert);
|
||||
return nextNodes;
|
||||
}
|
||||
|
||||
return nodes.map((node) => {
|
||||
if (node.kind !== "folder") {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node.id === parentId) {
|
||||
const nextChildren = [...(node.children ?? [])];
|
||||
nextChildren.splice(Math.max(0, Math.min(index, nextChildren.length)), 0, nodeToInsert);
|
||||
return {
|
||||
...node,
|
||||
children: nextChildren,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...node,
|
||||
children: node.children ? insertWorkspaceTreeNode(node.children, parentId, index, nodeToInsert) : node.children,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const moveWorkspaceTreeNode = (
|
||||
nodes: readonly WorkspaceTreeNode[],
|
||||
draggedNodeId: string,
|
||||
dropTarget: WorkspaceDragTarget,
|
||||
): WorkspaceTreeNode[] => {
|
||||
const location = findWorkspaceNodeLocation(nodes, draggedNodeId);
|
||||
|
||||
if (!location) {
|
||||
return [...nodes];
|
||||
}
|
||||
|
||||
if (
|
||||
location.node.kind === "folder" &&
|
||||
dropTarget.parentId !== null &&
|
||||
((location.node.children && workspaceTreeContainsNode(location.node.children, dropTarget.parentId)) ||
|
||||
dropTarget.parentId === location.node.id)
|
||||
) {
|
||||
return [...nodes];
|
||||
}
|
||||
|
||||
let normalizedIndex = dropTarget.index;
|
||||
|
||||
if (dropTarget.parentId === location.parentId && dropTarget.index > location.index) {
|
||||
normalizedIndex -= 1;
|
||||
}
|
||||
|
||||
if (dropTarget.parentId === location.parentId && normalizedIndex === location.index) {
|
||||
return [...nodes];
|
||||
}
|
||||
|
||||
const removalResult = removeWorkspaceTreeNode(nodes, draggedNodeId);
|
||||
|
||||
if (!removalResult.removed) {
|
||||
return [...nodes];
|
||||
}
|
||||
|
||||
return insertWorkspaceTreeNode(removalResult.nodes, dropTarget.parentId, normalizedIndex, removalResult.removed);
|
||||
};
|
||||
|
||||
const FolderDraftRow = (props: {
|
||||
depth: number;
|
||||
value: string;
|
||||
onInput: (value: string) => void;
|
||||
onSubmit: () => void;
|
||||
onCancel: () => void;
|
||||
}): JSX.Element => {
|
||||
let inputRef: HTMLInputElement | undefined;
|
||||
|
||||
queueMicrotask(() => inputRef?.focus());
|
||||
|
||||
return (
|
||||
<li>
|
||||
<div class={styles.treeInputRow} style={{ "--tree-depth": String(props.depth) }}>
|
||||
<Folder class={styles.icon} size={18} strokeWidth={2} />
|
||||
<input
|
||||
ref={inputRef}
|
||||
type="text"
|
||||
class={styles.treeInput}
|
||||
value={props.value}
|
||||
placeholder="Folder name"
|
||||
onInput={(event): void => props.onInput(event.currentTarget.value)}
|
||||
onBlur={props.onSubmit}
|
||||
onKeyDown={(event): void => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
event.currentTarget.blur();
|
||||
return;
|
||||
}
|
||||
|
||||
if (event.key === "Escape") {
|
||||
event.preventDefault();
|
||||
props.onCancel();
|
||||
event.currentTarget.blur();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
const isContextMenuKeyboardTrigger = (event: KeyboardEvent): boolean => event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");
|
||||
|
||||
const WorkspaceHomeEntry = (props: {
|
||||
item: WorkspaceStaticItem;
|
||||
onOpenContextMenu: (event: MouseEvent, 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 => {
|
||||
const Icon = props.item.icon;
|
||||
const target = createWorkspaceStaticTarget(props.item);
|
||||
|
||||
return (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
classList={{
|
||||
[styles.navItem]: true,
|
||||
[styles.navItemActive]: !!props.item.active,
|
||||
}}
|
||||
aria-current={props.item.active ? "page" : undefined}
|
||||
aria-label={props.item.label}
|
||||
title={props.item.label}
|
||||
data-slot="workspace-static-item"
|
||||
data-target-kind={target.kind}
|
||||
data-active={props.item.active ? "true" : "false"}
|
||||
onContextMenu={(event): void => {
|
||||
event.stopPropagation();
|
||||
props.onOpenContextMenu(event, target);
|
||||
}}
|
||||
onKeyDown={(event): void => {
|
||||
if (!isContextMenuKeyboardTrigger(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
props.onOpenContextMenuFromKeyboard(event.currentTarget, target);
|
||||
}}
|
||||
>
|
||||
<Icon class={styles.icon} size={18} strokeWidth={2} />
|
||||
<span class={styles.label}>{props.item.label}</span>
|
||||
<Show when={props.item.meta}>
|
||||
<span class={styles.itemMeta}>{props.item.meta}</span>
|
||||
</Show>
|
||||
</button>
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
const WorkspaceTreeBranch = (props: {
|
||||
nodes: readonly WorkspaceTreeNode[];
|
||||
parentId?: string | null;
|
||||
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;
|
||||
onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void;
|
||||
}): JSX.Element => {
|
||||
const depth = () => props.depth ?? 0;
|
||||
const parentId = () => props.parentId ?? null;
|
||||
|
||||
return (
|
||||
<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}>
|
||||
{(node, indexAccessor): JSX.Element => {
|
||||
const Icon = getWorkspaceNodeIcon(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 (
|
||||
<li>
|
||||
<button
|
||||
type="button"
|
||||
classList={{
|
||||
[styles.treeItem]: true,
|
||||
[styles.treeItemActive]: !!node.active,
|
||||
[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()) }}
|
||||
aria-expanded={node.kind === "folder" ? !isCollapsed() : undefined}
|
||||
aria-current={node.active ? "page" : undefined}
|
||||
aria-label={node.label}
|
||||
title={node.label}
|
||||
data-slot="workspace-tree-item"
|
||||
data-kind={node.kind}
|
||||
data-item-type={node.kind === "item" ? node.itemType : undefined}
|
||||
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 => {
|
||||
event.stopPropagation();
|
||||
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 => {
|
||||
if (!isContextMenuKeyboardTrigger(event)) {
|
||||
return;
|
||||
}
|
||||
|
||||
event.preventDefault();
|
||||
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} />
|
||||
<span class={styles.label}>{node.label}</span>
|
||||
<Show when={node.meta}>
|
||||
<span class={styles.itemMeta}>{node.meta}</span>
|
||||
</Show>
|
||||
</button>
|
||||
|
||||
<Show when={node.kind === "folder" && !isCollapsed() && (((node.children?.length ?? 0) > 0) || props.pendingFolderDraft?.parentId === node.id)}>
|
||||
<WorkspaceTreeBranch
|
||||
nodes={node.children ?? []}
|
||||
parentId={node.id}
|
||||
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}
|
||||
onOpenContextMenuFromKeyboard={props.onOpenContextMenuFromKeyboard}
|
||||
onNodePointerDown={props.onNodePointerDown}
|
||||
onNodePointerMove={props.onNodePointerMove}
|
||||
dragState={props.dragState}
|
||||
isTreeClickSuppressed={props.isTreeClickSuppressed}
|
||||
/>
|
||||
</Show>
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
</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>
|
||||
);
|
||||
};
|
||||
|
||||
export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false);
|
||||
const [workspaceTreeNodes, setWorkspaceTreeNodes] = createSignal<readonly WorkspaceTreeNode[]>(appShellData.workspaceTree());
|
||||
const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]);
|
||||
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingWorkspaceFolderDraft | null>(null);
|
||||
const [pendingFolderName, setPendingFolderName] = createSignal("");
|
||||
const [dragState, setDragState] = createSignal<WorkspaceDragState | null>(null);
|
||||
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
||||
const contextMenu = createWorkspaceContextMenuController();
|
||||
let longPressTimer: number | undefined;
|
||||
let suppressClickTimer: number | undefined;
|
||||
const railToggleLabel = (): string => (props.railCollapsed ? "Expand server rail" : "Collapse server rail");
|
||||
const sidebarContextMenuTarget = createWorkspaceSurfaceTarget(appShellData.activeProject());
|
||||
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 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(() => {
|
||||
setWorkspaceTreeNodes(appShellData.workspaceTree());
|
||||
setCollapsedFolderIds([]);
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
setDragState(null);
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
const handlePointerUp = (): void => {
|
||||
clearLongPressTimer();
|
||||
|
||||
const nextDragState = dragState();
|
||||
|
||||
if (!nextDragState?.dropTarget) {
|
||||
if (nextDragState) {
|
||||
suppressTreeClickTemporarily();
|
||||
}
|
||||
setDragState(null);
|
||||
return;
|
||||
}
|
||||
|
||||
suppressTreeClickTemporarily();
|
||||
setWorkspaceTreeNodes((current) =>
|
||||
moveWorkspaceTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget),
|
||||
);
|
||||
setDragState(null);
|
||||
};
|
||||
|
||||
const handleEscape = (event: KeyboardEvent): void => {
|
||||
if (event.key !== "Escape") {
|
||||
return;
|
||||
}
|
||||
|
||||
clearLongPressTimer();
|
||||
|
||||
if (dragState()) {
|
||||
setDragState(null);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
window.addEventListener("pointercancel", handlePointerUp);
|
||||
window.addEventListener("keydown", handleEscape);
|
||||
|
||||
onCleanup(() => {
|
||||
clearLongPressTimer();
|
||||
if (suppressClickTimer !== undefined) {
|
||||
window.clearTimeout(suppressClickTimer);
|
||||
}
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
window.removeEventListener("keydown", handleEscape);
|
||||
});
|
||||
});
|
||||
|
||||
const beginFolderDraft = (parentId: string | null, depth: number): void => {
|
||||
if (parentId) {
|
||||
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
|
||||
}
|
||||
|
||||
setPendingFolderName("");
|
||||
setPendingFolderDraft({ parentId, depth });
|
||||
};
|
||||
|
||||
const submitPendingFolder = (): void => {
|
||||
const name = pendingFolderName().trim();
|
||||
const draft = pendingFolderDraft();
|
||||
|
||||
if (!draft) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!name) {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
return;
|
||||
}
|
||||
|
||||
setWorkspaceTreeNodes((current) =>
|
||||
insertWorkspaceFolderNode(current, draft.parentId, {
|
||||
id: createWorkspaceFolderId(),
|
||||
label: name,
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: [],
|
||||
}),
|
||||
);
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
};
|
||||
|
||||
const cancelPendingFolder = (): void => {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
};
|
||||
|
||||
const handleNodePointerDown = (event: PointerEvent, nodeId: string): void => {
|
||||
if (event.button !== 0 || pendingFolderDraft()) {
|
||||
return;
|
||||
}
|
||||
|
||||
clearLongPressTimer();
|
||||
longPressTimer = window.setTimeout(() => {
|
||||
suppressTreeClickTemporarily();
|
||||
setDragState({ draggedNodeId: nodeId, dropTarget: null });
|
||||
}, LONG_PRESS_MS);
|
||||
};
|
||||
|
||||
const handleNodePointerMove = (
|
||||
event: PointerEvent,
|
||||
parentId: string | null,
|
||||
index: number,
|
||||
node: WorkspaceTreeNode,
|
||||
): void => {
|
||||
const nextDragState = dragState();
|
||||
|
||||
if (!nextDragState || nextDragState.draggedNodeId === getWorkspaceTreeNodeId(node)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const bounds = event.currentTarget.getBoundingClientRect();
|
||||
const relativeY = bounds.height <= 0 ? 0.5 : (event.clientY - bounds.top) / bounds.height;
|
||||
let nextTarget: WorkspaceDragTarget;
|
||||
|
||||
if (node.kind === "folder") {
|
||||
if (relativeY < 0.28) {
|
||||
nextTarget = { parentId, index, intent: "before", targetNodeId: node.id };
|
||||
} else if (relativeY > 0.72) {
|
||||
nextTarget = { parentId, index: index + 1, intent: "after", targetNodeId: node.id };
|
||||
} else {
|
||||
nextTarget = {
|
||||
parentId: node.id,
|
||||
index: (node.children ?? []).length,
|
||||
intent: "inside",
|
||||
targetNodeId: node.id,
|
||||
};
|
||||
}
|
||||
} else {
|
||||
nextTarget = {
|
||||
parentId,
|
||||
index: relativeY < 0.5 ? index : index + 1,
|
||||
intent: relativeY < 0.5 ? "before" : "after",
|
||||
targetNodeId: node.id,
|
||||
};
|
||||
}
|
||||
|
||||
setDragState({ ...nextDragState, dropTarget: nextTarget });
|
||||
};
|
||||
|
||||
const handleContextActionSelect = (action: WorkspaceContextMenuAction, target: WorkspaceContextMenuTarget): void => {
|
||||
if (action.id !== "new-folder") {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
case "home":
|
||||
beginFolderDraft(null, 0);
|
||||
return;
|
||||
case "folder":
|
||||
beginFolderDraft(target.id, (findWorkspaceFolderDepth(workspaceTreeNodes(), target.id) ?? 0) + 1);
|
||||
return;
|
||||
case "settings":
|
||||
case "item":
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<aside
|
||||
classList={{
|
||||
[styles.sidebar]: true,
|
||||
[styles.sidebarCollapsed]: props.collapsed,
|
||||
[styles.sidebarDragMode]: !!dragState(),
|
||||
}}
|
||||
aria-label="Left workspace sidebar"
|
||||
data-ui="workspace-sidebar"
|
||||
data-collapsed={props.collapsed ? "true" : "false"}
|
||||
onContextMenu={(event): void => {
|
||||
contextMenu.openMenu(event, sidebarContextMenuTarget);
|
||||
}}
|
||||
>
|
||||
<div
|
||||
classList={{
|
||||
[styles.header]: true,
|
||||
[styles.headerDrawerOpen]: isProjectDrawerOpen(),
|
||||
}}
|
||||
data-slot="workspace-sidebar-header"
|
||||
data-drawer-open={isProjectDrawerOpen() ? "true" : "false"}
|
||||
>
|
||||
<div class={styles.headerActions} data-slot="workspace-sidebar-header-actions">
|
||||
<button
|
||||
type="button"
|
||||
classList={{
|
||||
[styles.headerActionButton]: true,
|
||||
[styles.headerCollapseButton]: true,
|
||||
}}
|
||||
aria-label={railToggleLabel()}
|
||||
title={railToggleLabel()}
|
||||
data-slot="workspace-sidebar-rail-toggle"
|
||||
onClick={props.onToggleRailCollapse}
|
||||
>
|
||||
{props.railCollapsed ? <ChevronRight size={16} strokeWidth={2} /> : <ChevronLeft size={16} strokeWidth={2} />}
|
||||
</button>
|
||||
|
||||
<For each={workspaceSidebarHeaderActions}>
|
||||
{(action): JSX.Element => {
|
||||
const Icon = action.icon;
|
||||
|
||||
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}>
|
||||
<Icon size={16} strokeWidth={2} />
|
||||
</button>
|
||||
);
|
||||
}}
|
||||
</For>
|
||||
</div>
|
||||
|
||||
<div class={styles.headerControls} data-slot="workspace-sidebar-header-controls">
|
||||
<ProjectSelector
|
||||
compact={props.collapsed}
|
||||
isOpen={isProjectDrawerOpen()}
|
||||
onToggle={(): void => {
|
||||
setIsProjectDrawerOpen(true);
|
||||
}}
|
||||
onClose={(): void => {
|
||||
setIsProjectDrawerOpen(false);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div
|
||||
classList={{
|
||||
[styles.section]: true,
|
||||
[styles.sectionHidden]: isProjectDrawerOpen(),
|
||||
}}
|
||||
data-slot="workspace-sidebar-section"
|
||||
>
|
||||
<Show when={!props.collapsed}>
|
||||
<span class={styles.sectionLabel}>Workspace</span>
|
||||
</Show>
|
||||
<div class={styles.navScroller} data-slot="workspace-sidebar-nav-scroller">
|
||||
<ul class={styles.navList} role="list" data-slot="workspace-static-list">
|
||||
<For each={workspaceStaticItems}>
|
||||
{(item): JSX.Element => (
|
||||
<WorkspaceHomeEntry
|
||||
item={item}
|
||||
onOpenContextMenu={contextMenu.openMenu}
|
||||
onOpenContextMenuFromKeyboard={contextMenu.openMenuFromElement}
|
||||
/>
|
||||
)}
|
||||
</For>
|
||||
</ul>
|
||||
|
||||
<Show when={!props.collapsed}>
|
||||
<div class={styles.treeSectionLabel}>Items</div>
|
||||
</Show>
|
||||
|
||||
<div data-slot="workspace-tree-root">
|
||||
<WorkspaceTreeBranch
|
||||
nodes={workspaceTreeNodes()}
|
||||
parentId={null}
|
||||
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>
|
||||
</aside>
|
||||
|
||||
<WorkspaceContextMenu
|
||||
target={contextMenu.menuState()?.target ?? null}
|
||||
position={(() => {
|
||||
const state = contextMenu.menuState();
|
||||
return state
|
||||
? {
|
||||
x: state.x,
|
||||
y: state.y,
|
||||
}
|
||||
: null;
|
||||
})()}
|
||||
menuRef={contextMenu.setMenuRef}
|
||||
onClose={contextMenu.closeMenu}
|
||||
onSelect={handleContextActionSelect}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
};
|
||||
@@ -1,352 +0,0 @@
|
||||
// Path: Frontend/src/components/shell/data/app-shell.context.tsx
|
||||
|
||||
import {
|
||||
createContext,
|
||||
createMemo,
|
||||
createSignal,
|
||||
onMount,
|
||||
useContext,
|
||||
type Accessor,
|
||||
type JSX,
|
||||
} from "solid-js";
|
||||
import { Folder } from "../../../lib/icons";
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
import {
|
||||
activeDepartment as fallbackActiveDepartment,
|
||||
activeProject as fallbackActiveProject,
|
||||
activeServer as fallbackActiveServer,
|
||||
activeUserProfile as fallbackActiveUserProfile,
|
||||
departmentItems as fallbackDepartmentItems,
|
||||
organizationAdminDockActions,
|
||||
personalDockActions,
|
||||
projectItems as fallbackProjectItems,
|
||||
railItems as fallbackRailItems,
|
||||
workspaceTree as fallbackWorkspaceTree,
|
||||
type ActiveDepartment,
|
||||
type ActiveProject,
|
||||
type ActiveServer,
|
||||
type ActiveUserProfile,
|
||||
type DepartmentItem,
|
||||
type ProjectItem,
|
||||
type RailItem,
|
||||
type WorkspaceTreeNode,
|
||||
} from "./shell.data";
|
||||
|
||||
type AppShellInstallation = {
|
||||
id: string;
|
||||
name: string;
|
||||
mode: "personal" | "organizational" | string;
|
||||
access: string;
|
||||
protocol: string;
|
||||
host: string;
|
||||
isBootstrapped: boolean;
|
||||
};
|
||||
|
||||
type AppShellAdmin = {
|
||||
id: string;
|
||||
email: string;
|
||||
displayName: string;
|
||||
isInstanceAdmin: boolean;
|
||||
homeTitle: string;
|
||||
};
|
||||
|
||||
type AppShellOrganization = {
|
||||
id: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
type AppShellDepartment = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
type AppShellTeam = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
departmentId?: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
type AppShellProject = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
departmentId?: string;
|
||||
teamId?: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
};
|
||||
|
||||
type AppShellWorkspace = {
|
||||
id: string;
|
||||
organizationId: string;
|
||||
name: string;
|
||||
slug: string;
|
||||
kind: "organization" | "department" | "team" | "project" | string;
|
||||
departmentId?: string;
|
||||
teamId?: string;
|
||||
projectId?: string;
|
||||
};
|
||||
|
||||
type AppShellPayload = {
|
||||
installation?: AppShellInstallation;
|
||||
admin?: AppShellAdmin;
|
||||
organizations: AppShellOrganization[];
|
||||
departments: AppShellDepartment[];
|
||||
teams: AppShellTeam[];
|
||||
projects: AppShellProject[];
|
||||
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 = {
|
||||
status: Accessor<"idle" | "loading" | "success" | "error">;
|
||||
error: Accessor<string>;
|
||||
installation: Accessor<AppShellInstallation | undefined>;
|
||||
railItems: Accessor<readonly RailItem[]>;
|
||||
activeServer: Accessor<ActiveServer>;
|
||||
activeProject: Accessor<ActiveProject>;
|
||||
activeDepartment: Accessor<ActiveDepartment>;
|
||||
projectItems: Accessor<readonly ProjectItem[]>;
|
||||
departmentItems: Accessor<readonly DepartmentItem[]>;
|
||||
workspaceTree: Accessor<readonly WorkspaceTreeNode[]>;
|
||||
activeUserProfile: Accessor<ActiveUserProfile>;
|
||||
reload: () => Promise<void>;
|
||||
};
|
||||
|
||||
const AppShellContext = createContext<AppShellContextValue>();
|
||||
|
||||
const buildAbbreviation = (name: string, fallback: string): string => {
|
||||
const parts = name
|
||||
.trim()
|
||||
.split(/\s+/)
|
||||
.filter(Boolean);
|
||||
|
||||
if (parts.length === 0) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const abbreviation = parts
|
||||
.slice(0, 2)
|
||||
.map((part) => part[0]?.toUpperCase() ?? "")
|
||||
.join("");
|
||||
|
||||
return abbreviation || fallback;
|
||||
};
|
||||
|
||||
const buildRailItems = (payload: AppShellPayload | null): readonly RailItem[] => {
|
||||
if (!payload?.installation || payload.organizations.length === 0) {
|
||||
return fallbackRailItems;
|
||||
}
|
||||
|
||||
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) => ({
|
||||
id: organization.id,
|
||||
label: serverName || organization.name,
|
||||
abbreviation: buildAbbreviation(serverName || organization.name, kind === "personal" ? "P" : "O"),
|
||||
kind,
|
||||
active: index === 0,
|
||||
}));
|
||||
};
|
||||
|
||||
const buildActiveServer = (payload: AppShellPayload | null): ActiveServer => {
|
||||
const installation = payload?.installation;
|
||||
const organization = payload?.organizations[0];
|
||||
|
||||
if (!installation || !organization) {
|
||||
return fallbackActiveServer;
|
||||
}
|
||||
|
||||
const kind = installation.mode === "personal" ? "personal" : "organization";
|
||||
const serverName = installation.name || organization.name || installation.host;
|
||||
|
||||
return {
|
||||
id: installation.id,
|
||||
name: serverName || fallbackActiveServer.name,
|
||||
abbreviation: buildAbbreviation(serverName, kind === "personal" ? "P" : "O"),
|
||||
kind,
|
||||
connectedLabel: kind === "organization" ? `${payload?.teams.length ?? 0} connected` : undefined,
|
||||
subtitle: kind === "personal" ? installation.host || payload?.admin?.homeTitle || "Personal home" : undefined,
|
||||
dockActions: kind === "personal" ? personalDockActions : organizationAdminDockActions,
|
||||
};
|
||||
};
|
||||
|
||||
const buildProjectItems = (payload: AppShellPayload | null): readonly ProjectItem[] => {
|
||||
if (!payload?.projects.length) {
|
||||
return fallbackProjectItems;
|
||||
}
|
||||
|
||||
return payload.projects.map((project, index) => ({
|
||||
id: project.id,
|
||||
name: project.name,
|
||||
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,
|
||||
}));
|
||||
};
|
||||
|
||||
const buildActiveProject = (payload: AppShellPayload | null): ActiveProject => {
|
||||
const firstProject = payload?.projects[0];
|
||||
|
||||
if (!firstProject) {
|
||||
return fallbackActiveProject;
|
||||
}
|
||||
|
||||
return {
|
||||
id: firstProject.id,
|
||||
name: firstProject.name,
|
||||
};
|
||||
};
|
||||
|
||||
const buildDepartmentItems = (payload: AppShellPayload | null): readonly DepartmentItem[] => {
|
||||
if (!payload?.departments.length) {
|
||||
return fallbackDepartmentItems;
|
||||
}
|
||||
|
||||
return payload.departments.map((department, index) => ({
|
||||
id: department.id,
|
||||
name: department.name,
|
||||
teams: payload.teams
|
||||
.filter((team) => team.departmentId === department.id)
|
||||
.map((team) => team.name),
|
||||
active: index === 0,
|
||||
}));
|
||||
};
|
||||
|
||||
const buildActiveDepartment = (payload: AppShellPayload | null): ActiveDepartment => {
|
||||
const firstDepartment = payload?.departments[0];
|
||||
|
||||
if (!firstDepartment) {
|
||||
return fallbackActiveDepartment;
|
||||
}
|
||||
|
||||
const firstTeamName = payload?.teams.find((team) => team.departmentId === firstDepartment.id)?.name ?? "";
|
||||
|
||||
return {
|
||||
id: firstDepartment.id,
|
||||
name: firstDepartment.name,
|
||||
teamName: firstTeamName,
|
||||
};
|
||||
};
|
||||
|
||||
const buildWorkspaceTree = (payload: AppShellPayload | null): readonly WorkspaceTreeNode[] => {
|
||||
if (!payload?.projects.length) {
|
||||
return fallbackWorkspaceTree;
|
||||
}
|
||||
|
||||
// The workspace tree should represent items inside the current project, not the
|
||||
// project container itself. We do not have project-contents hydration yet, so
|
||||
// return an empty tree rather than showing the project root as a fake item.
|
||||
return [];
|
||||
};
|
||||
|
||||
const buildActiveUserProfile = (payload: AppShellPayload | null): ActiveUserProfile => {
|
||||
if (!payload?.admin) {
|
||||
return fallbackActiveUserProfile;
|
||||
}
|
||||
|
||||
const organizationName = payload.installation?.name || payload.organizations[0]?.name || fallbackActiveServer.name;
|
||||
const departmentName = payload.departments[0]?.name;
|
||||
|
||||
return {
|
||||
name: payload.admin.displayName,
|
||||
email: payload.admin.email,
|
||||
roleLabel: payload.admin.isInstanceAdmin ? "Instance admin" : "Member",
|
||||
contextLabel: departmentName ? `${organizationName} • ${departmentName}` : organizationName,
|
||||
};
|
||||
};
|
||||
|
||||
export const AppShellDataProvider = (props: { children: JSX.Element }): JSX.Element => {
|
||||
const [status, setStatus] = createSignal<"idle" | "loading" | "success" | "error">("idle");
|
||||
const [error, setError] = createSignal("");
|
||||
const [payload, setPayload] = createSignal<AppShellPayload | null>(null);
|
||||
|
||||
const load = async (): Promise<void> => {
|
||||
setStatus("loading");
|
||||
setError("");
|
||||
|
||||
try {
|
||||
const response = await fetch(`${resolveAPIBase()}/app-shell`, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
|
||||
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) {
|
||||
throw new Error(errorMessage || "Failed to load app shell state.");
|
||||
}
|
||||
|
||||
setPayload(normalizeAppShellPayload(body.data));
|
||||
setStatus("success");
|
||||
} catch (loadError) {
|
||||
setStatus("error");
|
||||
setError(loadError instanceof Error ? loadError.message : "Failed to load app shell state.");
|
||||
}
|
||||
};
|
||||
|
||||
onMount(() => {
|
||||
void load();
|
||||
});
|
||||
|
||||
const value: AppShellContextValue = {
|
||||
status,
|
||||
error,
|
||||
installation: createMemo(() => payload()?.installation),
|
||||
railItems: createMemo(() => buildRailItems(payload())),
|
||||
activeServer: createMemo(() => buildActiveServer(payload())),
|
||||
activeProject: createMemo(() => buildActiveProject(payload())),
|
||||
activeDepartment: createMemo(() => buildActiveDepartment(payload())),
|
||||
projectItems: createMemo(() => buildProjectItems(payload())),
|
||||
departmentItems: createMemo(() => buildDepartmentItems(payload())),
|
||||
workspaceTree: createMemo(() => buildWorkspaceTree(payload())),
|
||||
activeUserProfile: createMemo(() => buildActiveUserProfile(payload())),
|
||||
reload: load,
|
||||
};
|
||||
|
||||
return <AppShellContext.Provider value={value}>{props.children}</AppShellContext.Provider>;
|
||||
};
|
||||
|
||||
export const useAppShellData = (): AppShellContextValue => {
|
||||
const context = useContext(AppShellContext);
|
||||
|
||||
if (!context) {
|
||||
throw new Error("useAppShellData must be used within AppShellDataProvider");
|
||||
}
|
||||
|
||||
return context;
|
||||
};
|
||||
@@ -1,722 +0,0 @@
|
||||
// Path: Frontend/src/components/shell/data/shell.data.ts
|
||||
|
||||
import type { Component } from "solid-js";
|
||||
import {
|
||||
Bell,
|
||||
CircleHelp,
|
||||
FileText,
|
||||
Folder,
|
||||
Home,
|
||||
Keyboard,
|
||||
LayoutGrid,
|
||||
LogOut,
|
||||
Repeat,
|
||||
Search,
|
||||
Settings,
|
||||
Shield,
|
||||
User,
|
||||
} from "../../../lib/icons";
|
||||
|
||||
type ShellIconProps = {
|
||||
class?: string;
|
||||
size?: number;
|
||||
strokeWidth?: number;
|
||||
};
|
||||
|
||||
export type ShellIcon = Component<ShellIconProps>;
|
||||
|
||||
export type RailItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
abbreviation: string;
|
||||
kind: "personal" | "organization";
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type ServerDockAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
};
|
||||
|
||||
export type ActiveServer = {
|
||||
id: string;
|
||||
name: string;
|
||||
abbreviation: string;
|
||||
kind: "personal" | "organization";
|
||||
connectedLabel?: string;
|
||||
subtitle?: string;
|
||||
dockActions: readonly ServerDockAction[];
|
||||
};
|
||||
|
||||
export type ActiveProject = {
|
||||
id: string;
|
||||
name: string;
|
||||
};
|
||||
|
||||
export type ActiveDepartment = {
|
||||
id: string;
|
||||
name: string;
|
||||
teamName: string;
|
||||
};
|
||||
|
||||
export type DepartmentItem = {
|
||||
id: string;
|
||||
name: string;
|
||||
teams: readonly string[];
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type ProjectItem = {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
groupLabel?: string;
|
||||
parentLabel?: string;
|
||||
meta?: string;
|
||||
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 = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
active?: boolean;
|
||||
meta?: string;
|
||||
};
|
||||
|
||||
export type WorkspaceStaticKind = "workspace" | "home" | "settings";
|
||||
|
||||
// Keep this open-ended so future server-driven or plugin-provided item types do
|
||||
// not require a frontend source edit before they can be represented safely.
|
||||
export type WorkspaceItemTypeId = string;
|
||||
|
||||
export type WorkspaceStaticItem = SidebarItem & {
|
||||
contextKind: WorkspaceStaticKind;
|
||||
};
|
||||
|
||||
export type WorkspaceFolderNode = {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: "folder";
|
||||
icon: ShellIcon;
|
||||
active?: boolean;
|
||||
meta?: string;
|
||||
children?: readonly WorkspaceTreeNode[];
|
||||
};
|
||||
|
||||
export type WorkspaceItemNode = {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: "item";
|
||||
itemType: WorkspaceItemTypeId;
|
||||
active?: boolean;
|
||||
meta?: string;
|
||||
children?: undefined;
|
||||
};
|
||||
|
||||
export type WorkspaceTreeNode = WorkspaceFolderNode | WorkspaceItemNode;
|
||||
|
||||
export type WorkspaceItemTypeDefinition = {
|
||||
id: WorkspaceItemTypeId;
|
||||
label: string;
|
||||
shortLabel: string;
|
||||
icon: ShellIcon;
|
||||
noun: string;
|
||||
actionPrefix: string;
|
||||
defaultCreateLabel: string;
|
||||
includeInWorkspaceCreate?: boolean;
|
||||
description?: string;
|
||||
};
|
||||
|
||||
export type SidebarHeaderAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
};
|
||||
|
||||
export type TopBarAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
};
|
||||
|
||||
export type MobileBottomNavItem = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
active?: boolean;
|
||||
};
|
||||
|
||||
export type WorkspaceContextMenuTarget =
|
||||
| {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: WorkspaceStaticKind;
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: "folder";
|
||||
}
|
||||
| {
|
||||
id: string;
|
||||
label: string;
|
||||
kind: "item";
|
||||
itemType: WorkspaceItemTypeId;
|
||||
};
|
||||
|
||||
export type WorkspaceContextMenuAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
tone?: "default" | "danger";
|
||||
shortcut?: WorkspaceContextMenuShortcut;
|
||||
children?: readonly WorkspaceContextMenuAction[];
|
||||
};
|
||||
|
||||
export type WorkspaceContextMenuShortcutModifier = "meta" | "alt" | "shift";
|
||||
|
||||
export type WorkspaceContextMenuShortcutKey = "b" | "c" | "d" | "delete" | "enter" | "f" | "m" | "r";
|
||||
|
||||
export type WorkspaceContextMenuShortcut = {
|
||||
modifiers?: readonly WorkspaceContextMenuShortcutModifier[];
|
||||
key: WorkspaceContextMenuShortcutKey;
|
||||
};
|
||||
|
||||
export type WorkspaceContextMenuSection = {
|
||||
id: string;
|
||||
label?: string;
|
||||
items: readonly WorkspaceContextMenuAction[];
|
||||
};
|
||||
|
||||
export const firstPartyWorkspaceItemTypes: readonly WorkspaceItemTypeDefinition[] = [
|
||||
{
|
||||
id: "core.doc",
|
||||
label: "Doc",
|
||||
shortLabel: "Doc",
|
||||
icon: FileText,
|
||||
noun: "doc",
|
||||
actionPrefix: "doc",
|
||||
defaultCreateLabel: "New doc",
|
||||
includeInWorkspaceCreate: true,
|
||||
description: "Rich text documents and notes.",
|
||||
},
|
||||
{
|
||||
id: "core.board.kanban",
|
||||
label: "Kanban board",
|
||||
shortLabel: "Board",
|
||||
icon: LayoutGrid,
|
||||
noun: "board",
|
||||
actionPrefix: "board",
|
||||
defaultCreateLabel: "New board",
|
||||
includeInWorkspaceCreate: true,
|
||||
description: "Default board-style workspace item.",
|
||||
},
|
||||
{
|
||||
id: "core.board.list",
|
||||
label: "List board",
|
||||
shortLabel: "Board",
|
||||
icon: LayoutGrid,
|
||||
noun: "board",
|
||||
actionPrefix: "list-board",
|
||||
defaultCreateLabel: "New list board",
|
||||
description: "Alternate first-party board view prepared for the future registry.",
|
||||
},
|
||||
] as const;
|
||||
|
||||
const workspaceItemTypeMap = new Map<WorkspaceItemTypeId, WorkspaceItemTypeDefinition>(
|
||||
firstPartyWorkspaceItemTypes.map((definition) => [definition.id, definition]),
|
||||
);
|
||||
|
||||
const createUnknownWorkspaceItemTypeDefinition = (
|
||||
itemType: WorkspaceItemTypeId,
|
||||
): WorkspaceItemTypeDefinition => ({
|
||||
id: itemType,
|
||||
label: "Item",
|
||||
shortLabel: "Item",
|
||||
icon: FileText,
|
||||
noun: "item",
|
||||
actionPrefix: "item",
|
||||
defaultCreateLabel: "New item",
|
||||
description: "Fallback definition for unknown or future workspace item types.",
|
||||
});
|
||||
|
||||
export const getWorkspaceItemTypeDefinition = (itemType: WorkspaceItemTypeId): WorkspaceItemTypeDefinition => {
|
||||
return workspaceItemTypeMap.get(itemType) ?? createUnknownWorkspaceItemTypeDefinition(itemType);
|
||||
};
|
||||
|
||||
export const getWorkspaceNodeIcon = (node: WorkspaceTreeNode): ShellIcon =>
|
||||
node.kind === "folder" ? node.icon : getWorkspaceItemTypeDefinition(node.itemType).icon;
|
||||
|
||||
const getWorkspaceCreateActions = (): readonly WorkspaceContextMenuAction[] => [
|
||||
{ id: "new-folder", label: "New folder", shortcut: { modifiers: ["alt"], key: "f" } },
|
||||
...firstPartyWorkspaceItemTypes
|
||||
.filter((definition) => definition.includeInWorkspaceCreate)
|
||||
.map((definition) => ({
|
||||
id: `create-${definition.actionPrefix}`,
|
||||
label: definition.defaultCreateLabel,
|
||||
shortcut:
|
||||
definition.id === "core.board.kanban"
|
||||
? ({ modifiers: ["alt"], key: "b" } as const)
|
||||
: definition.id === "core.doc"
|
||||
? ({ modifiers: ["alt"], key: "d" } as const)
|
||||
: undefined,
|
||||
})),
|
||||
];
|
||||
|
||||
export const getWorkspaceContextMenuEyebrow = (target: WorkspaceContextMenuTarget): string => {
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
case "home":
|
||||
return "Workspace";
|
||||
case "settings":
|
||||
return "Configuration";
|
||||
case "folder":
|
||||
return "Folder";
|
||||
case "item":
|
||||
return getWorkspaceItemTypeDefinition(target.itemType).shortLabel;
|
||||
}
|
||||
};
|
||||
|
||||
export const createWorkspaceSurfaceTarget = (workspace: ActiveProject): WorkspaceContextMenuTarget => ({
|
||||
id: `workspace-${workspace.id}`,
|
||||
label: workspace.name,
|
||||
kind: "workspace",
|
||||
});
|
||||
|
||||
export const createWorkspaceStaticTarget = (item: WorkspaceStaticItem): WorkspaceContextMenuTarget => ({
|
||||
id: item.id,
|
||||
label: item.label,
|
||||
kind: item.contextKind,
|
||||
});
|
||||
|
||||
export const createWorkspaceTreeTarget = (node: WorkspaceTreeNode): WorkspaceContextMenuTarget => ({
|
||||
id: node.id,
|
||||
label: node.label,
|
||||
...(node.kind === "folder"
|
||||
? { kind: "folder" as const }
|
||||
: {
|
||||
kind: "item" as const,
|
||||
itemType: node.itemType,
|
||||
}),
|
||||
});
|
||||
|
||||
export type NotificationItem = {
|
||||
id: string;
|
||||
title: string;
|
||||
contextLabel: string;
|
||||
timeLabel: string;
|
||||
unread?: boolean;
|
||||
};
|
||||
|
||||
export type ProfileMenuAction = {
|
||||
id: string;
|
||||
label: string;
|
||||
icon: ShellIcon;
|
||||
tone?: "default" | "danger";
|
||||
};
|
||||
|
||||
export type ProfileMenuSection = {
|
||||
id: string;
|
||||
items: readonly ProfileMenuAction[];
|
||||
};
|
||||
|
||||
export type ActiveUserProfile = {
|
||||
name: string;
|
||||
email: string;
|
||||
roleLabel: string;
|
||||
contextLabel: string;
|
||||
};
|
||||
|
||||
export const personalDockActions: readonly ServerDockAction[] = [
|
||||
{ id: "account", label: "Account", icon: User },
|
||||
{ id: "settings", label: "Settings", icon: Settings },
|
||||
] as const;
|
||||
|
||||
export const organizationAdminDockActions: readonly ServerDockAction[] = [
|
||||
{ id: "members", label: "Members", icon: User },
|
||||
{ id: "server", label: "Server", icon: Settings },
|
||||
] as const;
|
||||
|
||||
// Server shell scaffold data
|
||||
export const railItems: readonly RailItem[] = [
|
||||
{ id: "personal-server", label: "Personal Server Name", abbreviation: "P", kind: "personal" },
|
||||
{ id: "organization-server", label: "Organization Name", abbreviation: "O", kind: "organization", active: true },
|
||||
{ id: "design-review", label: "Design Review", abbreviation: "D", kind: "organization" },
|
||||
] as const;
|
||||
|
||||
export const activeServer: ActiveServer = {
|
||||
id: "organization-server",
|
||||
name: "Organization Name",
|
||||
abbreviation: "O",
|
||||
kind: "organization",
|
||||
connectedLabel: "12 connected",
|
||||
dockActions: organizationAdminDockActions,
|
||||
};
|
||||
|
||||
// Workspace framing scaffold data
|
||||
export const activeProject: ActiveProject = {
|
||||
id: "general",
|
||||
name: "General",
|
||||
};
|
||||
|
||||
export const activeDepartment: ActiveDepartment = {
|
||||
id: "product",
|
||||
name: "Product",
|
||||
teamName: "Design Systems",
|
||||
};
|
||||
|
||||
export const projectItems: readonly ProjectItem[] = [
|
||||
{
|
||||
id: "general",
|
||||
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;
|
||||
|
||||
export const departmentItems: readonly DepartmentItem[] = [
|
||||
{ id: "product", name: "Product", teams: ["Design Systems", "Research Ops"], active: true },
|
||||
{ id: "engineering", name: "Engineering", teams: ["Platform", "Realtime Collaboration"] },
|
||||
{ id: "operations", name: "Operations", teams: ["Shared Services", "People Ops"] },
|
||||
] as const;
|
||||
|
||||
// Sidebar and topbar scaffold data
|
||||
// These static entries stay pinned in both desktop and mobile workspace navigation.
|
||||
export const workspaceStaticItems: readonly WorkspaceStaticItem[] = [
|
||||
{ id: "home", label: "Home", icon: Home, active: true, contextKind: "home" },
|
||||
{ id: "workspace-settings", label: "Settings", icon: Settings, contextKind: "settings" },
|
||||
] as const;
|
||||
|
||||
// Freeform workspace tree scaffold: folders are structural, while non-folder
|
||||
// nodes already flow through the future-safe itemType registry seam.
|
||||
export const workspaceTree: readonly WorkspaceTreeNode[] = [
|
||||
{
|
||||
id: "product-workspace",
|
||||
label: "Product",
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{ id: "roadmap-board", label: "Roadmap", kind: "item", itemType: "core.board.kanban", active: true },
|
||||
{ id: "launch-brief", label: "Launch Brief", kind: "item", itemType: "core.doc" },
|
||||
{
|
||||
id: "research-folder",
|
||||
label: "Research",
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{ id: "interviews-doc", label: "Interviews", kind: "item", itemType: "core.doc" },
|
||||
{ id: "signals-board", label: "Signals", kind: "item", itemType: "core.board.kanban", meta: "2" },
|
||||
],
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "design-folder",
|
||||
label: "Design",
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: [
|
||||
{ id: "system-doc", label: "Design System", kind: "item", itemType: "core.doc" },
|
||||
{ id: "review-board", label: "Review Queue", kind: "item", itemType: "core.board.kanban" },
|
||||
],
|
||||
},
|
||||
{ id: "general-notes", label: "General Notes", kind: "item", itemType: "core.doc" },
|
||||
] as const;
|
||||
|
||||
export const workspaceSidebarHeaderActions: readonly SidebarHeaderAction[] = [
|
||||
{ id: "search-workspace", label: "Search workspace", icon: Search },
|
||||
] as const;
|
||||
|
||||
export const mobileBottomNavItems: readonly MobileBottomNavItem[] = [
|
||||
{ id: "home", label: "Home", icon: Home, active: true },
|
||||
{ id: "search", label: "Search", icon: Search },
|
||||
{ id: "browse", label: "Browse", icon: Folder },
|
||||
] as const;
|
||||
|
||||
// Initial context-menu IA scaffold. Behavior wiring can evolve later, but the
|
||||
// target kinds and action grouping should stay shared across workspace surfaces.
|
||||
export const getWorkspaceContextMenuSections = (
|
||||
target: WorkspaceContextMenuTarget,
|
||||
): readonly WorkspaceContextMenuSection[] => {
|
||||
const createActions = getWorkspaceCreateActions();
|
||||
|
||||
const createSubmenuAction = {
|
||||
id: "create",
|
||||
label: "Create",
|
||||
children: createActions,
|
||||
} as const;
|
||||
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
return [
|
||||
{
|
||||
id: "create",
|
||||
label: undefined,
|
||||
items: [createSubmenuAction],
|
||||
},
|
||||
{
|
||||
id: "workspace",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: "rename-workspace", label: "Rename workspace", shortcut: { key: "enter" } },
|
||||
{ id: "copy-workspace-link", label: "Copy link", shortcut: { modifiers: ["meta"], key: "c" } },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
case "home":
|
||||
return [
|
||||
{
|
||||
id: "create",
|
||||
label: undefined,
|
||||
items: [createSubmenuAction],
|
||||
},
|
||||
{
|
||||
id: "workspace",
|
||||
label: undefined,
|
||||
items: [{ id: "open-home", label: "Open home", shortcut: { key: "enter" } }],
|
||||
},
|
||||
] as const;
|
||||
case "settings":
|
||||
return [
|
||||
{
|
||||
id: "settings",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: "open-settings", label: "Open settings", shortcut: { key: "enter" } },
|
||||
{ id: "copy-settings-link", label: "Copy link", shortcut: { modifiers: ["meta"], key: "c" } },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
case "folder":
|
||||
return [
|
||||
{
|
||||
id: "open",
|
||||
items: [
|
||||
{ id: "open-folder", label: "Open folder", shortcut: { key: "enter" } },
|
||||
{ id: "rename-folder", label: "Rename", shortcut: { modifiers: ["meta"], key: "r" } },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "create",
|
||||
label: undefined,
|
||||
items: [createSubmenuAction],
|
||||
},
|
||||
{
|
||||
id: "organize",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: "duplicate-folder", label: "Duplicate", shortcut: { modifiers: ["meta"], key: "d" } },
|
||||
{ id: "move-folder", label: "Move", shortcut: { modifiers: ["meta"], key: "m" } },
|
||||
{ id: "delete-folder", label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
case "item": {
|
||||
const definition = getWorkspaceItemTypeDefinition(target.itemType);
|
||||
const actionPrefix = definition.actionPrefix;
|
||||
const nounLabel = definition.noun;
|
||||
|
||||
return [
|
||||
{
|
||||
id: `${actionPrefix}-primary`,
|
||||
items: [
|
||||
{ id: `open-${actionPrefix}`, label: `Open ${nounLabel}`, shortcut: { key: "enter" } },
|
||||
{ id: `rename-${actionPrefix}`, label: "Rename", shortcut: { modifiers: ["meta"], key: "r" } },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "organize",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: `duplicate-${actionPrefix}`, label: "Duplicate", shortcut: { modifiers: ["meta"], key: "d" } },
|
||||
{ id: `move-${actionPrefix}`, label: "Move", shortcut: { modifiers: ["meta"], key: "m" } },
|
||||
{ id: `delete-${actionPrefix}`, label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const getProjectCreateActions = (): readonly ProjectContextMenuAction[] =>
|
||||
[
|
||||
{ id: "new-project", label: "New project" },
|
||||
{ id: "new-folder", label: "New folder" },
|
||||
] 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,
|
||||
},
|
||||
] as const;
|
||||
case "project":
|
||||
return [
|
||||
{
|
||||
id: "create",
|
||||
items: createActions,
|
||||
},
|
||||
] as const;
|
||||
}
|
||||
};
|
||||
|
||||
export const topBarActions: readonly TopBarAction[] = [
|
||||
{ id: "search", label: "Search", icon: Search },
|
||||
] as const;
|
||||
|
||||
export const notificationItems: readonly NotificationItem[] = [
|
||||
{
|
||||
id: "comment-design-systems",
|
||||
title: "New comment on Design Systems",
|
||||
contextLabel: "Product • Review thread updated",
|
||||
timeLabel: "2m ago",
|
||||
unread: true,
|
||||
},
|
||||
{
|
||||
id: "sprint-platform",
|
||||
title: "Sprint updated in Platform",
|
||||
contextLabel: "Engineering • Scope changed",
|
||||
timeLabel: "15m ago",
|
||||
unread: true,
|
||||
},
|
||||
{
|
||||
id: "member-joined",
|
||||
title: "New member joined Operations",
|
||||
contextLabel: "Organization Name • Access granted",
|
||||
timeLabel: "1h ago",
|
||||
},
|
||||
{
|
||||
id: "daily-summary",
|
||||
title: "Daily summary is ready",
|
||||
contextLabel: "General • 8 updates across boards",
|
||||
timeLabel: "Today, 8:00 AM",
|
||||
},
|
||||
] as const;
|
||||
|
||||
export const unreadNotificationCount = notificationItems.filter((item) => item.unread).length;
|
||||
|
||||
export const activeUserProfile: ActiveUserProfile = {
|
||||
name: "Demo Account",
|
||||
email: "demo@moku.work",
|
||||
roleLabel: "Founder · Product",
|
||||
contextLabel: "Organization Name • Design Systems",
|
||||
};
|
||||
|
||||
export const profileMenuSections: readonly ProfileMenuSection[] = [
|
||||
{
|
||||
id: "account",
|
||||
items: [
|
||||
{ id: "profile", label: "Profile", icon: User },
|
||||
{ id: "account-settings", label: "Account Settings", icon: Settings },
|
||||
{ id: "notifications", label: "Notifications", icon: Bell },
|
||||
{ id: "security", label: "Security", icon: Shield },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "preferences",
|
||||
items: [
|
||||
{ id: "keyboard-shortcuts", label: "Keyboard Shortcuts", icon: Keyboard },
|
||||
{ id: "theme-preferences", label: "Theme Preferences", icon: Settings },
|
||||
{ id: "help-support", label: "Help & Support", icon: CircleHelp },
|
||||
],
|
||||
},
|
||||
{
|
||||
id: "session",
|
||||
items: [
|
||||
{ id: "switch-account", label: "Switch Account", icon: Repeat },
|
||||
{ id: "sign-out", label: "Sign Out", icon: LogOut, tone: "danger" },
|
||||
],
|
||||
},
|
||||
] as const;
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { For, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
||||
import { ChevronDown } from "../../../lib/icons";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import { type DepartmentItem } from "../data/shell.data";
|
||||
import { useAppShellData } from "../../app-shell/data/app-shell.context";
|
||||
import { type DepartmentItem } from "../../app-shell/data/shell.data";
|
||||
import styles from "./DepartmentSelector.module.scss";
|
||||
|
||||
export const DepartmentSelector = (): JSX.Element => {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import type { JSX } from "solid-js";
|
||||
import { Bell } from "../../../lib/icons";
|
||||
import { unreadNotificationCount } from "../data/shell.data";
|
||||
import { unreadNotificationCount } from "../../app-shell/data/shell.data";
|
||||
import styles from "./NotificationsButton.module.scss";
|
||||
|
||||
type NotificationsButtonProps = {
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
import { For, Show, type JSX } from "solid-js";
|
||||
import { Bell, Settings } from "../../../lib/icons";
|
||||
import { notificationItems, unreadNotificationCount } from "../data/shell.data";
|
||||
import { notificationItems, unreadNotificationCount } from "../../app-shell/data/shell.data";
|
||||
import styles from "./NotificationsMenu.module.scss";
|
||||
|
||||
type NotificationsMenuProps = {
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
import { For, type JSX } from "solid-js";
|
||||
import { User } from "../../../lib/icons";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import { profileMenuSections } from "../data/shell.data";
|
||||
import { useAppShellData } from "../../app-shell/data/app-shell.context";
|
||||
import { profileMenuSections } from "../../app-shell/data/shell.data";
|
||||
import styles from "./ProfileMenu.module.scss";
|
||||
|
||||
type ProfileMenuProps = {
|
||||
+2
-2
@@ -1,7 +1,7 @@
|
||||
// Path: Frontend/src/components/shell/TopBar/ThemeToggle.tsx
|
||||
// Path: Frontend/src/components/top-bar/TopBar/ThemeToggle.tsx
|
||||
|
||||
import type { JSX } from "solid-js";
|
||||
import type { Theme } from "../../../theme/runtime";
|
||||
import type { Theme } from "../../../helper/themeRuntime";
|
||||
import { Moon, Sun } from "../../../lib/icons";
|
||||
import styles from "./ThemeToggle.module.scss";
|
||||
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
// Path: Frontend/src/components/shell/TopBar/TopBar.tsx
|
||||
// Path: Frontend/src/components/top-bar/TopBar/TopBar.tsx
|
||||
|
||||
import { For, type JSX } from "solid-js";
|
||||
import type { Theme } from "../../../theme/runtime";
|
||||
import { topBarActions } from "../data/shell.data";
|
||||
import type { Theme } from "../../../helper/themeRuntime";
|
||||
import { topBarActions } from "../../app-shell/data/shell.data";
|
||||
import { DepartmentSelector } from "../DepartmentSelector/DepartmentSelector";
|
||||
import { NotificationsNav } from "./NotificationsNav";
|
||||
import { ThemeToggle } from "./ThemeToggle";
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
// Path: Frontend/src/components/shell/TopBar/UserNavButton.tsx
|
||||
// Path: Frontend/src/components/top-bar/TopBar/UserNavButton.tsx
|
||||
|
||||
import type { JSX } from "solid-js";
|
||||
import { User } from "../../../lib/icons";
|
||||
@@ -0,0 +1,25 @@
|
||||
/* Path: Frontend/src/components/workspace-home/WorkspaceHome.module.scss */
|
||||
|
||||
.viewport {
|
||||
--workspace-content-max-width: var(--content-width-wide);
|
||||
|
||||
min-width: 0;
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-5) var(--space-6);
|
||||
}
|
||||
|
||||
.title {
|
||||
@include text-display;
|
||||
font-family: var(--font-family-display);
|
||||
max-width: 12ch;
|
||||
}
|
||||
|
||||
@include respond-down(mobile) {
|
||||
.viewport {
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-4) var(--space-4) calc(var(--space-8) + env(safe-area-inset-bottom, 0px));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
// Path: Frontend/src/components/workspace-home/WorkspaceHome.tsx
|
||||
|
||||
import { type JSX } from "solid-js";
|
||||
import { useAppShellData } from "../app-shell/data/app-shell.context";
|
||||
import styles from "./WorkspaceHome.module.scss";
|
||||
|
||||
export const WorkspaceHome = (): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
|
||||
return (
|
||||
<main class={styles.viewport} data-ui="workspace-home">
|
||||
<h1 class={styles.title}>{appShellData.activeServer().name}</h1>
|
||||
</main>
|
||||
);
|
||||
};
|
||||
@@ -1,582 +0,0 @@
|
||||
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.tsx
|
||||
|
||||
import { For, Show, createEffect, createMemo, createSignal, type JSX } from "solid-js";
|
||||
import { Portal } from "solid-js/web";
|
||||
import { createStore } from "solid-js/store";
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
import { ChevronLeft, ChevronRight } from "../../../lib/icons";
|
||||
import { useAppShellData } from "../../shell/data/app-shell.context";
|
||||
import styles from "./WorkspaceHome.module.scss";
|
||||
|
||||
type BootstrapStepKey = "instance" | "mode" | "admin" | "structure";
|
||||
|
||||
type BootstrapStepDefinition = {
|
||||
id: BootstrapStepKey;
|
||||
title: string;
|
||||
buttonLabel: string;
|
||||
};
|
||||
|
||||
type BootstrapSubmissionState = {
|
||||
status: "idle" | "submitting" | "success" | "error";
|
||||
error: string;
|
||||
};
|
||||
|
||||
const bootstrapStepDefinitions: readonly BootstrapStepDefinition[] = [
|
||||
{
|
||||
id: "instance",
|
||||
title: "Instance shape",
|
||||
buttonLabel: "Save and continue",
|
||||
},
|
||||
{
|
||||
id: "mode",
|
||||
title: "Server mode",
|
||||
buttonLabel: "Save and continue",
|
||||
},
|
||||
{
|
||||
id: "admin",
|
||||
title: "Admin account",
|
||||
buttonLabel: "Save and continue",
|
||||
},
|
||||
{
|
||||
id: "structure",
|
||||
title: "Initial structure",
|
||||
buttonLabel: "Submit",
|
||||
},
|
||||
];
|
||||
|
||||
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 => ({
|
||||
status: "idle",
|
||||
error: "",
|
||||
});
|
||||
|
||||
const readResponseBody = async (response: Response): Promise<unknown> => {
|
||||
const raw = await response.text();
|
||||
|
||||
if (!raw.trim()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return raw;
|
||||
}
|
||||
};
|
||||
|
||||
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 = {
|
||||
sidebarCollapsed: boolean;
|
||||
onToggleSidebarCollapse: () => void;
|
||||
};
|
||||
|
||||
export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
const [instanceForm, setInstanceForm] = createStore({ ...defaultInstanceForm });
|
||||
const [modeForm, setModeForm] = createStore({ ...defaultModeForm });
|
||||
const [adminForm, setAdminForm] = createStore({ ...defaultAdminForm });
|
||||
const [structureForm, setStructureForm] = createStore({ ...defaultStructureForm });
|
||||
const [stepState, setStepState] = createStore<Record<BootstrapStepKey, BootstrapSubmissionState>>({
|
||||
instance: initialSubmissionState(),
|
||||
mode: initialSubmissionState(),
|
||||
admin: initialSubmissionState(),
|
||||
structure: initialSubmissionState(),
|
||||
});
|
||||
const [isBootstrapStateResolved, setIsBootstrapStateResolved] = createSignal(false);
|
||||
const [isBootstrapComplete, setIsBootstrapComplete] = createSignal(false);
|
||||
const [isWizardOpen, setIsWizardOpen] = createSignal(false);
|
||||
const [currentStepIndex, setCurrentStepIndex] = createSignal(0);
|
||||
|
||||
createEffect(() => {
|
||||
if (modeForm.mode === "personal") {
|
||||
setStructureForm("departmentName", personalStructureDefaults.departmentName);
|
||||
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);
|
||||
});
|
||||
|
||||
const sidebarToggleLabel = (): string =>
|
||||
props.sidebarCollapsed ? "Expand left workspace sidebar" : "Collapse left workspace sidebar";
|
||||
const breadcrumb = (): string => `${appShellData.activeServer().name} / ${appShellData.activeProject().name} / Home`;
|
||||
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>(
|
||||
() => bootstrapStepDefinitions[currentStepIndex()] ?? bootstrapStepDefinitions[0]!,
|
||||
);
|
||||
const currentStepState = createMemo<BootstrapSubmissionState>(() => stepState[currentStep().id]);
|
||||
const isFirstStep = (): boolean => currentStepIndex() === 0;
|
||||
const isLastStep = (): boolean => currentStepIndex() === bootstrapStepDefinitions.length - 1;
|
||||
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> => {
|
||||
setStepState(step, { status: "submitting", error: "" });
|
||||
|
||||
try {
|
||||
const response = await fetch(`${apiBase()}/bootstrap/steps/${step}`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
Accept: "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const data = await readResponseBody(response);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(readResponseError(step, data));
|
||||
}
|
||||
|
||||
setStepState(step, {
|
||||
status: "success",
|
||||
error: "",
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (error) {
|
||||
setStepState(step, {
|
||||
status: "error",
|
||||
error: error instanceof Error ? error.message : `Bootstrap ${step} request failed.`,
|
||||
});
|
||||
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const payloadForStep = (step: BootstrapStepKey): unknown => {
|
||||
switch (step) {
|
||||
case "instance":
|
||||
return instanceForm;
|
||||
case "mode":
|
||||
return modeForm;
|
||||
case "admin":
|
||||
return adminForm;
|
||||
case "structure":
|
||||
return structureForm;
|
||||
}
|
||||
};
|
||||
|
||||
const submitCurrentStep = async (): Promise<void> => {
|
||||
const step = currentStep().id;
|
||||
const didSucceed = await submitStep(step, payloadForStep(step));
|
||||
|
||||
if (!didSucceed) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (isLastStep()) {
|
||||
await appShellData.reload();
|
||||
const installationAccessor = appShellData.installation;
|
||||
const installation = typeof installationAccessor === "function" ? installationAccessor() : undefined;
|
||||
const isPersistedBootstrap = installation?.isBootstrapped ?? false;
|
||||
|
||||
setIsBootstrapComplete(isPersistedBootstrap);
|
||||
setIsWizardOpen(!isPersistedBootstrap);
|
||||
setIsBootstrapStateResolved(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentStepIndex((index) => Math.min(index + 1, bootstrapStepDefinitions.length - 1));
|
||||
};
|
||||
|
||||
const handleCurrentStepSubmit: JSX.EventHandler<HTMLFormElement, SubmitEvent> = (event): void => {
|
||||
event.preventDefault();
|
||||
void submitCurrentStep();
|
||||
};
|
||||
|
||||
const statusLabel = (state: BootstrapSubmissionState): string => {
|
||||
switch (state.status) {
|
||||
case "submitting":
|
||||
return "Sending";
|
||||
case "success":
|
||||
return "Saved";
|
||||
case "error":
|
||||
return "Request failed";
|
||||
default:
|
||||
return "Ready";
|
||||
}
|
||||
};
|
||||
|
||||
const stepStatusLabel = (step: BootstrapStepDefinition): string => {
|
||||
const state = stepState[step.id];
|
||||
|
||||
if (state.status === "success") {
|
||||
return "Done";
|
||||
}
|
||||
|
||||
if (state.status === "error") {
|
||||
return "Needs retry";
|
||||
}
|
||||
|
||||
return "";
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<main class={styles.viewport} data-ui="workspace-home">
|
||||
<div class={styles.workspaceTopBar} data-slot="workspace-home-top-bar">
|
||||
<div class={styles.workspaceTopBarStart} data-slot="workspace-home-top-bar-start">
|
||||
<button
|
||||
type="button"
|
||||
class={styles.workspaceCollapseButton}
|
||||
aria-label={sidebarToggleLabel()}
|
||||
title={sidebarToggleLabel()}
|
||||
data-slot="workspace-home-sidebar-toggle"
|
||||
onClick={props.onToggleSidebarCollapse}
|
||||
>
|
||||
{props.sidebarCollapsed ? <ChevronRight size={16} strokeWidth={2} /> : <ChevronLeft size={16} strokeWidth={2} />}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div class={styles.workspaceTopBarCenter} data-slot="workspace-home-top-bar-center">
|
||||
<span class={styles.workspaceBreadcrumb}>{breadcrumb()}</span>
|
||||
</div>
|
||||
|
||||
<div class={styles.workspaceTopBarEnd} data-slot="workspace-home-top-bar-end" aria-hidden="true" />
|
||||
</div>
|
||||
|
||||
<section class={styles.hero} data-slot="workspace-home-hero">
|
||||
<h1 class={styles.title}>{isBootstrapComplete() ? appShellData.activeServer().name : bootstrapTargetLabel()}</h1>
|
||||
<Show when={isBootstrapStateResolved() && !isBootstrapComplete()}>
|
||||
<div class={styles.heroActions}>
|
||||
<button type="button" class={styles.primaryButton} onClick={(): void => setIsWizardOpen(true)}>
|
||||
Open bootstrap wizard
|
||||
</button>
|
||||
</div>
|
||||
</Show>
|
||||
</section>
|
||||
</main>
|
||||
|
||||
<Show when={isBootstrapStateResolved() && isWizardOpen()}>
|
||||
<Portal>
|
||||
<div class={styles.wizardLayer} data-ui="bootstrap-wizard" data-step={currentStep().id}>
|
||||
<div class={styles.wizardBackdrop} aria-hidden="true" />
|
||||
|
||||
<section class={styles.wizardPanel} role="dialog" aria-modal="true" aria-labelledby="bootstrap-wizard-title" data-slot="bootstrap-wizard-panel">
|
||||
<header class={styles.wizardHeader} data-slot="bootstrap-wizard-header">
|
||||
<div class={styles.wizardHeaderCopy}>
|
||||
<h2 id="bootstrap-wizard-title" class={styles.wizardTitle}>
|
||||
Bootstrap {bootstrapTargetLabel()}
|
||||
</h2>
|
||||
</div>
|
||||
<Show when={canDismissWizard()}>
|
||||
<button type="button" class={styles.wizardCloseButton} onClick={(): void => setIsWizardOpen(false)}>
|
||||
Close
|
||||
</button>
|
||||
</Show>
|
||||
</header>
|
||||
|
||||
<div class={styles.wizardBody}>
|
||||
<aside class={styles.wizardSidebar} data-slot="bootstrap-wizard-sidebar">
|
||||
<nav class={styles.wizardSteps} aria-label="Bootstrap steps">
|
||||
<For each={bootstrapStepDefinitions}>
|
||||
{(step, index): JSX.Element => (
|
||||
<button
|
||||
type="button"
|
||||
class={styles.wizardStepButton}
|
||||
data-active={step.id === currentStep().id ? "true" : "false"}
|
||||
disabled={index() > currentStepIndex()}
|
||||
onClick={(): void => {
|
||||
if (index() <= currentStepIndex()) {
|
||||
setCurrentStepIndex(index());
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span class={styles.wizardStepIndex}>{index() + 1}</span>
|
||||
<span class={styles.wizardStepCopy}>
|
||||
<strong>{step.title}</strong>
|
||||
<Show when={stepStatusLabel(step)}>
|
||||
<small>{stepStatusLabel(step)}</small>
|
||||
</Show>
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<div class={styles.wizardStepPanel} data-slot="bootstrap-wizard-step-panel">
|
||||
<div class={styles.sectionHeader}>
|
||||
<div>
|
||||
<span class={styles.wizardStepEyebrow}>{`Step ${currentStepIndex() + 1} of ${bootstrapStepDefinitions.length}`}</span>
|
||||
<h3 class={styles.sectionTitle}>{currentStep().title}</h3>
|
||||
</div>
|
||||
<div class={styles.statusBadge} data-status={currentStepState().status}>{statusLabel(currentStepState())}</div>
|
||||
</div>
|
||||
|
||||
<form class={styles.form} onSubmit={handleCurrentStepSubmit}>
|
||||
<Show when={currentStep().id === "instance"}>
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Protocol</span>
|
||||
<select value={instanceForm.protocol} onInput={(event): void => setInstanceForm("protocol", event.currentTarget.value)}>
|
||||
<option value="http">http</option>
|
||||
<option value="https">https</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Access</span>
|
||||
<select value={instanceForm.access} onInput={(event): void => setInstanceForm("access", event.currentTarget.value)}>
|
||||
<option value="local">local</option>
|
||||
<option value="remote">remote</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Host</span>
|
||||
<input
|
||||
type="text"
|
||||
value={instanceForm.host}
|
||||
onInput={(event): void => setInstanceForm("host", event.currentTarget.value)}
|
||||
placeholder="localhost or app.example.com"
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
</Show>
|
||||
|
||||
<Show when={currentStep().id === "mode"}>
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Mode</span>
|
||||
<select value={modeForm.mode} onInput={(event): void => setModeForm("mode", event.currentTarget.value)}>
|
||||
<option value="personal">personal</option>
|
||||
<option value="organizational">organizational</option>
|
||||
</select>
|
||||
</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"}>
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Display name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={adminForm.displayName}
|
||||
onInput={(event): void => setAdminForm("displayName", event.currentTarget.value)}
|
||||
placeholder="Admin"
|
||||
/>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Email</span>
|
||||
<input
|
||||
type="email"
|
||||
value={adminForm.email}
|
||||
onInput={(event): void => setAdminForm("email", event.currentTarget.value)}
|
||||
placeholder="admin@example.com"
|
||||
/>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Password</span>
|
||||
<input
|
||||
type="password"
|
||||
value={adminForm.password}
|
||||
onInput={(event): void => setAdminForm("password", event.currentTarget.value)}
|
||||
placeholder="Create a strong password"
|
||||
/>
|
||||
<small class={styles.fieldHelp}>
|
||||
Use at least 12 characters with uppercase, lowercase, numbers, and symbols.
|
||||
</small>
|
||||
</label>
|
||||
</>
|
||||
</Show>
|
||||
|
||||
<Show when={currentStep().id === "structure"}>
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Department</span>
|
||||
<input
|
||||
type="text"
|
||||
value={structureForm.departmentName}
|
||||
disabled={modeForm.mode === "personal"}
|
||||
onInput={(event): void => setStructureForm("departmentName", event.currentTarget.value)}
|
||||
placeholder={organizationalStructureDefaults.departmentName}
|
||||
/>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Team</span>
|
||||
<input
|
||||
type="text"
|
||||
value={structureForm.teamName}
|
||||
disabled={modeForm.mode === "personal"}
|
||||
onInput={(event): void => setStructureForm("teamName", event.currentTarget.value)}
|
||||
placeholder={organizationalStructureDefaults.teamName}
|
||||
/>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Project</span>
|
||||
<input
|
||||
type="text"
|
||||
value={structureForm.projectName}
|
||||
onInput={(event): void => setStructureForm("projectName", event.currentTarget.value)}
|
||||
placeholder="Moku"
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
</Show>
|
||||
|
||||
<div class={styles.wizardFormActions}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.secondaryButton}
|
||||
disabled={isFirstStep()}
|
||||
onClick={(): void => setCurrentStepIndex((index) => Math.max(index - 1, 0))}
|
||||
>
|
||||
Back
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class={styles.primaryButton}
|
||||
disabled={currentStepState().status === "submitting"}
|
||||
>
|
||||
{currentStep().buttonLabel}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
<Show when={currentStepState().error}>
|
||||
<p class={styles.errorText}>{currentStepState().error}</p>
|
||||
</Show>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Portal>
|
||||
</Show>
|
||||
</>
|
||||
);
|
||||
};
|
||||
+3
-3
@@ -1,8 +1,8 @@
|
||||
// Path: Frontend/src/components/shell/LeftRail/LeftRail.tsx
|
||||
// Path: Frontend/src/components/workspace-navigation/LeftRail/LeftRail.tsx
|
||||
|
||||
import { For, Show, type JSX } from "solid-js";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import { type RailItem } from "../data/shell.data";
|
||||
import { useAppShellData } from "../../app-shell/data/app-shell.context";
|
||||
import { type RailItem } from "../../app-shell/data/shell.data";
|
||||
import styles from "./LeftRail.module.scss";
|
||||
|
||||
type RailEntryProps = {
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/MobileWorkspaceBrowser/MobileWorkspaceBrowser.data.ts
|
||||
|
||||
import type { WorkspaceTreeNode } from "../../app-shell/data/shell.data";
|
||||
|
||||
export type MobileWorkspaceBrowserProps = {
|
||||
open: boolean;
|
||||
onClose: VoidFunction;
|
||||
};
|
||||
|
||||
export type MobileWorkspaceDialogState =
|
||||
| {
|
||||
kind: "text";
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel: string;
|
||||
initialValue: string;
|
||||
onConfirm: (value: string) => void;
|
||||
}
|
||||
| {
|
||||
kind: "confirm";
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel: string;
|
||||
tone?: "danger";
|
||||
onConfirm: () => void;
|
||||
};
|
||||
|
||||
export type MobileMoveTargetState = {
|
||||
kind: "folder" | "item";
|
||||
id: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
export type MobileMoveDestination = {
|
||||
id: string | null;
|
||||
label: string;
|
||||
depth: number;
|
||||
meta?: string;
|
||||
};
|
||||
|
||||
export const collectMoveDestinations = (
|
||||
nodes: readonly WorkspaceTreeNode[],
|
||||
movingTarget: MobileMoveTargetState,
|
||||
depth = 0,
|
||||
ancestorBlocked = false,
|
||||
): MobileMoveDestination[] => {
|
||||
const destinations: MobileMoveDestination[] = [];
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.kind !== "folder") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const isBlockedFolder = movingTarget.kind === "folder" && node.id === movingTarget.id;
|
||||
if (!ancestorBlocked && !isBlockedFolder) {
|
||||
destinations.push({
|
||||
id: node.id,
|
||||
label: node.label,
|
||||
depth,
|
||||
meta: "Folder",
|
||||
});
|
||||
}
|
||||
|
||||
destinations.push(
|
||||
...collectMoveDestinations(node.children ?? [], movingTarget, depth + 1, ancestorBlocked || isBlockedFolder),
|
||||
);
|
||||
}
|
||||
|
||||
return destinations;
|
||||
};
|
||||
|
||||
export const findTreeNodeById = (nodes: readonly WorkspaceTreeNode[], nodeId: string): WorkspaceTreeNode | null => {
|
||||
for (const node of nodes) {
|
||||
if (node.id === nodeId) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node.kind !== "folder") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const nestedMatch = findTreeNodeById(node.children ?? [], nodeId);
|
||||
if (nestedMatch) {
|
||||
return nestedMatch;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
export const isDangerDialogState = (state: MobileWorkspaceDialogState): boolean => state.kind === "confirm" && state.tone === "danger";
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/MobileWorkspaceBrowser/MobileWorkspaceBrowser.hook.ts
|
||||
|
||||
import { createSignal } from "solid-js";
|
||||
import { createLongPressGesture } from "../../../helper/createLongPressGesture";
|
||||
import { useAppShellData } from "../../app-shell/data/app-shell.context";
|
||||
import {
|
||||
createWorkspaceSurfaceTarget,
|
||||
getWorkspaceItemTypeDefinition,
|
||||
type WorkspaceContextMenuAction,
|
||||
type WorkspaceContextMenuTarget,
|
||||
type WorkspaceItemTypeId,
|
||||
} from "../../app-shell/data/shell.data";
|
||||
import { useWorkspaceTreeData } from "../shared/useWorkspaceTreeData";
|
||||
import {
|
||||
collectMoveDestinations,
|
||||
findTreeNodeById,
|
||||
type MobileMoveDestination,
|
||||
type MobileMoveTargetState,
|
||||
type MobileWorkspaceDialogState,
|
||||
} from "./MobileWorkspaceBrowser.data";
|
||||
|
||||
export const useMobileWorkspaceBrowser = () => {
|
||||
const appShellData = useAppShellData();
|
||||
const [actionSheetTarget, setActionSheetTarget] = createSignal<WorkspaceContextMenuTarget | null>(null);
|
||||
const [dialogState, setDialogState] = createSignal<MobileWorkspaceDialogState | null>(null);
|
||||
const [dialogValue, setDialogValue] = createSignal("");
|
||||
const [moveTarget, setMoveTarget] = createSignal<MobileMoveTargetState | null>(null);
|
||||
const { workspaceTreeNodes, createFolder, renameFolder, deleteFolder, moveFolder, createItem, deleteItem, moveItem } = useWorkspaceTreeData({
|
||||
activeProjectId: () => appShellData.activeProject().id,
|
||||
fallbackWorkspaceTree: () => appShellData.workspaceTree(),
|
||||
});
|
||||
const workspaceTarget = () => createWorkspaceSurfaceTarget(appShellData.activeProject());
|
||||
|
||||
const moveDestinations = (): MobileMoveDestination[] => {
|
||||
const target = moveTarget();
|
||||
if (!target) {
|
||||
return [];
|
||||
}
|
||||
|
||||
return [{ id: null, label: "Items root", depth: 0, meta: "Root" }, ...collectMoveDestinations(workspaceTreeNodes(), target)];
|
||||
};
|
||||
|
||||
const resolveCreateItemType = (actionId: string): WorkspaceItemTypeId | null => {
|
||||
switch (actionId) {
|
||||
case "create-doc":
|
||||
return "core.doc";
|
||||
case "create-board":
|
||||
return "core.board.kanban";
|
||||
case "create-list-board":
|
||||
return "core.board.list";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const createPersistedItem = (itemType: WorkspaceItemTypeId, parentId: string | null): void => {
|
||||
const definition = getWorkspaceItemTypeDefinition(itemType);
|
||||
void createItem(definition.defaultCreateLabel, itemType, parentId);
|
||||
};
|
||||
|
||||
const openActionSheet = (target: WorkspaceContextMenuTarget): void => {
|
||||
setActionSheetTarget(target);
|
||||
};
|
||||
|
||||
const closeActionSheet = (): void => {
|
||||
setActionSheetTarget(null);
|
||||
};
|
||||
|
||||
const closeMoveSheet = (): void => {
|
||||
setMoveTarget(null);
|
||||
};
|
||||
|
||||
const openWorkspaceActionSheet = (): void => {
|
||||
openActionSheet(workspaceTarget());
|
||||
};
|
||||
|
||||
const closeDialog = (): void => {
|
||||
setDialogState(null);
|
||||
setDialogValue("");
|
||||
};
|
||||
|
||||
const openMoveSheet = (target: MobileMoveTargetState): void => {
|
||||
setMoveTarget(target);
|
||||
};
|
||||
|
||||
const openTextDialog = (config: Omit<Extract<MobileWorkspaceDialogState, { kind: "text" }>, "kind">): void => {
|
||||
setDialogValue(config.initialValue);
|
||||
setDialogState({ kind: "text", ...config });
|
||||
};
|
||||
|
||||
const openConfirmDialog = (config: Omit<Extract<MobileWorkspaceDialogState, { kind: "confirm" }>, "kind">): void => {
|
||||
setDialogValue("");
|
||||
setDialogState({ kind: "confirm", ...config });
|
||||
};
|
||||
|
||||
const submitDialog = (): void => {
|
||||
const state = dialogState();
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.kind === "text") {
|
||||
const value = dialogValue().trim();
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
|
||||
closeDialog();
|
||||
state.onConfirm(value);
|
||||
return;
|
||||
}
|
||||
|
||||
closeDialog();
|
||||
state.onConfirm();
|
||||
};
|
||||
|
||||
const handleMoveDestinationSelect = (destinationId: string | null): void => {
|
||||
const target = moveTarget();
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
const destinationNode = destinationId ? findTreeNodeById(workspaceTreeNodes(), destinationId) : null;
|
||||
const targetIndex = destinationNode?.kind === "folder"
|
||||
? destinationNode.children?.length ?? 0
|
||||
: destinationId
|
||||
? 0
|
||||
: workspaceTreeNodes().length;
|
||||
|
||||
closeMoveSheet();
|
||||
|
||||
if (target.kind === "folder") {
|
||||
void moveFolder(target.id, destinationId, targetIndex);
|
||||
return;
|
||||
}
|
||||
|
||||
void moveItem(target.id, destinationId, targetIndex);
|
||||
};
|
||||
|
||||
const handleActionSelect = (action: WorkspaceContextMenuAction, target: WorkspaceContextMenuTarget): void => {
|
||||
const createItemType = resolveCreateItemType(action.id);
|
||||
if (createItemType) {
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
case "home":
|
||||
createPersistedItem(createItemType, null);
|
||||
return;
|
||||
case "folder":
|
||||
createPersistedItem(createItemType, target.id);
|
||||
return;
|
||||
case "settings":
|
||||
case "item":
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
switch (action.id) {
|
||||
case "new-folder": {
|
||||
if (target.kind === "settings" || target.kind === "item") {
|
||||
return;
|
||||
}
|
||||
|
||||
openTextDialog({
|
||||
title: "New folder",
|
||||
message: target.kind === "folder" ? `Create a folder inside "${target.label}".` : "Create a folder at the root of Items.",
|
||||
confirmLabel: "Create",
|
||||
initialValue: "Untitled folder",
|
||||
onConfirm: (name) => {
|
||||
void createFolder(name, target.kind === "folder" ? target.id : null);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "rename-folder": {
|
||||
if (target.kind !== "folder") {
|
||||
return;
|
||||
}
|
||||
|
||||
openTextDialog({
|
||||
title: "Rename folder",
|
||||
message: `Update the name for "${target.label}".`,
|
||||
confirmLabel: "Save",
|
||||
initialValue: target.label,
|
||||
onConfirm: (name) => {
|
||||
if (name === target.label) {
|
||||
return;
|
||||
}
|
||||
void renameFolder(target.id, name);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "move-folder": {
|
||||
if (target.kind !== "folder") {
|
||||
return;
|
||||
}
|
||||
|
||||
openMoveSheet({ kind: "folder", id: target.id, label: target.label });
|
||||
return;
|
||||
}
|
||||
case "delete-folder": {
|
||||
if (target.kind !== "folder") {
|
||||
return;
|
||||
}
|
||||
|
||||
openConfirmDialog({
|
||||
title: "Delete folder?",
|
||||
message: `"${target.label}" and everything inside it will be removed.`,
|
||||
confirmLabel: "Delete",
|
||||
tone: "danger",
|
||||
onConfirm: () => {
|
||||
void deleteFolder(target.id);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "move-doc":
|
||||
case "move-board":
|
||||
case "move-list-board": {
|
||||
if (target.kind !== "item") {
|
||||
return;
|
||||
}
|
||||
|
||||
openMoveSheet({ kind: "item", id: target.id, label: target.label });
|
||||
return;
|
||||
}
|
||||
case "delete-doc":
|
||||
case "delete-board":
|
||||
case "delete-list-board": {
|
||||
if (target.kind !== "item") {
|
||||
return;
|
||||
}
|
||||
|
||||
openConfirmDialog({
|
||||
title: "Delete item?",
|
||||
message: `"${target.label}" will be removed from the project tree.`,
|
||||
confirmLabel: "Delete",
|
||||
tone: "danger",
|
||||
onConfirm: () => {
|
||||
void deleteItem(target.id);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const workspaceLongPress = createLongPressGesture({
|
||||
onLongPress: openWorkspaceActionSheet,
|
||||
});
|
||||
|
||||
return {
|
||||
appShellData,
|
||||
actionSheetTarget,
|
||||
openActionSheet,
|
||||
closeActionSheet,
|
||||
dialogState,
|
||||
dialogValue,
|
||||
setDialogValue,
|
||||
closeDialog,
|
||||
submitDialog,
|
||||
moveTarget,
|
||||
moveDestinations,
|
||||
closeMoveSheet,
|
||||
handleMoveDestinationSelect,
|
||||
workspaceTreeNodes,
|
||||
handleActionSelect,
|
||||
workspaceLongPress,
|
||||
openWorkspaceActionSheet,
|
||||
};
|
||||
};
|
||||
+414
@@ -0,0 +1,414 @@
|
||||
.browserLayer {
|
||||
display: none;
|
||||
}
|
||||
|
||||
@include respond-down(mobile) {
|
||||
.browserLayer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
z-index: calc(var(--z-popover, 20) + 2);
|
||||
background: color-mix(in srgb, var(--color-canvas) 96%, black 4%);
|
||||
}
|
||||
|
||||
.sheet {
|
||||
height: 100dvh;
|
||||
display: grid;
|
||||
grid-template-rows: auto minmax(0, 1fr);
|
||||
background:
|
||||
linear-gradient(180deg, color-mix(in srgb, var(--color-surface) 84%, transparent) 0%, transparent 8rem),
|
||||
color-mix(in srgb, var(--color-canvas) 97%, black 3%);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.sheetHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: calc(var(--space-5) + env(safe-area-inset-top, 0px)) var(--space-4) var(--space-4);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--color-border) 84%, transparent);
|
||||
}
|
||||
|
||||
.headerActions {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.brandBlock {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
}
|
||||
|
||||
.sectionLabel {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.brandEyebrow {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.08em;
|
||||
}
|
||||
|
||||
.brandTitle {
|
||||
@include text-title;
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.brandContext {
|
||||
@include text-caption;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.closeButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: var(--control-size-md);
|
||||
height: var(--control-size-md);
|
||||
padding: 0;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 92%, transparent);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--color-surface) 92%, transparent);
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.createButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: var(--space-2);
|
||||
min-height: var(--control-size-md);
|
||||
padding: 0 var(--space-3);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border-strong, var(--color-border)) 82%, transparent);
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--color-surface) 94%, var(--color-canvas) 6%);
|
||||
color: var(--color-text);
|
||||
box-shadow: var(--shadow-soft);
|
||||
font: inherit;
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.sheetBody {
|
||||
min-height: 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: var(--space-5);
|
||||
padding: var(--space-5) var(--space-5) calc(var(--space-12) + var(--space-10) + env(safe-area-inset-bottom, 0px));
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
overscroll-behavior: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.sectionBlock {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.treeList,
|
||||
.treeListItem {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.treeList {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 92%, transparent);
|
||||
}
|
||||
|
||||
.treeListNested {
|
||||
display: grid;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.treeRow {
|
||||
min-width: 0;
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
min-height: calc(var(--control-size-lg) + var(--space-3));
|
||||
padding: var(--space-4) var(--space-2) var(--space-4) calc(var(--space-2) + (var(--tree-depth, 0) * var(--space-4)));
|
||||
border: 0;
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--color-border) 92%, transparent);
|
||||
border-radius: 0;
|
||||
background: transparent;
|
||||
color: var(--color-text);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.treeRowActive {
|
||||
color: var(--color-text);
|
||||
background: color-mix(in srgb, var(--color-surface) 72%, transparent);
|
||||
}
|
||||
|
||||
.treeRowBranch {
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.treeRowLead,
|
||||
.treeRowTrail {
|
||||
min-width: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.treeRowTrail {
|
||||
flex: 0 0 auto;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.treeLabel {
|
||||
@include text-label;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.treeMeta {
|
||||
@include text-caption;
|
||||
min-width: 1rem;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
.treeChevron {
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.treeListNested > .treeListItem > .treeRow {
|
||||
min-height: calc(var(--control-size-lg) + var(--space-1));
|
||||
}
|
||||
|
||||
.dialogLayer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
z-index: calc(var(--z-modal, 30) + 2);
|
||||
padding: var(--space-5);
|
||||
}
|
||||
|
||||
.dialogBackdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: 0;
|
||||
background: color-mix(in srgb, black 56%, transparent);
|
||||
}
|
||||
|
||||
.dialogCard {
|
||||
position: relative;
|
||||
width: min(100%, 28rem);
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-4);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
border-radius: var(--radius-xl);
|
||||
background: color-mix(in srgb, var(--color-surface) 94%, var(--color-canvas) 6%);
|
||||
box-shadow: var(--shadow-strong);
|
||||
}
|
||||
|
||||
.dialogCopy {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.dialogTitle {
|
||||
@include text-title;
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.dialogMessage {
|
||||
@include text-body;
|
||||
margin: 0;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.dialogInput {
|
||||
width: 100%;
|
||||
min-height: var(--control-size-lg);
|
||||
padding: 0 var(--space-3);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border-strong, var(--color-border)) 82%, transparent);
|
||||
border-radius: var(--radius-lg);
|
||||
background: color-mix(in srgb, var(--color-canvas) 92%, var(--color-surface) 8%);
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.moveSheetLayer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: block;
|
||||
z-index: calc(var(--z-modal, 30) + 2);
|
||||
}
|
||||
|
||||
.moveSheet {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
max-height: calc(100dvh - (var(--space-12) * 2));
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-3) calc(var(--space-4) + env(safe-area-inset-bottom, 0px));
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
border-radius: var(--radius-xl) var(--radius-xl) 0 0;
|
||||
background: var(--color-surface);
|
||||
box-shadow: var(--shadow-strong);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.moveSheetHandle {
|
||||
width: var(--space-10);
|
||||
height: var(--space-1);
|
||||
margin: 0 auto;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--color-text-muted) 24%, transparent);
|
||||
}
|
||||
|
||||
.moveSheetHeader {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
padding-bottom: var(--space-3);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
}
|
||||
|
||||
.moveSheetHeaderCopy {
|
||||
display: grid;
|
||||
gap: calc(var(--space-1) / 2);
|
||||
}
|
||||
|
||||
.moveSheetEyebrow {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.moveSheetTitle {
|
||||
@include text-title;
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.moveSheetMessage {
|
||||
@include text-body;
|
||||
margin: 0;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.moveSection {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.moveSectionLabel {
|
||||
@include text-caption;
|
||||
padding-inline: var(--space-1);
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.moveDestinationList {
|
||||
display: grid;
|
||||
overflow: hidden;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
border-radius: var(--radius-lg);
|
||||
background: color-mix(in srgb, var(--color-surface) 88%, var(--color-surface-elevated, var(--color-surface)) 12%);
|
||||
max-height: min(20rem, 45vh);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.moveDestinationButton {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
min-height: calc(var(--control-size-lg) + var(--space-2));
|
||||
padding: 0 var(--space-3);
|
||||
padding-left: calc(var(--space-3) + (var(--move-depth, 0) * var(--space-4)));
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--color-text);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.moveDestinationButton:active {
|
||||
background: color-mix(in srgb, var(--color-text) 6%, transparent);
|
||||
}
|
||||
|
||||
.moveDestinationButton + .moveDestinationButton {
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 92%, transparent);
|
||||
}
|
||||
|
||||
.moveDestinationLabel {
|
||||
@include text-label;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.moveDestinationMeta {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.moveSheetFooter {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding-top: var(--space-2);
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
}
|
||||
|
||||
.dialogActions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.dialogSecondaryButton,
|
||||
.dialogPrimaryButton {
|
||||
min-height: var(--control-size-md);
|
||||
padding: 0 var(--space-3);
|
||||
border-radius: 999px;
|
||||
font: inherit;
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.dialogSecondaryButton {
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
background: color-mix(in srgb, var(--color-surface) 92%, transparent);
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.dialogPrimaryButton {
|
||||
border: 1px solid color-mix(in srgb, var(--color-border-strong, var(--color-border)) 82%, transparent);
|
||||
background: color-mix(in srgb, var(--color-text) 10%, var(--color-surface) 90%);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.dialogDangerButton {
|
||||
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border-strong, var(--color-border))) 82%, transparent);
|
||||
background: color-mix(in srgb, var(--color-danger-text, #b42318) 12%, var(--color-surface) 88%);
|
||||
color: var(--color-danger-text, #b42318);
|
||||
}
|
||||
}
|
||||
+140
@@ -0,0 +1,140 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/MobileWorkspaceBrowser/MobileWorkspaceBrowser.parts.tsx
|
||||
|
||||
import { For, Show, type JSX } from "solid-js";
|
||||
import { ChevronRight } from "../../../lib/icons";
|
||||
import { createLongPressGesture } from "../../../helper/createLongPressGesture";
|
||||
import {
|
||||
createWorkspaceStaticTarget,
|
||||
createWorkspaceTreeTarget,
|
||||
getWorkspaceNodeIcon,
|
||||
type SidebarItem,
|
||||
type WorkspaceContextMenuTarget,
|
||||
type WorkspaceStaticItem,
|
||||
type WorkspaceTreeNode,
|
||||
} from "../../app-shell/data/shell.data";
|
||||
import styles from "./MobileWorkspaceBrowser.module.scss";
|
||||
|
||||
export const TreeRow = (props: { node: WorkspaceTreeNode; depth?: number }): JSX.Element => {
|
||||
const depth = props.depth ?? 0;
|
||||
const Icon = getWorkspaceNodeIcon(props.node);
|
||||
const hasChildren = (props.node.children?.length ?? 0) > 0;
|
||||
|
||||
return (
|
||||
<button
|
||||
classList={{
|
||||
[styles.treeRow]: true,
|
||||
[styles.treeRowActive]: props.node.active ?? false,
|
||||
[styles.treeRowBranch]: hasChildren,
|
||||
}}
|
||||
type="button"
|
||||
style={{ "--tree-depth": `${depth}` }}
|
||||
data-slot="mobile-workspace-tree-row"
|
||||
data-kind={props.node.kind}
|
||||
data-item-type={props.node.kind === "item" ? props.node.itemType : undefined}
|
||||
data-active={props.node.active ? "true" : "false"}
|
||||
>
|
||||
<span class={styles.treeRowLead}>
|
||||
<Icon size={16} strokeWidth={2} />
|
||||
<span class={styles.treeLabel}>{props.node.label}</span>
|
||||
</span>
|
||||
|
||||
<span class={styles.treeRowTrail}>
|
||||
<Show when={props.node.meta}>
|
||||
<span class={styles.treeMeta}>{props.node.meta}</span>
|
||||
</Show>
|
||||
<Show when={hasChildren}>
|
||||
<ChevronRight size={14} strokeWidth={2} class={styles.treeChevron} />
|
||||
</Show>
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
export const StaticRow = (props: { item: SidebarItem }): JSX.Element => {
|
||||
const Icon = props.item.icon;
|
||||
|
||||
return (
|
||||
<button classList={{ [styles.treeRow]: true, [styles.treeRowActive]: props.item.active ?? false }} type="button" style={{ "--tree-depth": "0" }} data-slot="mobile-workspace-static-row" data-active={props.item.active ? "true" : "false"}>
|
||||
<span class={styles.treeRowLead}>
|
||||
<Icon size={16} strokeWidth={2} />
|
||||
<span class={styles.treeLabel}>{props.item.label}</span>
|
||||
</span>
|
||||
<span class={styles.treeRowTrail}>
|
||||
<Show when={props.item.meta}>
|
||||
<span class={styles.treeMeta}>{props.item.meta}</span>
|
||||
</Show>
|
||||
<ChevronRight size={14} strokeWidth={2} class={styles.treeChevron} />
|
||||
</span>
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
export const WorkspaceStaticRow = (props: {
|
||||
item: WorkspaceStaticItem;
|
||||
onOpenActionSheet: (target: WorkspaceContextMenuTarget) => void;
|
||||
}): JSX.Element => {
|
||||
const target = createWorkspaceStaticTarget(props.item);
|
||||
const longPress = createLongPressGesture({
|
||||
onLongPress: () => {
|
||||
props.onOpenActionSheet(target);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<li
|
||||
class={styles.treeListItem}
|
||||
data-slot="mobile-workspace-static-item"
|
||||
data-target-kind={target.kind}
|
||||
onContextMenu={(event): void => {
|
||||
event.preventDefault();
|
||||
props.onOpenActionSheet(target);
|
||||
}}
|
||||
{...longPress}
|
||||
>
|
||||
<StaticRow item={props.item} />
|
||||
</li>
|
||||
);
|
||||
};
|
||||
|
||||
export const WorkspaceTreeBranch = (props: {
|
||||
nodes: readonly WorkspaceTreeNode[];
|
||||
depth?: number;
|
||||
onOpenActionSheet: (target: WorkspaceContextMenuTarget) => void;
|
||||
}): JSX.Element => {
|
||||
const depth = props.depth ?? 0;
|
||||
|
||||
return (
|
||||
<For each={props.nodes}>
|
||||
{(node): JSX.Element => {
|
||||
const target = createWorkspaceTreeTarget(node);
|
||||
const longPress = createLongPressGesture({
|
||||
onLongPress: () => {
|
||||
props.onOpenActionSheet(target);
|
||||
},
|
||||
});
|
||||
|
||||
return (
|
||||
<li
|
||||
class={styles.treeListItem}
|
||||
data-slot="mobile-workspace-tree-item"
|
||||
data-kind={node.kind}
|
||||
data-item-type={node.kind === "item" ? node.itemType : undefined}
|
||||
onContextMenu={(event): void => {
|
||||
event.preventDefault();
|
||||
props.onOpenActionSheet(target);
|
||||
}}
|
||||
{...longPress}
|
||||
>
|
||||
<TreeRow node={node} depth={depth} />
|
||||
|
||||
<Show when={node.children?.length}>
|
||||
<ul class={styles.treeListNested}>
|
||||
<WorkspaceTreeBranch nodes={node.children ?? []} depth={depth + 1} onOpenActionSheet={props.onOpenActionSheet} />
|
||||
</ul>
|
||||
</Show>
|
||||
</li>
|
||||
);
|
||||
}}
|
||||
</For>
|
||||
);
|
||||
};
|
||||
+192
@@ -0,0 +1,192 @@
|
||||
import { For, Show, type JSX } from "solid-js";
|
||||
import { Portal } from "solid-js/web";
|
||||
import { Plus, X } from "../../../lib/icons";
|
||||
import {
|
||||
workspaceStaticItems,
|
||||
} from "../../app-shell/data/shell.data";
|
||||
import { WorkspaceMobileActionSheet } from "../WorkspaceMobileActionSheet/WorkspaceMobileActionSheet";
|
||||
import { useMobileWorkspaceBrowser } from "./MobileWorkspaceBrowser.hook";
|
||||
import { isDangerDialogState, type MobileWorkspaceBrowserProps } from "./MobileWorkspaceBrowser.data";
|
||||
import { WorkspaceStaticRow, WorkspaceTreeBranch } from "./MobileWorkspaceBrowser.parts";
|
||||
import styles from "./MobileWorkspaceBrowser.module.scss";
|
||||
|
||||
export const MobileWorkspaceBrowser = (props: MobileWorkspaceBrowserProps): JSX.Element => {
|
||||
const {
|
||||
appShellData,
|
||||
actionSheetTarget,
|
||||
openActionSheet,
|
||||
closeActionSheet,
|
||||
dialogState,
|
||||
dialogValue,
|
||||
setDialogValue,
|
||||
closeDialog,
|
||||
submitDialog,
|
||||
moveTarget,
|
||||
moveDestinations,
|
||||
closeMoveSheet,
|
||||
handleMoveDestinationSelect,
|
||||
workspaceTreeNodes,
|
||||
handleActionSelect,
|
||||
workspaceLongPress,
|
||||
openWorkspaceActionSheet,
|
||||
} = useMobileWorkspaceBrowser();
|
||||
|
||||
return (
|
||||
<Show when={props.open}>
|
||||
<div class={styles.browserLayer} data-ui="mobile-workspace-browser">
|
||||
<section class={styles.sheet} aria-label="Mobile workspace browser" data-slot="mobile-workspace-sheet">
|
||||
<header class={styles.sheetHeader} data-slot="mobile-workspace-header">
|
||||
<div
|
||||
class={styles.brandBlock}
|
||||
data-slot="mobile-workspace-brand"
|
||||
onContextMenu={(event): void => {
|
||||
event.preventDefault();
|
||||
openWorkspaceActionSheet();
|
||||
}}
|
||||
{...workspaceLongPress}
|
||||
>
|
||||
{/* Long-pressing the browser header exposes workspace-level actions on mobile. */}
|
||||
<span class={styles.brandEyebrow}>Moku Work</span>
|
||||
<strong class={styles.brandTitle}>{appShellData.activeProject().name}</strong>
|
||||
<span class={styles.brandContext}>{appShellData.activeServer().name}</span>
|
||||
</div>
|
||||
|
||||
<div class={styles.headerActions} data-slot="mobile-workspace-header-actions">
|
||||
<button
|
||||
class={styles.createButton}
|
||||
type="button"
|
||||
aria-label="Create"
|
||||
data-slot="mobile-workspace-create"
|
||||
onClick={openWorkspaceActionSheet}
|
||||
>
|
||||
<Plus size={16} strokeWidth={2.25} />
|
||||
<span>Create</span>
|
||||
</button>
|
||||
|
||||
<button class={styles.closeButton} type="button" aria-label="Close workspace browser" data-slot="mobile-workspace-close" onClick={props.onClose}>
|
||||
<X size={18} strokeWidth={2} />
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<div class={styles.sheetBody} data-slot="mobile-workspace-body">
|
||||
<section class={styles.sectionBlock} data-slot="mobile-workspace-section" data-section-id="workspace">
|
||||
<span class={styles.sectionLabel}>Workspace</span>
|
||||
<ul class={styles.treeList} data-slot="mobile-workspace-list" data-section-id="workspace">
|
||||
<For each={workspaceStaticItems}>
|
||||
{(item): JSX.Element => <WorkspaceStaticRow item={item} onOpenActionSheet={openActionSheet} />}
|
||||
</For>
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<section class={styles.sectionBlock} data-slot="mobile-workspace-section" data-section-id="items">
|
||||
<span class={styles.sectionLabel}>Items</span>
|
||||
<ul class={styles.treeList} data-slot="mobile-workspace-list" data-section-id="items">
|
||||
<WorkspaceTreeBranch nodes={workspaceTreeNodes()} onOpenActionSheet={openActionSheet} />
|
||||
</ul>
|
||||
</section>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<WorkspaceMobileActionSheet target={actionSheetTarget()} onClose={closeActionSheet} onSelect={handleActionSelect} />
|
||||
|
||||
<Show when={moveTarget()}>
|
||||
{(state): JSX.Element => (
|
||||
<Portal>
|
||||
<div class={styles.moveSheetLayer} data-ui="mobile-workspace-move-sheet">
|
||||
<button class={styles.dialogBackdrop} type="button" aria-label="Close move sheet" onClick={closeMoveSheet} />
|
||||
<section class={styles.moveSheet} aria-label={`Move ${state().label}`}>
|
||||
<div class={styles.moveSheetHandle} aria-hidden="true" />
|
||||
<div class={styles.moveSheetHeader}>
|
||||
<div class={styles.moveSheetHeaderCopy}>
|
||||
<span class={styles.moveSheetEyebrow}>Move {state().kind}</span>
|
||||
<strong class={styles.moveSheetTitle}>{state().label}</strong>
|
||||
<p class={styles.moveSheetMessage}>Choose a new location in the project tree.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class={styles.moveSection}>
|
||||
<span class={styles.moveSectionLabel}>Destination</span>
|
||||
<div class={styles.moveDestinationList}>
|
||||
<For each={moveDestinations()}>
|
||||
{(destination): JSX.Element => (
|
||||
<button
|
||||
type="button"
|
||||
class={styles.moveDestinationButton}
|
||||
style={{ "--move-depth": `${destination.depth}` }}
|
||||
onClick={(): void => handleMoveDestinationSelect(destination.id)}
|
||||
>
|
||||
<span class={styles.moveDestinationLabel}>{destination.label}</span>
|
||||
<Show when={destination.meta}>
|
||||
<span class={styles.moveDestinationMeta}>{destination.meta}</span>
|
||||
</Show>
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class={styles.moveSheetFooter}>
|
||||
<button class={styles.dialogSecondaryButton} type="button" onClick={closeMoveSheet}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Portal>
|
||||
)}
|
||||
</Show>
|
||||
|
||||
<Show when={dialogState()}>
|
||||
{(state): JSX.Element => (
|
||||
<Portal>
|
||||
<div class={styles.dialogLayer} data-ui="mobile-workspace-dialog">
|
||||
<button class={styles.dialogBackdrop} type="button" aria-label="Close dialog" onClick={closeDialog} />
|
||||
<section class={styles.dialogCard} aria-label={state().title}>
|
||||
<div class={styles.dialogCopy}>
|
||||
<strong class={styles.dialogTitle}>{state().title}</strong>
|
||||
<p class={styles.dialogMessage}>{state().message}</p>
|
||||
</div>
|
||||
|
||||
<Show when={state().kind === "text"}>
|
||||
<input
|
||||
class={styles.dialogInput}
|
||||
type="text"
|
||||
value={dialogValue()}
|
||||
onInput={(event): void => {
|
||||
setDialogValue(event.currentTarget.value);
|
||||
}}
|
||||
onKeyDown={(event): void => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
submitDialog();
|
||||
}
|
||||
}}
|
||||
autofocus
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<div class={styles.dialogActions}>
|
||||
<button class={styles.dialogSecondaryButton} type="button" onClick={closeDialog}>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
classList={{
|
||||
[styles.dialogPrimaryButton]: true,
|
||||
[styles.dialogDangerButton]: isDangerDialogState(state()),
|
||||
}}
|
||||
type="button"
|
||||
onClick={submitDialog}
|
||||
>
|
||||
{state().confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Portal>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
);
|
||||
};
|
||||
+1
-1
@@ -7,7 +7,7 @@ import {
|
||||
type ProjectContextMenuAction,
|
||||
type ProjectMenuTarget,
|
||||
type WorkspaceContextMenuShortcut,
|
||||
} from "../data/shell.data";
|
||||
} from "../../app-shell/data/shell.data";
|
||||
import styles from "../WorkspaceContextMenu/WorkspaceContextMenu.module.scss";
|
||||
|
||||
type ShortcutPlatform = "mac" | "windows";
|
||||
+11
-1
@@ -1,5 +1,5 @@
|
||||
import { createEffect, createSignal, onCleanup } from "solid-js";
|
||||
import type { ProjectMenuTarget } from "../data/shell.data";
|
||||
import type { ProjectMenuTarget } from "../../app-shell/data/shell.data";
|
||||
|
||||
type ProjectContextMenuState = {
|
||||
target: ProjectMenuTarget;
|
||||
@@ -70,6 +70,15 @@ export const createProjectContextMenuController = () => {
|
||||
setMenuState({ target, x: event.clientX, y: event.clientY });
|
||||
};
|
||||
|
||||
const openMenuFromElement = (element: HTMLElement, target: ProjectMenuTarget): void => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
setMenuState({
|
||||
target,
|
||||
x: rect.left + rect.width / 2,
|
||||
y: rect.top + rect.height / 2,
|
||||
});
|
||||
};
|
||||
|
||||
createEffect(() => {
|
||||
if (!menuState() || typeof window === "undefined") {
|
||||
return;
|
||||
@@ -112,6 +121,7 @@ export const createProjectContextMenuController = () => {
|
||||
return {
|
||||
menuState,
|
||||
openMenu,
|
||||
openMenuFromElement,
|
||||
closeMenu,
|
||||
setMenuRef: (element: HTMLDivElement): void => {
|
||||
menuRef = element;
|
||||
@@ -0,0 +1,144 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/ProjectSelector/ProjectSelector.data.ts
|
||||
|
||||
import type { JSX } from "solid-js";
|
||||
import type {
|
||||
NavTreeAdapter,
|
||||
NavTreeDropTarget,
|
||||
} from "../shared/navTreeDnd";
|
||||
import type { ProjectItem } from "../../app-shell/data/shell.data";
|
||||
|
||||
export type ProjectSelectorProps = {
|
||||
compact?: boolean;
|
||||
isOpen: boolean;
|
||||
onToggle: () => void;
|
||||
onClose: () => void;
|
||||
};
|
||||
|
||||
export type ProjectFolderNode = {
|
||||
kind: "folder";
|
||||
id: string;
|
||||
path: string;
|
||||
label: string;
|
||||
meta?: string;
|
||||
children: ProjectTreeNode[];
|
||||
};
|
||||
|
||||
export type ProjectLeafNode = {
|
||||
kind: "project";
|
||||
item: ProjectItem;
|
||||
};
|
||||
|
||||
export type ProjectTreeNode = ProjectFolderNode | ProjectLeafNode;
|
||||
|
||||
export type PersistedProjectFolderRecord = {
|
||||
id: string;
|
||||
path: string;
|
||||
label: string;
|
||||
children: PersistedProjectFolderRecord[];
|
||||
};
|
||||
|
||||
export type ProjectFoldersResponse = {
|
||||
data?: {
|
||||
folders?: PersistedProjectFolderRecord[];
|
||||
renamedFolder?: PersistedProjectFolderRecord;
|
||||
movedFolder?: PersistedProjectFolderRecord;
|
||||
previousFolderId?: string;
|
||||
previousFolderPath?: string;
|
||||
};
|
||||
error?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
export type PendingProjectFolderDraft = {
|
||||
parentId: string | null;
|
||||
depth: number;
|
||||
};
|
||||
|
||||
export type PendingProjectFolderRename = {
|
||||
folderId: string;
|
||||
depth: number;
|
||||
};
|
||||
|
||||
export type ProjectDragTarget = NavTreeDropTarget;
|
||||
|
||||
export type ProjectDragState = {
|
||||
draggedNodeId: string;
|
||||
dropTarget: ProjectDragTarget | null;
|
||||
};
|
||||
|
||||
export type DragGhostPosition = {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
|
||||
export type ProjectFolderBranchProps = {
|
||||
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;
|
||||
pendingFolderRename: PendingProjectFolderRename | null;
|
||||
pendingFolderRenameName: string;
|
||||
onPendingFolderRenameChange: (value: string) => void;
|
||||
onSubmitPendingFolderRename: () => void;
|
||||
onCancelPendingFolderRename: () => void;
|
||||
dragState: ProjectDragState | null;
|
||||
isTreeClickSuppressed: () => boolean;
|
||||
};
|
||||
|
||||
export const LONG_PRESS_MS = 320;
|
||||
|
||||
export const getProjectTreeNodeId = (node: ProjectTreeNode): string =>
|
||||
node.kind === "folder" ? node.id : node.item.id;
|
||||
|
||||
export const buildPersistedFolderNodes = (folders: readonly PersistedProjectFolderRecord[] = []): ProjectTreeNode[] =>
|
||||
folders.map((folder) => ({
|
||||
kind: "folder",
|
||||
id: folder.id,
|
||||
path: folder.path,
|
||||
label: folder.label,
|
||||
children: buildPersistedFolderNodes(folder.children ?? []),
|
||||
}));
|
||||
|
||||
export const buildProjectTree = (
|
||||
items: readonly ProjectItem[],
|
||||
folders: readonly PersistedProjectFolderRecord[] = [],
|
||||
): ProjectTreeNode[] => [
|
||||
...items.map((item) => ({
|
||||
kind: "project" as const,
|
||||
item,
|
||||
})),
|
||||
...buildPersistedFolderNodes(folders),
|
||||
];
|
||||
|
||||
export const countProjectFolderSiblingsBeforeIndex = (
|
||||
siblings: readonly ProjectTreeNode[],
|
||||
index: number,
|
||||
): number => siblings.slice(0, index).filter((node) => node.kind === "folder").length;
|
||||
|
||||
export const readPersistedFolders = (body: ProjectFoldersResponse): PersistedProjectFolderRecord[] =>
|
||||
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
||||
|
||||
export 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,
|
||||
};
|
||||
@@ -0,0 +1,671 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/ProjectSelector/ProjectSelector.hook.ts
|
||||
|
||||
import { createEffect, createSignal, onCleanup, onMount } from "solid-js";
|
||||
import { useAppShellData } from "../../app-shell/data/app-shell.context";
|
||||
import {
|
||||
createProjectFolderTarget,
|
||||
createProjectSurfaceTarget,
|
||||
createProjectTarget,
|
||||
type ProjectItem,
|
||||
type ProjectMenuTarget,
|
||||
} from "../../app-shell/data/shell.data";
|
||||
import {
|
||||
collectBranchNodeIds,
|
||||
findTreeNodeDepth,
|
||||
findTreeNodeLocation,
|
||||
getPointerRelativeY,
|
||||
isUuidString,
|
||||
moveTreeNode,
|
||||
resolveTreeDropTarget,
|
||||
} from "../shared/navTreeDnd";
|
||||
import { createProjectContextMenuController } from "../ProjectContextMenu/createProjectContextMenuController";
|
||||
import {
|
||||
LONG_PRESS_MS,
|
||||
buildProjectTree,
|
||||
countProjectFolderSiblingsBeforeIndex,
|
||||
projectTreeAdapter,
|
||||
readPersistedFolders,
|
||||
type DragGhostPosition,
|
||||
type PendingProjectFolderDraft,
|
||||
type PendingProjectFolderRename,
|
||||
type PersistedProjectFolderRecord,
|
||||
type ProjectDragState,
|
||||
type ProjectFolderNode,
|
||||
type ProjectSelectorProps,
|
||||
type ProjectTreeNode,
|
||||
} from "./ProjectSelector.data";
|
||||
import {
|
||||
createProjectFolderRequest,
|
||||
deleteProjectFolderRequest,
|
||||
fetchProjectFolders,
|
||||
isValidProjectFolderProjectId,
|
||||
moveProjectFolderRequest,
|
||||
renameProjectFolderRequest,
|
||||
} from "./projectFolders.api";
|
||||
|
||||
export const useProjectSelector = (props: ProjectSelectorProps) => {
|
||||
const appShellData = useAppShellData();
|
||||
const [selectedProject, setSelectedProject] = createSignal(appShellData.activeProject());
|
||||
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 [pendingFolderRename, setPendingFolderRename] = createSignal<PendingProjectFolderRename | null>(null);
|
||||
const [pendingFolderRenameName, setPendingFolderRenameName] = createSignal("");
|
||||
const [dragState, setDragState] = createSignal<ProjectDragState | null>(null);
|
||||
const [dragGhostPosition, setDragGhostPosition] = createSignal<DragGhostPosition>({ x: 0, y: 0 });
|
||||
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
||||
let rootRef: HTMLDivElement | 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 setRootRef = (element: HTMLDivElement | undefined): void => {
|
||||
rootRef = element;
|
||||
};
|
||||
|
||||
const setTriggerRef = (element: HTMLButtonElement | undefined): void => {
|
||||
triggerRef = element;
|
||||
};
|
||||
|
||||
const setContextMenuElement = (element: HTMLDivElement | undefined): void => {
|
||||
contextMenuRef = element;
|
||||
if (element) {
|
||||
contextMenu.setMenuRef(element);
|
||||
}
|
||||
};
|
||||
|
||||
const clearLongPressTimer = (): void => {
|
||||
if (longPressTimer !== undefined) {
|
||||
window.clearTimeout(longPressTimer);
|
||||
longPressTimer = undefined;
|
||||
}
|
||||
};
|
||||
|
||||
const updateDragGhostPosition = (x: number, y: number): void => {
|
||||
setDragGhostPosition({ x: x + 18, y: y + 18 });
|
||||
};
|
||||
|
||||
const draggedNode = (): ProjectTreeNode | null => {
|
||||
const currentDragState = dragState();
|
||||
if (!currentDragState) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return findTreeNodeLocation(projectTreeNodes(), currentDragState.draggedNodeId, projectTreeAdapter)?.node ?? null;
|
||||
};
|
||||
|
||||
const draggedNodeMeta = (): string => {
|
||||
const node = draggedNode();
|
||||
if (!node) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return node.kind === "folder" ? "Folder" : "Project";
|
||||
};
|
||||
|
||||
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("");
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
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 (!isValidProjectFolderProjectId(projectId) || !isUuidString(projectId)) {
|
||||
setPersistedFolders([]);
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await fetchProjectFolders(projectId);
|
||||
|
||||
if (requestId !== latestPersistedFoldersRequest) {
|
||||
return;
|
||||
}
|
||||
|
||||
setPersistedFolders(readPersistedFolders(body));
|
||||
} catch (error) {
|
||||
if (requestId !== latestPersistedFoldersRequest) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.error(error);
|
||||
setPersistedFolders([]);
|
||||
}
|
||||
};
|
||||
|
||||
createEffect(() => {
|
||||
setSelectedProject(appShellData.activeProject());
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
syncProjectTree();
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
const projectId = selectedProject().id;
|
||||
|
||||
if (lastSelectedProjectId === null) {
|
||||
lastSelectedProjectId = projectId;
|
||||
return;
|
||||
}
|
||||
|
||||
if (projectId === lastSelectedProjectId) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastSelectedProjectId = projectId;
|
||||
resetProjectTreeInteractionState();
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
void loadPersistedFolders(selectedProject().id);
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const target = event.target;
|
||||
|
||||
if (target instanceof Node && rootRef.contains(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (target instanceof Node && contextMenuRef?.contains(target)) {
|
||||
return;
|
||||
}
|
||||
|
||||
props.onClose();
|
||||
};
|
||||
|
||||
const handlePointerUp = (): void => {
|
||||
clearLongPressTimer();
|
||||
|
||||
const nextDragState = dragState();
|
||||
|
||||
if (!nextDragState?.dropTarget) {
|
||||
if (nextDragState) {
|
||||
suppressTreeClickTemporarily();
|
||||
}
|
||||
setDragState(null);
|
||||
return;
|
||||
}
|
||||
|
||||
suppressTreeClickTemporarily();
|
||||
|
||||
const currentNodes = projectTreeNodes();
|
||||
const draggedLocation = findTreeNodeLocation(currentNodes, nextDragState.draggedNodeId, projectTreeAdapter);
|
||||
const canPersistMove = isUuidString(selectedProject().id);
|
||||
const draggedFolderPath = draggedLocation?.node.kind === "folder" ? draggedLocation.node.path : null;
|
||||
const previewNodes = moveTreeNode(currentNodes, nextDragState.draggedNodeId, nextDragState.dropTarget, projectTreeAdapter);
|
||||
const previewLocation = findTreeNodeLocation(previewNodes, nextDragState.draggedNodeId, projectTreeAdapter);
|
||||
const persistedParentLocation = previewLocation?.parentId ? findTreeNodeLocation(previewNodes, previewLocation.parentId, projectTreeAdapter) : null;
|
||||
const persistedParentFolderPath = persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.path : null;
|
||||
const previewSiblings = previewLocation?.parentId ? persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.children : [] : previewNodes;
|
||||
const targetIndex = previewLocation ? countProjectFolderSiblingsBeforeIndex(previewSiblings, previewLocation.index) : 0;
|
||||
|
||||
if (canPersistMove && draggedLocation?.node.kind === "folder" && draggedFolderPath && (!previewLocation?.parentId || persistedParentLocation?.node.kind === "folder")) {
|
||||
void movePersistedFolder(
|
||||
draggedFolderPath,
|
||||
persistedParentFolderPath,
|
||||
draggedLocation.node.id,
|
||||
persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.id : null,
|
||||
targetIndex,
|
||||
);
|
||||
} else {
|
||||
setProjectTreeNodes((current) => moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget!, 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();
|
||||
};
|
||||
|
||||
const handlePointerMove = (event: PointerEvent): void => {
|
||||
if (!dragState()) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateDragGhostPosition(event.clientX, event.clientY);
|
||||
};
|
||||
|
||||
document.addEventListener("pointerdown", handlePointerDown);
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
window.addEventListener("pointercancel", handlePointerUp);
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("keydown", handleEscape);
|
||||
|
||||
onCleanup(() => {
|
||||
clearLongPressTimer();
|
||||
if (suppressClickTimer !== undefined) {
|
||||
window.clearTimeout(suppressClickTimer);
|
||||
}
|
||||
document.removeEventListener("pointerdown", handlePointerDown);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("keydown", handleEscape);
|
||||
});
|
||||
});
|
||||
|
||||
const toggleOpen = (): void => {
|
||||
if (!props.isOpen) {
|
||||
props.onToggle();
|
||||
return;
|
||||
}
|
||||
|
||||
props.onClose();
|
||||
};
|
||||
|
||||
const selectProject = (projectId: string): void => {
|
||||
const location = findTreeNodeLocation(projectTreeNodes(), projectId, projectTreeAdapter);
|
||||
|
||||
if (!location || location.node.kind !== "project") {
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedProject({ id: location.node.item.id, name: location.node.item.name });
|
||||
props.onClose();
|
||||
};
|
||||
|
||||
const beginFolderDraft = (parentId: string | null, depth: number): void => {
|
||||
if (parentId) {
|
||||
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
|
||||
}
|
||||
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
setPendingFolderName("");
|
||||
setPendingFolderDraft({ parentId, depth });
|
||||
};
|
||||
|
||||
const beginFolderRename = (folderId: string, label: string, depth: number): void => {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
setPendingFolderRename({ folderId, depth });
|
||||
setPendingFolderRenameName(label);
|
||||
};
|
||||
|
||||
const resolveFolderPath = (folderId: string): string | null => {
|
||||
const location = findTreeNodeLocation(projectTreeNodes(), folderId, projectTreeAdapter);
|
||||
return location && location.node.kind === "folder" ? location.node.path : null;
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const parentFolderPath = draft.parentId ? resolveFolderPath(draft.parentId) : null;
|
||||
if (draft.parentId && !parentFolderPath) {
|
||||
cancelPendingFolder();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await createProjectFolderRequest(projectId, name, parentFolderPath);
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const folderPath = resolveFolderPath(folderId);
|
||||
if (!folderPath) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await deleteProjectFolderRequest(projectId, folderPath);
|
||||
|
||||
setPersistedFolders(readPersistedFolders(body));
|
||||
setCollapsedFolderIds((current) => current.filter((id) => id !== folderId));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const movePersistedFolder = async (
|
||||
folderPath: string,
|
||||
parentFolderPath: string | null,
|
||||
folderStableId: string,
|
||||
parentStableId: string | null,
|
||||
targetIndex: number,
|
||||
): Promise<void> => {
|
||||
const projectId = selectedProject().id;
|
||||
if (!folderPath || !folderStableId || !isUuidString(projectId)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await moveProjectFolderRequest(projectId, {
|
||||
folderId: folderPath,
|
||||
folderNodeId: folderStableId,
|
||||
parentFolderId: parentFolderPath,
|
||||
parentNodeId: parentStableId,
|
||||
targetIndex,
|
||||
});
|
||||
|
||||
setPersistedFolders(readPersistedFolders(body));
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const submitPendingFolderRename = async (): Promise<void> => {
|
||||
const draft = pendingFolderRename();
|
||||
const name = pendingFolderRenameName().trim();
|
||||
const projectId = selectedProject().id;
|
||||
|
||||
if (!draft) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!name) {
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!isUuidString(projectId)) {
|
||||
cancelPendingFolderRename();
|
||||
return;
|
||||
}
|
||||
|
||||
const folderPath = resolveFolderPath(draft.folderId);
|
||||
if (!folderPath) {
|
||||
cancelPendingFolderRename();
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const body = await renameProjectFolderRequest(projectId, folderPath, name);
|
||||
|
||||
setPersistedFolders(readPersistedFolders(body));
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
const cancelPendingFolder = (): void => {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
};
|
||||
|
||||
const cancelPendingFolderRename = (): void => {
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
};
|
||||
|
||||
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;
|
||||
case "rename-folder":
|
||||
if (target.kind === "folder") {
|
||||
beginFolderRename(target.id, target.label, findTreeNodeDepth(projectTreeNodes(), target.id, projectTreeAdapter) ?? 0);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const handleSurfaceContextMenu = (event: MouseEvent): void => {
|
||||
event.stopPropagation();
|
||||
contextMenu.openMenu(event, createProjectSurfaceTarget("Projects"));
|
||||
};
|
||||
|
||||
const openRootCreateMenu = (element: HTMLElement): void => {
|
||||
contextMenu.openMenuFromElement(element, 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;
|
||||
}
|
||||
|
||||
updateDragGhostPosition(event.clientX, event.clientY);
|
||||
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 || nextDragState.draggedNodeId === (node.kind === "folder" ? node.id : node.item.id)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const relativeY = getPointerRelativeY(event);
|
||||
if (relativeY === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
setDragState({
|
||||
...nextDragState,
|
||||
dropTarget: resolveTreeDropTarget({
|
||||
parentId,
|
||||
index,
|
||||
node,
|
||||
relativeY,
|
||||
adapter: projectTreeAdapter,
|
||||
}),
|
||||
});
|
||||
};
|
||||
|
||||
const openFolderMenu = (event: MouseEvent, folder: ProjectFolderNode): void => {
|
||||
event.stopPropagation();
|
||||
contextMenu.openMenu(event, createProjectFolderTarget(folder.id, folder.label));
|
||||
};
|
||||
|
||||
const openProjectMenu = (event: MouseEvent, item: ProjectItem): void => {
|
||||
event.stopPropagation();
|
||||
contextMenu.openMenu(event, createProjectTarget(item));
|
||||
};
|
||||
|
||||
const contextMenuPosition = () => {
|
||||
const state = contextMenu.menuState();
|
||||
return state ? { x: state.x, y: state.y } : null;
|
||||
};
|
||||
|
||||
return {
|
||||
selectedProject,
|
||||
drawerTop,
|
||||
setRootRef,
|
||||
setTriggerRef,
|
||||
setContextMenuElement,
|
||||
toggleOpen,
|
||||
handleSurfaceContextMenu,
|
||||
openRootCreateMenu,
|
||||
treeControlLabel,
|
||||
toggleAllFolders,
|
||||
totalFolderCount,
|
||||
areAllFoldersCollapsed,
|
||||
projectTreeNodes,
|
||||
isFolderCollapsed,
|
||||
toggleFolder,
|
||||
selectProject,
|
||||
openFolderMenu,
|
||||
openProjectMenu,
|
||||
handleNodePointerDown,
|
||||
handleNodePointerMove,
|
||||
pendingFolderDraft,
|
||||
pendingFolderName,
|
||||
setPendingFolderName,
|
||||
submitPendingFolder,
|
||||
cancelPendingFolder,
|
||||
pendingFolderRename,
|
||||
pendingFolderRenameName,
|
||||
setPendingFolderRenameName,
|
||||
submitPendingFolderRename,
|
||||
cancelPendingFolderRename,
|
||||
dragState,
|
||||
suppressNextTreeClick,
|
||||
contextMenu,
|
||||
contextMenuPosition,
|
||||
handleContextActionSelect,
|
||||
draggedNode,
|
||||
dragGhostPosition,
|
||||
draggedNodeMeta,
|
||||
};
|
||||
};
|
||||
+91
-85
@@ -1,3 +1,5 @@
|
||||
@use "../shared/tree-nav" as treeNav;
|
||||
|
||||
.root {
|
||||
display: grid;
|
||||
--project-drawer-gap: var(--space-3);
|
||||
@@ -191,142 +193,146 @@
|
||||
}
|
||||
|
||||
.treeSectionLabel {
|
||||
@include text-caption;
|
||||
margin: 0 0 var(--space-2);
|
||||
@include treeNav.section-label;
|
||||
margin: 0;
|
||||
padding: 0 var(--space-3);
|
||||
color: var(--color-text-subtle);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.treeList {
|
||||
list-style: none;
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.treeEmptySlot {
|
||||
min-height: calc(var(--control-size-lg) - var(--space-2));
|
||||
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||
border-radius: var(--radius-lg);
|
||||
border: 1px dashed color-mix(in srgb, var(--color-border) 38%, transparent);
|
||||
opacity: 0.35;
|
||||
}
|
||||
|
||||
.treeInputRow {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
.treeSectionHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
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);
|
||||
margin-bottom: var(--space-2);
|
||||
padding-right: var(--space-1);
|
||||
}
|
||||
|
||||
.treeInput {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
.treeControls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
flex-wrap: wrap;
|
||||
justify-content: flex-end;
|
||||
}
|
||||
|
||||
.treeControlButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
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);
|
||||
}
|
||||
|
||||
.treeControlButton:hover,
|
||||
.treeControlButton:focus-visible {
|
||||
border-color: color-mix(in srgb, var(--color-border-strong) 56%, transparent);
|
||||
background: var(--color-surface-hover);
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.treeInput::placeholder {
|
||||
color: var(--color-text-muted);
|
||||
.treeControlButton:disabled {
|
||||
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 {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
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: 1px solid transparent;
|
||||
border-radius: var(--radius-lg);
|
||||
background: transparent;
|
||||
color: var(--color-text-muted);
|
||||
transition:
|
||||
background 160ms var(--easing-standard),
|
||||
color 160ms var(--easing-standard),
|
||||
border-color 160ms var(--easing-standard),
|
||||
box-shadow 160ms var(--easing-standard),
|
||||
transform 180ms var(--easing-standard);
|
||||
text-align: left;
|
||||
@include treeNav.item;
|
||||
}
|
||||
|
||||
.treeItem:hover,
|
||||
.treeItem:focus-visible {
|
||||
background: color-mix(in srgb, var(--color-surface-hover) 80%, var(--color-accent-soft) 20%);
|
||||
color: var(--color-text);
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||
@include treeNav.item-hover;
|
||||
}
|
||||
|
||||
.treeItemFolder {
|
||||
color: var(--color-text);
|
||||
@include treeNav.item-folder;
|
||||
}
|
||||
|
||||
.treeItemDragging {
|
||||
opacity: 0.45;
|
||||
transform: scale(0.985);
|
||||
box-shadow: none;
|
||||
@include treeNav.item-dragging;
|
||||
}
|
||||
|
||||
.treeItemDropBefore {
|
||||
box-shadow: inset 0 2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||
@include treeNav.item-drop-before;
|
||||
}
|
||||
|
||||
.treeItemDropAfter {
|
||||
box-shadow: inset 0 -2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||
@include treeNav.item-drop-after;
|
||||
}
|
||||
|
||||
.treeItemDropInside {
|
||||
border-color: color-mix(in srgb, var(--color-accent-strong) 55%, transparent);
|
||||
background: color-mix(in srgb, var(--color-accent-soft) 36%, var(--color-surface));
|
||||
color: var(--color-text);
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||
@include treeNav.item-drop-inside;
|
||||
}
|
||||
|
||||
.folderChevron {
|
||||
color: var(--color-text-muted);
|
||||
transition: transform 160ms var(--easing-standard);
|
||||
@include treeNav.folder-chevron;
|
||||
}
|
||||
|
||||
.folderChevronOpen {
|
||||
transform: rotate(90deg);
|
||||
@include treeNav.folder-chevron-open;
|
||||
}
|
||||
|
||||
.treeItemActive {
|
||||
border-color: var(--color-border);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||
@include treeNav.item-active;
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: inherit;
|
||||
opacity: 0.85;
|
||||
@include treeNav.icon;
|
||||
}
|
||||
|
||||
.label {
|
||||
@include text-label;
|
||||
min-width: 0;
|
||||
@include treeNav.label;
|
||||
}
|
||||
|
||||
.itemMeta {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
@include treeNav.item-meta;
|
||||
}
|
||||
|
||||
.dragGhostLayer {
|
||||
@include treeNav.drag-ghost-layer;
|
||||
}
|
||||
|
||||
.dragGhost {
|
||||
@include treeNav.drag-ghost;
|
||||
}
|
||||
|
||||
.dragGhostCopy {
|
||||
@include treeNav.drag-ghost-copy;
|
||||
}
|
||||
|
||||
.dragGhostTitle {
|
||||
@include treeNav.drag-ghost-title;
|
||||
}
|
||||
|
||||
.dragGhostMeta {
|
||||
@include treeNav.drag-ghost-meta;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
+213
@@ -0,0 +1,213 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/ProjectSelector/ProjectSelector.parts.tsx
|
||||
|
||||
import { For, Show, type JSX } from "solid-js";
|
||||
import { ChevronRight, Folder, LayoutGrid } from "../../../lib/icons";
|
||||
import type { ProjectItem } from "../../app-shell/data/shell.data";
|
||||
import {
|
||||
getProjectTreeNodeId,
|
||||
type PendingProjectFolderDraft,
|
||||
type PendingProjectFolderRename,
|
||||
type ProjectDragState,
|
||||
type ProjectFolderBranchProps,
|
||||
type ProjectFolderNode,
|
||||
type ProjectTreeNode,
|
||||
} from "./ProjectSelector.data";
|
||||
import styles from "./ProjectSelector.module.scss";
|
||||
|
||||
export 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>
|
||||
);
|
||||
};
|
||||
|
||||
export const ProjectFolderBranch = (props: ProjectFolderBranchProps): 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 = (): "before" | "after" | "inside" | 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);
|
||||
const isRenaming = (): boolean => props.pendingFolderRename?.folderId === node.id;
|
||||
|
||||
return (
|
||||
<li>
|
||||
<Show
|
||||
when={isRenaming()}
|
||||
fallback={
|
||||
<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>
|
||||
}
|
||||
>
|
||||
<ProjectFolderDraftRow
|
||||
depth={props.pendingFolderRename?.depth ?? props.depth}
|
||||
value={props.pendingFolderRenameName}
|
||||
onInput={props.onPendingFolderRenameChange}
|
||||
onSubmit={props.onSubmitPendingFolderRename}
|
||||
onCancel={props.onCancelPendingFolderRename}
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<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}
|
||||
pendingFolderRename={props.pendingFolderRename}
|
||||
pendingFolderRenameName={props.pendingFolderRenameName}
|
||||
onPendingFolderRenameChange={props.onPendingFolderRenameChange}
|
||||
onSubmitPendingFolderRename={props.onSubmitPendingFolderRename}
|
||||
onCancelPendingFolderRename={props.onCancelPendingFolderRename}
|
||||
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>
|
||||
);
|
||||
@@ -0,0 +1,222 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/ProjectSelector/ProjectSelector.tsx
|
||||
|
||||
import { Show, type JSX } from "solid-js";
|
||||
import { Portal } from "solid-js/web";
|
||||
import { ChevronDown, ChevronRight, Folder, LayoutGrid, ListCollapse, Plus, UnfoldVertical } from "../../../lib/icons";
|
||||
import { ProjectContextMenu } from "../ProjectContextMenu/ProjectContextMenu";
|
||||
import { useProjectSelector } from "./ProjectSelector.hook";
|
||||
import { ProjectFolderBranch } from "./ProjectSelector.parts";
|
||||
import { type ProjectSelectorProps } from "./ProjectSelector.data";
|
||||
import styles from "./ProjectSelector.module.scss";
|
||||
|
||||
export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
const {
|
||||
selectedProject,
|
||||
drawerTop,
|
||||
setRootRef,
|
||||
setTriggerRef,
|
||||
setContextMenuElement,
|
||||
toggleOpen,
|
||||
handleSurfaceContextMenu,
|
||||
openRootCreateMenu,
|
||||
treeControlLabel,
|
||||
toggleAllFolders,
|
||||
totalFolderCount,
|
||||
areAllFoldersCollapsed,
|
||||
projectTreeNodes,
|
||||
isFolderCollapsed,
|
||||
toggleFolder,
|
||||
selectProject,
|
||||
openFolderMenu,
|
||||
openProjectMenu,
|
||||
handleNodePointerDown,
|
||||
handleNodePointerMove,
|
||||
pendingFolderDraft,
|
||||
pendingFolderName,
|
||||
setPendingFolderName,
|
||||
submitPendingFolder,
|
||||
cancelPendingFolder,
|
||||
pendingFolderRename,
|
||||
pendingFolderRenameName,
|
||||
setPendingFolderRenameName,
|
||||
submitPendingFolderRename,
|
||||
cancelPendingFolderRename,
|
||||
dragState,
|
||||
suppressNextTreeClick,
|
||||
contextMenu,
|
||||
contextMenuPosition,
|
||||
handleContextActionSelect,
|
||||
draggedNode,
|
||||
dragGhostPosition,
|
||||
draggedNodeMeta,
|
||||
} = useProjectSelector(props);
|
||||
|
||||
return (
|
||||
<div
|
||||
ref={setRootRef}
|
||||
classList={{
|
||||
[styles.root]: true,
|
||||
[styles.rootCompact]: !!props.compact,
|
||||
[styles.rootDragMode]: !!dragState(),
|
||||
}}
|
||||
style={{
|
||||
"--project-drawer-top": `${drawerTop()}px`,
|
||||
}}
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
ref={setTriggerRef}
|
||||
classList={{
|
||||
[styles.trigger]: true,
|
||||
[styles.triggerCompact]: !!props.compact,
|
||||
[styles.triggerOpen]: props.isOpen,
|
||||
}}
|
||||
aria-label={`Open project menu for ${selectedProject().name}`}
|
||||
aria-expanded={props.isOpen}
|
||||
aria-haspopup="menu"
|
||||
title={selectedProject().name}
|
||||
onClick={toggleOpen}
|
||||
>
|
||||
<span class={styles.triggerLead} aria-hidden="true">
|
||||
<Folder size={18} strokeWidth={2} />
|
||||
</span>
|
||||
{!props.compact ? (
|
||||
<span class={styles.triggerCopy}>
|
||||
<span class={styles.eyebrow}>Projects</span>
|
||||
<span class={styles.value}>{selectedProject().name}</span>
|
||||
</span>
|
||||
) : null}
|
||||
<ChevronDown
|
||||
classList={{
|
||||
[styles.triggerIcon]: true,
|
||||
[styles.triggerIconOpen]: props.isOpen,
|
||||
}}
|
||||
size={16}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</button>
|
||||
|
||||
<Show when={props.isOpen}>
|
||||
<>
|
||||
<button
|
||||
type="button"
|
||||
classList={{
|
||||
[styles.scrim]: true,
|
||||
[styles.scrimOpen]: props.isOpen,
|
||||
}}
|
||||
aria-hidden={!props.isOpen}
|
||||
tabIndex={props.isOpen ? 0 : -1}
|
||||
onClick={props.onClose}
|
||||
/>
|
||||
|
||||
<div
|
||||
classList={{
|
||||
[styles.drawer]: true,
|
||||
[styles.drawerOpen]: props.isOpen,
|
||||
}}
|
||||
aria-hidden={!props.isOpen}
|
||||
onContextMenu={handleSurfaceContextMenu}
|
||||
>
|
||||
<div class={styles.drawerBody}>
|
||||
<div class={styles.treeSectionHeader}>
|
||||
<Show when={!props.compact}>
|
||||
<div class={styles.treeSectionLabel}>Projects</div>
|
||||
</Show>
|
||||
|
||||
<div class={styles.treeControls}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.treeControlButton}
|
||||
onClick={(event): void => {
|
||||
event.stopPropagation();
|
||||
openRootCreateMenu(event.currentTarget);
|
||||
}}
|
||||
aria-label="Create in Projects"
|
||||
title="Create"
|
||||
>
|
||||
<Plus size={16} strokeWidth={2.25} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.treeControlButton}
|
||||
onClick={toggleAllFolders}
|
||||
aria-label={treeControlLabel()}
|
||||
title={treeControlLabel()}
|
||||
disabled={totalFolderCount() === 0}
|
||||
>
|
||||
<Show
|
||||
when={areAllFoldersCollapsed()}
|
||||
fallback={<ListCollapse size={16} strokeWidth={2} />}
|
||||
>
|
||||
<UnfoldVertical size={16} strokeWidth={2} />
|
||||
</Show>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<ProjectFolderBranch
|
||||
nodes={projectTreeNodes()}
|
||||
depth={0}
|
||||
parentId={null}
|
||||
selectedProjectId={selectedProject().id}
|
||||
isFolderCollapsed={isFolderCollapsed}
|
||||
onToggleFolder={toggleFolder}
|
||||
onSelectProject={selectProject}
|
||||
onOpenFolderMenu={openFolderMenu}
|
||||
onOpenProjectMenu={openProjectMenu}
|
||||
onNodePointerDown={handleNodePointerDown}
|
||||
onNodePointerMove={handleNodePointerMove}
|
||||
pendingFolderDraft={pendingFolderDraft()}
|
||||
pendingFolderName={pendingFolderName()}
|
||||
onPendingFolderNameChange={setPendingFolderName}
|
||||
onSubmitPendingFolder={submitPendingFolder}
|
||||
onCancelPendingFolder={cancelPendingFolder}
|
||||
pendingFolderRename={pendingFolderRename()}
|
||||
pendingFolderRenameName={pendingFolderRenameName()}
|
||||
onPendingFolderRenameChange={setPendingFolderRenameName}
|
||||
onSubmitPendingFolderRename={submitPendingFolderRename}
|
||||
onCancelPendingFolderRename={cancelPendingFolderRename}
|
||||
dragState={dragState()}
|
||||
isTreeClickSuppressed={suppressNextTreeClick}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
</Show>
|
||||
|
||||
<ProjectContextMenu
|
||||
target={contextMenu.menuState()?.target ?? null}
|
||||
position={contextMenuPosition()}
|
||||
menuRef={setContextMenuElement}
|
||||
onClose={contextMenu.closeMenu}
|
||||
onSelect={handleContextActionSelect}
|
||||
/>
|
||||
|
||||
<Show when={draggedNode()} keyed>
|
||||
{(node): JSX.Element => {
|
||||
const GhostIcon = node.kind === "folder" ? Folder : LayoutGrid;
|
||||
|
||||
return (
|
||||
<Portal>
|
||||
<div class={styles.dragGhostLayer} aria-hidden="true">
|
||||
<div
|
||||
class={styles.dragGhost}
|
||||
style={{
|
||||
"--drag-ghost-x": `${dragGhostPosition().x}px`,
|
||||
"--drag-ghost-y": `${dragGhostPosition().y}px`,
|
||||
}}
|
||||
>
|
||||
<GhostIcon class={styles.icon} size={18} strokeWidth={2} />
|
||||
<div class={styles.dragGhostCopy}>
|
||||
<div class={styles.dragGhostTitle}>{node.kind === "folder" ? node.label : node.item.name}</div>
|
||||
<div class={styles.dragGhostMeta}>{draggedNodeMeta()}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Portal>
|
||||
);
|
||||
}}
|
||||
</Show>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,109 @@
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
import type { ProjectFoldersResponse } from "./ProjectSelector.data";
|
||||
|
||||
const readProjectFoldersResponse = async (response: Response): Promise<ProjectFoldersResponse> =>
|
||||
(await response.json()) as ProjectFoldersResponse;
|
||||
|
||||
export const isValidProjectFolderProjectId = (projectId: string): boolean =>
|
||||
Boolean(projectId);
|
||||
|
||||
export const fetchProjectFolders = async (projectId: string): Promise<ProjectFoldersResponse> => {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
const body = await readProjectFoldersResponse(response);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to load project folders.");
|
||||
}
|
||||
|
||||
return body;
|
||||
};
|
||||
|
||||
export const createProjectFolderRequest = async (
|
||||
projectId: string,
|
||||
name: string,
|
||||
parentFolderId: string | null,
|
||||
): Promise<ProjectFoldersResponse> => {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ name, parentFolderId }),
|
||||
});
|
||||
const body = await readProjectFoldersResponse(response);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to create project folder.");
|
||||
}
|
||||
|
||||
return body;
|
||||
};
|
||||
|
||||
export const deleteProjectFolderRequest = async (
|
||||
projectId: string,
|
||||
folderId: string,
|
||||
): Promise<ProjectFoldersResponse> => {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders?folderId=${encodeURIComponent(folderId)}`, {
|
||||
method: "DELETE",
|
||||
headers: { Accept: "application/json" },
|
||||
});
|
||||
const body = await readProjectFoldersResponse(response);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to delete project folder.");
|
||||
}
|
||||
|
||||
return body;
|
||||
};
|
||||
|
||||
export const moveProjectFolderRequest = async (
|
||||
projectId: string,
|
||||
payload: {
|
||||
folderId: string;
|
||||
folderNodeId: string;
|
||||
parentFolderId: string | null;
|
||||
parentNodeId: string | null;
|
||||
targetIndex: number;
|
||||
},
|
||||
): Promise<ProjectFoldersResponse> => {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders/move`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
const body = await readProjectFoldersResponse(response);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to move project folder.");
|
||||
}
|
||||
|
||||
return body;
|
||||
};
|
||||
|
||||
export const renameProjectFolderRequest = async (
|
||||
projectId: string,
|
||||
folderId: string,
|
||||
name: string,
|
||||
): Promise<ProjectFoldersResponse> => {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({ folderId, name }),
|
||||
});
|
||||
const body = await readProjectFoldersResponse(response);
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to rename project folder.");
|
||||
}
|
||||
|
||||
return body;
|
||||
};
|
||||
+1
-1
@@ -7,7 +7,7 @@ import {
|
||||
type WorkspaceContextMenuAction,
|
||||
type WorkspaceContextMenuShortcut,
|
||||
type WorkspaceContextMenuTarget,
|
||||
} from "../data/shell.data";
|
||||
} from "../../app-shell/data/shell.data";
|
||||
import styles from "./WorkspaceContextMenu.module.scss";
|
||||
|
||||
type ShortcutPlatform = "mac" | "windows";
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
import { createEffect, createSignal, onCleanup } from "solid-js";
|
||||
import type { WorkspaceContextMenuTarget } from "../data/shell.data";
|
||||
import type { WorkspaceContextMenuTarget } from "../../app-shell/data/shell.data";
|
||||
|
||||
type WorkspaceContextMenuState = {
|
||||
target: WorkspaceContextMenuTarget;
|
||||
+1
-1
@@ -7,7 +7,7 @@ import {
|
||||
type WorkspaceContextMenuAction,
|
||||
type WorkspaceContextMenuSection,
|
||||
type WorkspaceContextMenuTarget,
|
||||
} from "../data/shell.data";
|
||||
} from "../../app-shell/data/shell.data";
|
||||
import styles from "./WorkspaceMobileActionSheet.module.scss";
|
||||
|
||||
type WorkspaceMobileActionSheetProps = {
|
||||
+57
@@ -0,0 +1,57 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/WorkspaceSidebar/WorkspaceSidebar.data.ts
|
||||
|
||||
import type { NavTreeAdapter, NavTreeDropTarget } from "../shared/navTreeDnd";
|
||||
import type { WorkspaceTreeNode } from "../../app-shell/data/shell.data";
|
||||
|
||||
export type WorkspaceSidebarProps = {
|
||||
collapsed: boolean;
|
||||
railCollapsed: boolean;
|
||||
onToggleRailCollapse: () => void;
|
||||
};
|
||||
|
||||
export type PendingWorkspaceFolderDraft = {
|
||||
parentId: string | null;
|
||||
depth: number;
|
||||
};
|
||||
|
||||
export type WorkspaceDragTarget = NavTreeDropTarget;
|
||||
|
||||
export type WorkspaceDragState = {
|
||||
draggedNodeId: string;
|
||||
dropTarget: WorkspaceDragTarget | null;
|
||||
};
|
||||
|
||||
export type DragGhostPosition = {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
|
||||
export type PendingWorkspaceFolderRename = {
|
||||
folderId: string;
|
||||
depth: number;
|
||||
};
|
||||
|
||||
export const LONG_PRESS_MS = 320;
|
||||
|
||||
export const getWorkspaceTreeNodeId = (node: WorkspaceTreeNode): string => node.id;
|
||||
|
||||
export const countWorkspaceFolderSiblingsBeforeIndex = (
|
||||
siblings: readonly WorkspaceTreeNode[],
|
||||
index: number,
|
||||
): number => siblings.slice(0, index).filter((node) => node.kind === "folder").length;
|
||||
|
||||
export 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,
|
||||
};
|
||||
|
||||
export const isContextMenuKeyboardTrigger = (event: KeyboardEvent): boolean =>
|
||||
event.key === "ContextMenu" || (event.shiftKey && event.key === "F10");
|
||||
+534
@@ -0,0 +1,534 @@
|
||||
// Path: Frontend/src/components/workspace-navigation/WorkspaceSidebar/WorkspaceSidebar.hook.ts
|
||||
|
||||
import { createEffect, createSignal, onCleanup, onMount } from "solid-js";
|
||||
import { useAppShellData } from "../../app-shell/data/app-shell.context";
|
||||
import {
|
||||
createWorkspaceSurfaceTarget,
|
||||
getWorkspaceItemTypeDefinition,
|
||||
type WorkspaceContextMenuAction,
|
||||
type WorkspaceContextMenuTarget,
|
||||
type WorkspaceItemTypeId,
|
||||
type WorkspaceTreeNode,
|
||||
} from "../../app-shell/data/shell.data";
|
||||
import {
|
||||
collectBranchNodeIds,
|
||||
findTreeNodeDepth,
|
||||
findTreeNodeLocation,
|
||||
getPointerRelativeY,
|
||||
isUuidString,
|
||||
moveTreeNode,
|
||||
resolveTreeDropTarget,
|
||||
} from "../shared/navTreeDnd";
|
||||
import { useWorkspaceTreeData } from "../shared/useWorkspaceTreeData";
|
||||
import { createWorkspaceContextMenuController } from "../WorkspaceContextMenu/createWorkspaceContextMenuController";
|
||||
import {
|
||||
countWorkspaceFolderSiblingsBeforeIndex,
|
||||
getWorkspaceTreeNodeId,
|
||||
LONG_PRESS_MS,
|
||||
workspaceTreeAdapter,
|
||||
type DragGhostPosition,
|
||||
type PendingWorkspaceFolderDraft,
|
||||
type PendingWorkspaceFolderRename,
|
||||
type WorkspaceDragTarget,
|
||||
type WorkspaceDragState,
|
||||
} from "./WorkspaceSidebar.data";
|
||||
|
||||
export const useWorkspaceSidebar = () => {
|
||||
const appShellData = useAppShellData();
|
||||
const activeProject = () => appShellData.activeProject();
|
||||
const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false);
|
||||
const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]);
|
||||
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingWorkspaceFolderDraft | null>(null);
|
||||
const [pendingFolderName, setPendingFolderName] = createSignal("");
|
||||
const [pendingFolderRename, setPendingFolderRename] = createSignal<PendingWorkspaceFolderRename | null>(null);
|
||||
const [pendingFolderRenameName, setPendingFolderRenameName] = createSignal("");
|
||||
const [dragState, setDragState] = createSignal<WorkspaceDragState | null>(null);
|
||||
const [dragGhostPosition, setDragGhostPosition] = createSignal<DragGhostPosition>({ x: 0, y: 0 });
|
||||
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
||||
let lastSelectedProjectId: string | null = null;
|
||||
const {
|
||||
workspaceTreeNodes,
|
||||
setWorkspaceTreeNodes,
|
||||
resolveFolderPath,
|
||||
resolveItemPath,
|
||||
createFolder,
|
||||
renameFolder,
|
||||
deleteFolder,
|
||||
moveFolder,
|
||||
createItem,
|
||||
deleteItem,
|
||||
moveItem,
|
||||
} = useWorkspaceTreeData({
|
||||
activeProjectId: () => activeProject()?.id ?? "",
|
||||
fallbackWorkspaceTree: () => appShellData.workspaceTree(),
|
||||
});
|
||||
const contextMenu = createWorkspaceContextMenuController();
|
||||
let longPressTimer: number | undefined;
|
||||
let suppressClickTimer: number | undefined;
|
||||
const sidebarContextMenuTarget = () => createWorkspaceSurfaceTarget(appShellData.activeProject());
|
||||
const isFolderCollapsed = (folderId: string): boolean => collapsedFolderIds().includes(folderId);
|
||||
const folderIds = (): string[] => collectBranchNodeIds(workspaceTreeNodes(), workspaceTreeAdapter);
|
||||
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;
|
||||
}
|
||||
|
||||
collapseAllFolders();
|
||||
};
|
||||
const resetWorkspaceTreeInteractionState = (): void => {
|
||||
setCollapsedFolderIds([]);
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
setDragState(null);
|
||||
};
|
||||
const syncCollapsedFolderIds = (): void => {
|
||||
const availableFolderIds = new Set(collectBranchNodeIds(workspaceTreeNodes(), workspaceTreeAdapter));
|
||||
setCollapsedFolderIds((current) => current.filter((id) => availableFolderIds.has(id)));
|
||||
};
|
||||
const updateDragGhostPosition = (x: number, y: number): void => {
|
||||
setDragGhostPosition({ x: x + 18, y: y + 18 });
|
||||
};
|
||||
const draggedNode = (): WorkspaceTreeNode | null => {
|
||||
const currentDragState = dragState();
|
||||
if (!currentDragState) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return findTreeNodeLocation(workspaceTreeNodes(), currentDragState.draggedNodeId, workspaceTreeAdapter)?.node ?? null;
|
||||
};
|
||||
const draggedNodeMeta = (): string => {
|
||||
const node = draggedNode();
|
||||
if (!node) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (node.kind === "folder") {
|
||||
return "Folder";
|
||||
}
|
||||
|
||||
return getWorkspaceItemTypeDefinition(node.itemType).label;
|
||||
};
|
||||
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(() => {
|
||||
syncCollapsedFolderIds();
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
const projectId = activeProject()?.id ?? null;
|
||||
|
||||
if (lastSelectedProjectId === null) {
|
||||
lastSelectedProjectId = projectId;
|
||||
return;
|
||||
}
|
||||
|
||||
if (projectId === lastSelectedProjectId) {
|
||||
return;
|
||||
}
|
||||
|
||||
lastSelectedProjectId = projectId;
|
||||
resetWorkspaceTreeInteractionState();
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
const handlePointerMove = (event: PointerEvent): void => {
|
||||
if (!dragState()) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateDragGhostPosition(event.clientX, event.clientY);
|
||||
};
|
||||
|
||||
const handlePointerUp = (): void => {
|
||||
clearLongPressTimer();
|
||||
|
||||
const nextDragState = dragState();
|
||||
|
||||
if (!nextDragState?.dropTarget) {
|
||||
if (nextDragState) {
|
||||
suppressTreeClickTemporarily();
|
||||
}
|
||||
setDragState(null);
|
||||
return;
|
||||
}
|
||||
|
||||
suppressTreeClickTemporarily();
|
||||
|
||||
const currentNodes = workspaceTreeNodes();
|
||||
const draggedLocation = findTreeNodeLocation(currentNodes, nextDragState.draggedNodeId, workspaceTreeAdapter);
|
||||
const canPersistMove = isUuidString(activeProject()?.id ?? "");
|
||||
const previewNodes = moveTreeNode(currentNodes, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter);
|
||||
const previewLocation = findTreeNodeLocation(previewNodes, nextDragState.draggedNodeId, workspaceTreeAdapter);
|
||||
const persistedParentLocation = previewLocation?.parentId
|
||||
? findTreeNodeLocation(previewNodes, previewLocation.parentId, workspaceTreeAdapter)
|
||||
: null;
|
||||
const previewSiblings = previewLocation?.parentId
|
||||
? persistedParentLocation?.node.kind === "folder"
|
||||
? persistedParentLocation.node.children ?? []
|
||||
: []
|
||||
: previewNodes;
|
||||
const targetIndex = previewLocation
|
||||
? countWorkspaceFolderSiblingsBeforeIndex(previewSiblings, previewLocation.index)
|
||||
: 0;
|
||||
|
||||
if (
|
||||
canPersistMove &&
|
||||
draggedLocation?.node.kind === "folder" &&
|
||||
(!previewLocation?.parentId || persistedParentLocation?.node.kind === "folder")
|
||||
) {
|
||||
void moveFolder(
|
||||
draggedLocation.node.id,
|
||||
persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.id : null,
|
||||
targetIndex,
|
||||
);
|
||||
} else if (
|
||||
canPersistMove &&
|
||||
draggedLocation?.node.kind === "item" &&
|
||||
resolveItemPath(draggedLocation.node.id) &&
|
||||
(!previewLocation?.parentId || persistedParentLocation?.node.kind === "folder")
|
||||
) {
|
||||
void moveItem(
|
||||
draggedLocation.node.id,
|
||||
persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.id : null,
|
||||
previewLocation?.index ?? 0,
|
||||
);
|
||||
} else {
|
||||
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("pointermove", handlePointerMove);
|
||||
window.addEventListener("keydown", handleEscape);
|
||||
|
||||
onCleanup(() => {
|
||||
clearLongPressTimer();
|
||||
if (suppressClickTimer !== undefined) {
|
||||
window.clearTimeout(suppressClickTimer);
|
||||
}
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("keydown", handleEscape);
|
||||
});
|
||||
});
|
||||
|
||||
const beginFolderDraft = (parentId: string | null, depth: number): void => {
|
||||
if (parentId) {
|
||||
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
|
||||
}
|
||||
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
setPendingFolderName("");
|
||||
setPendingFolderDraft({ parentId, depth });
|
||||
};
|
||||
|
||||
const beginFolderRename = (folderId: string, label: string, depth: number): void => {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
setPendingFolderRename({ folderId, depth });
|
||||
setPendingFolderRenameName(label);
|
||||
};
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
const parentFolderPath = draft.parentId ? resolveFolderPath(draft.parentId) : null;
|
||||
if (draft.parentId && !parentFolderPath) {
|
||||
cancelPendingFolder();
|
||||
return;
|
||||
}
|
||||
|
||||
const created = await createFolder(name, draft.parentId);
|
||||
if (created) {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
}
|
||||
};
|
||||
|
||||
const deletePersistedFolder = async (folderId: string): Promise<void> => {
|
||||
const deleted = await deleteFolder(folderId);
|
||||
if (deleted) {
|
||||
setCollapsedFolderIds((current) => current.filter((id) => id !== folderId));
|
||||
}
|
||||
};
|
||||
|
||||
const submitPendingFolderRename = async (): Promise<void> => {
|
||||
const draft = pendingFolderRename();
|
||||
const name = pendingFolderRenameName().trim();
|
||||
const projectId = activeProject()?.id ?? "";
|
||||
|
||||
if (!draft) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!name) {
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
return;
|
||||
}
|
||||
|
||||
if (!projectId || !isUuidString(projectId)) {
|
||||
cancelPendingFolderRename();
|
||||
return;
|
||||
}
|
||||
|
||||
const folderPath = resolveFolderPath(draft.folderId);
|
||||
if (!folderPath) {
|
||||
cancelPendingFolderRename();
|
||||
return;
|
||||
}
|
||||
|
||||
const renamed = await renameFolder(draft.folderId, name);
|
||||
if (renamed) {
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
}
|
||||
};
|
||||
|
||||
const cancelPendingFolder = (): void => {
|
||||
setPendingFolderDraft(null);
|
||||
setPendingFolderName("");
|
||||
};
|
||||
|
||||
const cancelPendingFolderRename = (): void => {
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
};
|
||||
|
||||
const handleHeaderActionClick = (actionId: string): void => {
|
||||
switch (actionId) {
|
||||
case "toggle-workspace-folders":
|
||||
toggleAllFolders();
|
||||
return;
|
||||
case "search-workspace":
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const openWorkspaceCreateMenu = (element: HTMLElement): void => {
|
||||
contextMenu.openMenuFromElement(element, sidebarContextMenuTarget());
|
||||
};
|
||||
|
||||
const resolveCreateItemType = (actionId: string): WorkspaceItemTypeId | null => {
|
||||
switch (actionId) {
|
||||
case "create-doc":
|
||||
return "core.doc";
|
||||
case "create-board":
|
||||
return "core.board.kanban";
|
||||
case "create-list-board":
|
||||
return "core.board.list";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const createPersistedItem = async (itemType: WorkspaceItemTypeId, parentId: string | null): Promise<void> => {
|
||||
const definition = getWorkspaceItemTypeDefinition(itemType);
|
||||
await createItem(definition.defaultCreateLabel, itemType, parentId);
|
||||
};
|
||||
|
||||
const handleNodePointerDown = (event: PointerEvent, nodeId: string): void => {
|
||||
if (event.button !== 0 || pendingFolderDraft()) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateDragGhostPosition(event.clientX, event.clientY);
|
||||
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 => {
|
||||
const createItemType = resolveCreateItemType(action.id);
|
||||
if (createItemType) {
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
case "home":
|
||||
void createPersistedItem(createItemType, null);
|
||||
return;
|
||||
case "folder":
|
||||
void createPersistedItem(createItemType, target.id);
|
||||
return;
|
||||
case "settings":
|
||||
case "item":
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
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;
|
||||
case "rename-folder":
|
||||
if (target.kind === "folder") {
|
||||
beginFolderRename(target.id, target.label, findTreeNodeDepth(workspaceTreeNodes(), target.id, workspaceTreeAdapter) ?? 0);
|
||||
}
|
||||
return;
|
||||
case "delete-doc":
|
||||
case "delete-board":
|
||||
case "delete-list-board":
|
||||
if (target.kind === "item") {
|
||||
void deleteItem(target.id);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
activeProject,
|
||||
contextMenu,
|
||||
sidebarContextMenuTarget,
|
||||
isProjectDrawerOpen,
|
||||
setIsProjectDrawerOpen,
|
||||
workspaceTreeNodes,
|
||||
isFolderCollapsed,
|
||||
pendingFolderDraft,
|
||||
pendingFolderName,
|
||||
setPendingFolderName,
|
||||
submitPendingFolder,
|
||||
cancelPendingFolder,
|
||||
pendingFolderRename,
|
||||
pendingFolderRenameName,
|
||||
setPendingFolderRenameName,
|
||||
submitPendingFolderRename,
|
||||
cancelPendingFolderRename,
|
||||
handleNodePointerDown,
|
||||
handleNodePointerMove,
|
||||
dragState,
|
||||
suppressNextTreeClick,
|
||||
draggedNode,
|
||||
dragGhostPosition,
|
||||
draggedNodeMeta,
|
||||
workspaceFolderToggleLabel,
|
||||
areAllFoldersCollapsed,
|
||||
totalFolderCount,
|
||||
handleHeaderActionClick,
|
||||
openWorkspaceCreateMenu,
|
||||
handleContextActionSelect,
|
||||
toggleFolder,
|
||||
};
|
||||
};
|
||||
+90
-84
@@ -1,3 +1,5 @@
|
||||
@use "../shared/tree-nav" as treeNav;
|
||||
|
||||
.sidebar {
|
||||
--sidebar-nav-item-min-height: var(--control-size-lg);
|
||||
position: relative;
|
||||
@@ -117,56 +119,72 @@
|
||||
}
|
||||
|
||||
.treeSectionLabel {
|
||||
@include text-caption;
|
||||
@include treeNav.section-label;
|
||||
margin: var(--space-3) 0 var(--space-2);
|
||||
padding: 0 var(--space-3);
|
||||
color: var(--color-text-subtle);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.04em;
|
||||
}
|
||||
|
||||
.treeList {
|
||||
list-style: none;
|
||||
display: grid;
|
||||
gap: var(--space-1);
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
.treeEmptySlot {
|
||||
min-height: calc(var(--control-size-lg) - var(--space-2));
|
||||
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||
border-radius: var(--radius-lg);
|
||||
border: 1px dashed color-mix(in srgb, var(--color-border) 38%, transparent);
|
||||
opacity: 0.35;
|
||||
}
|
||||
|
||||
.treeInputRow {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
.treeSectionHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
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);
|
||||
margin-top: var(--space-3);
|
||||
margin-bottom: var(--space-2);
|
||||
padding-right: var(--space-1);
|
||||
}
|
||||
|
||||
.treeInput {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
.treeSectionHeader .treeSectionLabel {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.treeControls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
justify-content: flex-end;
|
||||
padding-right: var(--space-2);
|
||||
}
|
||||
|
||||
.treeControlButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: calc(var(--control-size-md) - var(--space-1));
|
||||
height: calc(var(--control-size-md) - var(--space-1));
|
||||
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);
|
||||
}
|
||||
|
||||
.treeControlButton:hover,
|
||||
.treeControlButton:focus-visible {
|
||||
border-color: color-mix(in srgb, var(--color-border-strong) 56%, transparent);
|
||||
background: var(--color-surface-hover);
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.treeInput::placeholder {
|
||||
color: var(--color-text-muted);
|
||||
.treeList {
|
||||
@include treeNav.tree-list;
|
||||
}
|
||||
|
||||
.treeEmptySlot {
|
||||
@include treeNav.empty-slot;
|
||||
}
|
||||
|
||||
.treeInputRow {
|
||||
@include treeNav.input-row;
|
||||
}
|
||||
|
||||
.treeInput {
|
||||
@include treeNav.input;
|
||||
}
|
||||
|
||||
.navItem {
|
||||
@@ -184,74 +202,44 @@
|
||||
}
|
||||
|
||||
.treeItem {
|
||||
width: 100%;
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
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: 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),
|
||||
box-shadow 160ms var(--easing-standard),
|
||||
transform 180ms var(--easing-standard);
|
||||
@include treeNav.item;
|
||||
}
|
||||
|
||||
.treeItem:hover,
|
||||
.treeItem:focus-visible {
|
||||
background: color-mix(in srgb, var(--color-surface-hover) 80%, var(--color-accent-soft) 20%);
|
||||
color: var(--color-text);
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||
@include treeNav.item-hover;
|
||||
}
|
||||
|
||||
.treeItemFolder {
|
||||
color: var(--color-text);
|
||||
@include treeNav.item-folder;
|
||||
}
|
||||
|
||||
.treeItemDragging {
|
||||
opacity: 0.45;
|
||||
transform: scale(0.985);
|
||||
box-shadow: none;
|
||||
@include treeNav.item-dragging;
|
||||
}
|
||||
|
||||
.treeItemDropBefore {
|
||||
box-shadow: inset 0 2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||
@include treeNav.item-drop-before;
|
||||
}
|
||||
|
||||
.treeItemDropAfter {
|
||||
box-shadow: inset 0 -2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||
@include treeNav.item-drop-after;
|
||||
}
|
||||
|
||||
.treeItemDropInside {
|
||||
border-color: color-mix(in srgb, var(--color-accent-strong) 55%, transparent);
|
||||
background: color-mix(in srgb, var(--color-accent-soft) 36%, var(--color-surface));
|
||||
color: var(--color-text);
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||
@include treeNav.item-drop-inside;
|
||||
}
|
||||
|
||||
.folderChevron {
|
||||
color: var(--color-text-muted);
|
||||
transition: transform 160ms var(--easing-standard);
|
||||
@include treeNav.folder-chevron;
|
||||
}
|
||||
|
||||
.folderChevronOpen {
|
||||
transform: rotate(90deg);
|
||||
@include treeNav.folder-chevron-open;
|
||||
}
|
||||
|
||||
.treeItemActive {
|
||||
border-color: var(--color-border);
|
||||
background: var(--color-surface);
|
||||
color: var(--color-text);
|
||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||
@include treeNav.item-active;
|
||||
}
|
||||
|
||||
.navItemActive {
|
||||
@@ -262,18 +250,35 @@
|
||||
}
|
||||
|
||||
.icon {
|
||||
color: inherit;
|
||||
opacity: 0.85;
|
||||
@include treeNav.icon;
|
||||
}
|
||||
|
||||
.label {
|
||||
@include text-label;
|
||||
min-width: 0;
|
||||
@include treeNav.label;
|
||||
}
|
||||
|
||||
.itemMeta {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
@include treeNav.item-meta;
|
||||
}
|
||||
|
||||
.dragGhostLayer {
|
||||
@include treeNav.drag-ghost-layer;
|
||||
}
|
||||
|
||||
.dragGhost {
|
||||
@include treeNav.drag-ghost;
|
||||
}
|
||||
|
||||
.dragGhostCopy {
|
||||
@include treeNav.drag-ghost-copy;
|
||||
}
|
||||
|
||||
.dragGhostTitle {
|
||||
@include treeNav.drag-ghost-title;
|
||||
}
|
||||
|
||||
.dragGhostMeta {
|
||||
@include treeNav.drag-ghost-meta;
|
||||
}
|
||||
|
||||
.sidebarCollapsed {
|
||||
@@ -309,6 +314,7 @@
|
||||
|
||||
.sidebarCollapsed .label,
|
||||
.sidebarCollapsed .itemMeta,
|
||||
.sidebarCollapsed .treeSectionHeader,
|
||||
.sidebarCollapsed .treeSectionLabel,
|
||||
.sidebarCollapsed .treeList {
|
||||
display: none;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user