Compare commits
23 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 32acf6dc17 | |||
| 6b87e8a1fe | |||
| 3247f28c87 | |||
| 891e8b83ed | |||
| ae1f347549 | |||
| 7e62ff6d9a | |||
| adcc9afe05 | |||
| 24d1e472a2 | |||
| da1b210865 | |||
| eadf630c61 | |||
| 4fb073a1ff | |||
| 9ddfa0c3c7 | |||
| a92e188f84 | |||
| dcf181d640 | |||
| 1a8556df68 | |||
| a5f0c41cba | |||
| 268093d223 | |||
| c64a7b8d44 | |||
| 0b368b09fa | |||
| 212dd1c435 | |||
| 69af324b1b | |||
| 5758074f6f | |||
| 5b9e14b442 |
@@ -1,10 +1,16 @@
|
|||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"log"
|
"log"
|
||||||
|
"os/signal"
|
||||||
|
"syscall"
|
||||||
|
"time"
|
||||||
|
|
||||||
"moku-backend/internal/bootstrap"
|
"moku-backend/internal/bootstrap"
|
||||||
"moku-backend/internal/process"
|
"moku-backend/internal/jobs"
|
||||||
|
"moku-backend/internal/worker"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
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)
|
app.Logger.Error("worker stopped", "error", err)
|
||||||
log.Fatal(err)
|
log.Fatal(err)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
+1046
-190
File diff suppressed because it is too large
Load Diff
@@ -2,11 +2,73 @@ package bootstrap
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
"os"
|
"os"
|
||||||
"path/filepath"
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
"testing"
|
"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) {
|
func TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot(t *testing.T) {
|
||||||
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
rootPath := filepath.Join(t.TempDir(), "POSIX")
|
||||||
t.Setenv("POSIX_ROOT", rootPath)
|
t.Setenv("POSIX_ROOT", rootPath)
|
||||||
@@ -58,6 +120,10 @@ func TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot(t *testing.T) {
|
|||||||
filepath.Join(rootPath, "users", "settings.json"),
|
filepath.Join(rootPath, "users", "settings.json"),
|
||||||
filepath.Join(rootPath, "users", "data.json"),
|
filepath.Join(rootPath, "users", "data.json"),
|
||||||
filepath.Join(rootPath, "users", "personals"),
|
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 {
|
for _, path := range requiredPaths {
|
||||||
@@ -101,6 +167,25 @@ func TestEnsureBootstrapPOSIXSkeletonInitializesEmptyRoot(t *testing.T) {
|
|||||||
if usersSettings["primaryAdminId"] != "admin-1" {
|
if usersSettings["primaryAdminId"] != "admin-1" {
|
||||||
t.Fatalf("expected primary admin id admin-1, got %#v", usersSettings["primaryAdminId"])
|
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) {
|
func TestCreateProjectHierarchyFolderOnDiskCreatesExpectedFolderShape(t *testing.T) {
|
||||||
@@ -142,6 +227,9 @@ func TestCreateProjectHierarchyFolderOnDiskCreatesExpectedFolderShape(t *testing
|
|||||||
}
|
}
|
||||||
|
|
||||||
folderPayload := readJSONFileForTest[map[string]any](t, filepath.Join(createdFolderPath, "folder.json"))
|
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" {
|
if folderPayload["name"] != "Design System" {
|
||||||
t.Fatalf("expected folder name Design System, got %#v", folderPayload["name"])
|
t.Fatalf("expected folder name Design System, got %#v", folderPayload["name"])
|
||||||
}
|
}
|
||||||
@@ -161,11 +249,307 @@ func TestCreateProjectHierarchyFolderOnDiskCreatesExpectedFolderShape(t *testing
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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) {
|
func TestBuildProjectHierarchyFolderTreeBuildsNestedStructure(t *testing.T) {
|
||||||
rows := []projectHierarchyFolderRow{
|
rows := []projectHierarchyFolderRow{
|
||||||
{Path: "projects/project-primary-project/children/folder-design", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Design"},
|
{ID: "folder-design-id", Path: "projects/project-primary-project/children/folder-design", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Design"},
|
||||||
{Path: "projects/project-primary-project/children/folder-design/children/folder-research", ParentPath: "projects/project-primary-project/children/folder-design/children", Label: "Research"},
|
{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"},
|
||||||
{Path: "projects/project-primary-project/children/folder-ops", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Ops"},
|
{ID: "folder-ops-id", Path: "projects/project-primary-project/children/folder-ops", ParentPath: projectHierarchyRootPath("primary-project"), Label: "Ops"},
|
||||||
}
|
}
|
||||||
|
|
||||||
folders := buildProjectHierarchyFolderTree(rows, projectHierarchyRootPath("primary-project"))
|
folders := buildProjectHierarchyFolderTree(rows, projectHierarchyRootPath("primary-project"))
|
||||||
@@ -178,6 +562,64 @@ func TestBuildProjectHierarchyFolderTreeBuildsNestedStructure(t *testing.T) {
|
|||||||
if len(folders[0].Children) != 1 || folders[0].Children[0].Label != "Research" {
|
if len(folders[0].Children) != 1 || folders[0].Children[0].Label != "Research" {
|
||||||
t.Fatalf("unexpected nested folder structure: %#v", folders[0].Children)
|
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 {
|
func readJSONFileForTest[T any](t *testing.T, path string) T {
|
||||||
|
|||||||
@@ -14,7 +14,26 @@ import (
|
|||||||
|
|
||||||
type createProjectFolderRequest struct {
|
type createProjectFolderRequest struct {
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
ParentFolderID string `json:"parentFolderId"`
|
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"`
|
||||||
}
|
}
|
||||||
|
|
||||||
func (routes apiRoutes) handleProjectFolders(w http.ResponseWriter, r *http.Request) {
|
func (routes apiRoutes) handleProjectFolders(w http.ResponseWriter, r *http.Request) {
|
||||||
@@ -26,7 +45,7 @@ func (routes apiRoutes) handleProjectFolders(w http.ResponseWriter, r *http.Requ
|
|||||||
|
|
||||||
folders, err := routes.bootstrapService().GetProjectHierarchyFolders(r.Context(), projectID)
|
folders, err := routes.bootstrapService().GetProjectHierarchyFolders(r.Context(), projectID)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
routes.writeProjectFolderError(w, r, err)
|
routes.writeProjectFolderError(w, r, err, "load")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,7 +73,7 @@ func (routes apiRoutes) handleCreateProjectFolder(w http.ResponseWriter, r *http
|
|||||||
}
|
}
|
||||||
|
|
||||||
payload.Name = strings.TrimSpace(payload.Name)
|
payload.Name = strings.TrimSpace(payload.Name)
|
||||||
payload.ParentFolderID = strings.TrimSpace(payload.ParentFolderID)
|
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||||
if payload.Name == "" {
|
if payload.Name == "" {
|
||||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Folder name is required.")
|
||||||
return
|
return
|
||||||
@@ -62,11 +81,11 @@ func (routes apiRoutes) handleCreateProjectFolder(w http.ResponseWriter, r *http
|
|||||||
|
|
||||||
result, err := routes.bootstrapService().CreateProjectFolder(r.Context(), bootstrapservice.CreateProjectFolderInput{
|
result, err := routes.bootstrapService().CreateProjectFolder(r.Context(), bootstrapservice.CreateProjectFolderInput{
|
||||||
ProjectID: projectID,
|
ProjectID: projectID,
|
||||||
ParentFolderID: payload.ParentFolderID,
|
ParentFolderPath: payload.ParentFolderPath,
|
||||||
Name: payload.Name,
|
Name: payload.Name,
|
||||||
})
|
})
|
||||||
if err != nil {
|
if err != nil {
|
||||||
routes.writeProjectFolderError(w, r, err)
|
routes.writeProjectFolderError(w, r, err, "persist")
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,20 +98,370 @@ func (routes apiRoutes) handleCreateProjectFolder(w http.ResponseWriter, r *http
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.Request, err error) {
|
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) 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) writeProjectFolderError(w http.ResponseWriter, r *http.Request, err error, operation string) {
|
||||||
switch {
|
switch {
|
||||||
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound):
|
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound):
|
||||||
WriteError(w, http.StatusNotFound, RequestIDFromContext(r.Context()), "not_found", err.Error())
|
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:
|
default:
|
||||||
routes.cfg.Logger.Error("persist project folder", "error", err, "path", r.URL.Path)
|
routes.cfg.Logger.Error(operation+" project folder", "error", err, "path", r.URL.Path)
|
||||||
message := "Failed to persist project folder."
|
message := "Failed to " + operation + " project folder."
|
||||||
if routes.cfg.Config.IsDevelopment() {
|
if routes.cfg.Config.IsDevelopment() {
|
||||||
message = message + " " + err.Error()
|
message = message + " " + err.Error()
|
||||||
}
|
}
|
||||||
WriteError(w, http.StatusInternalServerError, RequestIDFromContext(r.Context()), "project_folder_persist_failed", message)
|
WriteError(w, http.StatusInternalServerError, RequestIDFromContext(r.Context()), "project_folder_"+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 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) {
|
func decodeProjectFolderRequest(w http.ResponseWriter, r *http.Request) (createProjectFolderRequest, bool) {
|
||||||
var payload createProjectFolderRequest
|
var payload createProjectFolderRequest
|
||||||
|
|
||||||
|
|||||||
@@ -36,6 +36,14 @@ func (routes apiRoutes) Register(router chi.Router) {
|
|||||||
apiRouter.Route("/projects/{projectId}", func(projectRouter chi.Router) {
|
apiRouter.Route("/projects/{projectId}", func(projectRouter chi.Router) {
|
||||||
projectRouter.Get("/folders", routes.handleProjectFolders)
|
projectRouter.Get("/folders", routes.handleProjectFolders)
|
||||||
projectRouter.Post("/folders", routes.handleCreateProjectFolder)
|
projectRouter.Post("/folders", routes.handleCreateProjectFolder)
|
||||||
|
projectRouter.Patch("/folders", routes.handleRenameProjectFolder)
|
||||||
|
projectRouter.Patch("/folders/move", routes.handleMoveProjectFolder)
|
||||||
|
projectRouter.Delete("/folders", routes.handleDeleteProjectFolder)
|
||||||
|
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)
|
||||||
})
|
})
|
||||||
|
|
||||||
if routes.cfg.Config.IsDevelopment() {
|
if routes.cfg.Config.IsDevelopment() {
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -411,7 +411,7 @@ func classifyPath(relPath string, isDir bool) (logicalType, fileRole string) {
|
|||||||
return "hierarchy_folder", ""
|
return "hierarchy_folder", ""
|
||||||
}
|
}
|
||||||
if hasTreeAncestor && strings.HasPrefix(name, "folder-") {
|
if hasTreeAncestor && strings.HasPrefix(name, "folder-") {
|
||||||
return "folder", ""
|
return "hierarchy_folder", ""
|
||||||
}
|
}
|
||||||
if hasTreeAncestor && strings.HasPrefix(name, "item-") {
|
if hasTreeAncestor && strings.HasPrefix(name, "item-") {
|
||||||
return "item", ""
|
return "item", ""
|
||||||
@@ -425,7 +425,7 @@ func classifyPath(relPath string, isDir bool) (logicalType, fileRole string) {
|
|||||||
return "item", fileRole
|
return "item", fileRole
|
||||||
}
|
}
|
||||||
if strings.HasPrefix(parentName, "folder-") {
|
if strings.HasPrefix(parentName, "folder-") {
|
||||||
return "folder", fileRole
|
return "hierarchy_folder", fileRole
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return "project", fileRole
|
return "project", fileRole
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ func TestScanRootBuildsProjectedNodesFromBootstrapShape(t *testing.T) {
|
|||||||
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", "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", "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"))
|
||||||
|
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, "projects", "project-primary-project", "tree", "folder-docs", "item-roadmap"))
|
||||||
mustMkdirAll(t, filepath.Join(root, "users", "personals"))
|
mustMkdirAll(t, filepath.Join(root, "users", "personals"))
|
||||||
|
|
||||||
@@ -185,10 +186,15 @@ func TestScanRootBuildsProjectedNodesFromBootstrapShape(t *testing.T) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
treeFolder := index["projects/project-primary-project/tree/folder-docs"]
|
treeFolder := index["projects/project-primary-project/tree/folder-docs"]
|
||||||
if treeFolder.LogicalType != "folder" || treeFolder.ProjectSlug != "primary-project" {
|
if treeFolder.LogicalType != "hierarchy_folder" || treeFolder.ProjectSlug != "primary-project" {
|
||||||
t.Fatalf("unexpected tree folder node: %#v", treeFolder)
|
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"]
|
treeItem := index["projects/project-primary-project/tree/folder-docs/item-roadmap/item.json"]
|
||||||
if treeItem.LogicalType != "item" || treeItem.FileRole != "item" {
|
if treeItem.LogicalType != "item" || treeItem.FileRole != "item" {
|
||||||
t.Fatalf("unexpected tree item classification: %#v", treeItem)
|
t.Fatalf("unexpected tree item classification: %#v", treeItem)
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
@use "../shared/tree-nav" as treeNav;
|
||||||
|
|
||||||
.root {
|
.root {
|
||||||
display: grid;
|
display: grid;
|
||||||
--project-drawer-gap: var(--space-3);
|
--project-drawer-gap: var(--space-3);
|
||||||
@@ -191,12 +193,9 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.treeSectionLabel {
|
.treeSectionLabel {
|
||||||
@include text-caption;
|
@include treeNav.section-label;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
padding: 0 var(--space-3);
|
padding: 0 var(--space-3);
|
||||||
color: var(--color-text-subtle);
|
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.04em;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeSectionHeader {
|
.treeSectionHeader {
|
||||||
@@ -248,133 +247,72 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.treeList {
|
.treeList {
|
||||||
list-style: none;
|
@include treeNav.tree-list;
|
||||||
display: grid;
|
|
||||||
gap: var(--space-1);
|
|
||||||
padding: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeEmptySlot {
|
.treeEmptySlot {
|
||||||
min-height: calc(var(--control-size-lg) - var(--space-2));
|
@include treeNav.empty-slot;
|
||||||
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 {
|
.treeInputRow {
|
||||||
width: 100%;
|
@include treeNav.input-row;
|
||||||
min-width: 0;
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: auto minmax(0, 1fr);
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--space-2);
|
|
||||||
min-height: calc(var(--control-size-lg) - var(--space-2));
|
|
||||||
padding: var(--space-2) var(--space-3);
|
|
||||||
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
|
||||||
border: 1px solid color-mix(in srgb, var(--color-border) 42%, transparent);
|
|
||||||
border-radius: var(--radius-lg);
|
|
||||||
background: color-mix(in srgb, var(--color-surface) 94%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeInput {
|
.treeInput {
|
||||||
width: 100%;
|
@include treeNav.input;
|
||||||
min-width: 0;
|
|
||||||
border: 0;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--color-text);
|
|
||||||
font: inherit;
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.treeInput::placeholder {
|
|
||||||
color: var(--color-text-muted);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItem {
|
.treeItem {
|
||||||
width: 100%;
|
@include treeNav.item;
|
||||||
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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItem:hover,
|
.treeItem:hover,
|
||||||
.treeItem:focus-visible {
|
.treeItem:focus-visible {
|
||||||
background: color-mix(in srgb, var(--color-surface-hover) 80%, var(--color-accent-soft) 20%);
|
@include treeNav.item-hover;
|
||||||
color: var(--color-text);
|
|
||||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemFolder {
|
.treeItemFolder {
|
||||||
color: var(--color-text);
|
@include treeNav.item-folder;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemDragging {
|
.treeItemDragging {
|
||||||
opacity: 0.45;
|
@include treeNav.item-dragging;
|
||||||
transform: scale(0.985);
|
|
||||||
box-shadow: none;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemDropBefore {
|
.treeItemDropBefore {
|
||||||
box-shadow: inset 0 2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
@include treeNav.item-drop-before;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemDropAfter {
|
.treeItemDropAfter {
|
||||||
box-shadow: inset 0 -2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
@include treeNav.item-drop-after;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemDropInside {
|
.treeItemDropInside {
|
||||||
border-color: color-mix(in srgb, var(--color-accent-strong) 55%, transparent);
|
@include treeNav.item-drop-inside;
|
||||||
background: color-mix(in srgb, var(--color-accent-soft) 36%, var(--color-surface));
|
|
||||||
color: var(--color-text);
|
|
||||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.folderChevron {
|
.folderChevron {
|
||||||
color: var(--color-text-muted);
|
@include treeNav.folder-chevron;
|
||||||
transition: transform 160ms var(--easing-standard);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.folderChevronOpen {
|
.folderChevronOpen {
|
||||||
transform: rotate(90deg);
|
@include treeNav.folder-chevron-open;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemActive {
|
.treeItemActive {
|
||||||
border-color: var(--color-border);
|
@include treeNav.item-active;
|
||||||
background: var(--color-surface);
|
|
||||||
color: var(--color-text);
|
|
||||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.icon {
|
.icon {
|
||||||
color: inherit;
|
@include treeNav.icon;
|
||||||
opacity: 0.85;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.label {
|
.label {
|
||||||
@include text-label;
|
@include treeNav.label;
|
||||||
min-width: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.itemMeta {
|
.itemMeta {
|
||||||
@include text-caption;
|
@include treeNav.item-meta;
|
||||||
color: var(--color-text-muted);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 720px) {
|
@media (max-width: 720px) {
|
||||||
|
|||||||
@@ -5,6 +5,17 @@ import { ChevronDown, ChevronRight, Folder, LayoutGrid, ListCollapse, UnfoldVert
|
|||||||
import { ProjectContextMenu } from "../ProjectContextMenu/ProjectContextMenu";
|
import { ProjectContextMenu } from "../ProjectContextMenu/ProjectContextMenu";
|
||||||
import { useAppShellData } from "../data/app-shell.context";
|
import { useAppShellData } from "../data/app-shell.context";
|
||||||
import { resolveAPIBase } from "../../../lib/api";
|
import { resolveAPIBase } from "../../../lib/api";
|
||||||
|
import {
|
||||||
|
collectBranchNodeIds,
|
||||||
|
findTreeNodeDepth,
|
||||||
|
findTreeNodeLocation,
|
||||||
|
getPointerRelativeY,
|
||||||
|
isUuidString,
|
||||||
|
moveTreeNode,
|
||||||
|
resolveTreeDropTarget,
|
||||||
|
type NavTreeAdapter,
|
||||||
|
type NavTreeDropTarget,
|
||||||
|
} from "../shared/navTreeDnd";
|
||||||
import {
|
import {
|
||||||
createProjectFolderTarget,
|
createProjectFolderTarget,
|
||||||
createProjectSurfaceTarget,
|
createProjectSurfaceTarget,
|
||||||
@@ -25,6 +36,7 @@ type ProjectSelectorProps = {
|
|||||||
type ProjectFolderNode = {
|
type ProjectFolderNode = {
|
||||||
kind: "folder";
|
kind: "folder";
|
||||||
id: string;
|
id: string;
|
||||||
|
path: string;
|
||||||
label: string;
|
label: string;
|
||||||
meta?: string;
|
meta?: string;
|
||||||
children: ProjectTreeNode[];
|
children: ProjectTreeNode[];
|
||||||
@@ -39,6 +51,7 @@ type ProjectTreeNode = ProjectFolderNode | ProjectLeafNode;
|
|||||||
|
|
||||||
type PersistedProjectFolderRecord = {
|
type PersistedProjectFolderRecord = {
|
||||||
id: string;
|
id: string;
|
||||||
|
path: string;
|
||||||
label: string;
|
label: string;
|
||||||
children: PersistedProjectFolderRecord[];
|
children: PersistedProjectFolderRecord[];
|
||||||
};
|
};
|
||||||
@@ -46,6 +59,10 @@ type PersistedProjectFolderRecord = {
|
|||||||
type ProjectFoldersResponse = {
|
type ProjectFoldersResponse = {
|
||||||
data?: {
|
data?: {
|
||||||
folders?: PersistedProjectFolderRecord[];
|
folders?: PersistedProjectFolderRecord[];
|
||||||
|
renamedFolder?: PersistedProjectFolderRecord;
|
||||||
|
movedFolder?: PersistedProjectFolderRecord;
|
||||||
|
previousFolderId?: string;
|
||||||
|
previousFolderPath?: string;
|
||||||
};
|
};
|
||||||
error?: string;
|
error?: string;
|
||||||
message?: string;
|
message?: string;
|
||||||
@@ -56,24 +73,18 @@ type PendingProjectFolderDraft = {
|
|||||||
depth: number;
|
depth: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
type ProjectDragTarget = {
|
type PendingProjectFolderRename = {
|
||||||
parentId: string | null;
|
folderId: string;
|
||||||
index: number;
|
depth: number;
|
||||||
intent: "before" | "after" | "inside";
|
|
||||||
targetNodeId?: string;
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
type ProjectDragTarget = NavTreeDropTarget;
|
||||||
|
|
||||||
type ProjectDragState = {
|
type ProjectDragState = {
|
||||||
draggedNodeId: string;
|
draggedNodeId: string;
|
||||||
dropTarget: ProjectDragTarget | null;
|
dropTarget: ProjectDragTarget | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type ProjectNodeLocation = {
|
|
||||||
parentId: string | null;
|
|
||||||
index: number;
|
|
||||||
node: ProjectTreeNode;
|
|
||||||
};
|
|
||||||
|
|
||||||
const LONG_PRESS_MS = 320;
|
const LONG_PRESS_MS = 320;
|
||||||
|
|
||||||
const getProjectTreeNodeId = (node: ProjectTreeNode): string =>
|
const getProjectTreeNodeId = (node: ProjectTreeNode): string =>
|
||||||
@@ -83,6 +94,7 @@ const buildPersistedFolderNodes = (folders: readonly PersistedProjectFolderRecor
|
|||||||
folders.map((folder) => ({
|
folders.map((folder) => ({
|
||||||
kind: "folder",
|
kind: "folder",
|
||||||
id: folder.id,
|
id: folder.id,
|
||||||
|
path: folder.path,
|
||||||
label: folder.label,
|
label: folder.label,
|
||||||
children: buildPersistedFolderNodes(folder.children ?? []),
|
children: buildPersistedFolderNodes(folder.children ?? []),
|
||||||
}));
|
}));
|
||||||
@@ -91,6 +103,9 @@ const buildProjectTree = (
|
|||||||
items: readonly ProjectItem[],
|
items: readonly ProjectItem[],
|
||||||
folders: readonly PersistedProjectFolderRecord[] = [],
|
folders: readonly PersistedProjectFolderRecord[] = [],
|
||||||
): ProjectTreeNode[] => [
|
): ProjectTreeNode[] => [
|
||||||
|
// The selector still presents scaffold project leaves beside persisted folders.
|
||||||
|
// Keep that mixed root shape explicit here so the drag/drop logic can account
|
||||||
|
// for folder-only ordering when we persist sibling positions.
|
||||||
...items.map((item) => ({
|
...items.map((item) => ({
|
||||||
kind: "project" as const,
|
kind: "project" as const,
|
||||||
item,
|
item,
|
||||||
@@ -98,198 +113,25 @@ const buildProjectTree = (
|
|||||||
...buildPersistedFolderNodes(folders),
|
...buildPersistedFolderNodes(folders),
|
||||||
];
|
];
|
||||||
|
|
||||||
const collectProjectFolderIds = (nodes: readonly ProjectTreeNode[]): string[] => {
|
const countProjectFolderSiblingsBeforeIndex = (
|
||||||
const ids: string[] = [];
|
siblings: readonly ProjectTreeNode[],
|
||||||
|
index: number,
|
||||||
for (const node of nodes) {
|
): number => siblings.slice(0, index).filter((node) => node.kind === "folder").length;
|
||||||
if (node.kind !== "folder") {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
ids.push(node.id);
|
|
||||||
ids.push(...collectProjectFolderIds(node.children));
|
|
||||||
}
|
|
||||||
|
|
||||||
return ids;
|
|
||||||
};
|
|
||||||
|
|
||||||
const readPersistedFolders = (body: ProjectFoldersResponse): PersistedProjectFolderRecord[] =>
|
const readPersistedFolders = (body: ProjectFoldersResponse): PersistedProjectFolderRecord[] =>
|
||||||
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
||||||
|
|
||||||
const cloneProjectTreeNode = (node: ProjectTreeNode): ProjectTreeNode => {
|
const projectTreeAdapter: NavTreeAdapter<ProjectTreeNode> = {
|
||||||
if (node.kind === "project") {
|
getNodeId: getProjectTreeNodeId,
|
||||||
return {
|
isBranchNode: (node) => node.kind === "folder",
|
||||||
kind: "project",
|
getChildren: (node) => (node.kind === "folder" ? node.children : []),
|
||||||
item: { ...node.item },
|
withChildren: (node, children) =>
|
||||||
};
|
node.kind === "folder"
|
||||||
}
|
? {
|
||||||
|
|
||||||
return {
|
|
||||||
kind: "folder",
|
|
||||||
id: node.id,
|
|
||||||
label: node.label,
|
|
||||||
meta: node.meta,
|
|
||||||
children: node.children.map(cloneProjectTreeNode),
|
|
||||||
};
|
|
||||||
};
|
|
||||||
|
|
||||||
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,
|
...node,
|
||||||
children: result.nodes,
|
children: [...children],
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
}
|
: node,
|
||||||
|
|
||||||
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: {
|
const ProjectFolderDraftRow = (props: {
|
||||||
@@ -351,6 +193,11 @@ const ProjectFolderBranch = (props: {
|
|||||||
onPendingFolderNameChange: (value: string) => void;
|
onPendingFolderNameChange: (value: string) => void;
|
||||||
onSubmitPendingFolder: () => void;
|
onSubmitPendingFolder: () => void;
|
||||||
onCancelPendingFolder: () => void;
|
onCancelPendingFolder: () => void;
|
||||||
|
pendingFolderRename: PendingProjectFolderRename | null;
|
||||||
|
pendingFolderRenameName: string;
|
||||||
|
onPendingFolderRenameChange: (value: string) => void;
|
||||||
|
onSubmitPendingFolderRename: () => void;
|
||||||
|
onCancelPendingFolderRename: () => void;
|
||||||
dragState: ProjectDragState | null;
|
dragState: ProjectDragState | null;
|
||||||
isTreeClickSuppressed: () => boolean;
|
isTreeClickSuppressed: () => boolean;
|
||||||
}): JSX.Element => (
|
}): JSX.Element => (
|
||||||
@@ -375,9 +222,13 @@ const ProjectFolderBranch = (props: {
|
|||||||
|
|
||||||
if (node.kind === "folder") {
|
if (node.kind === "folder") {
|
||||||
const isCollapsed = (): boolean => props.isFolderCollapsed(node.id);
|
const isCollapsed = (): boolean => props.isFolderCollapsed(node.id);
|
||||||
|
const isRenaming = (): boolean => props.pendingFolderRename?.folderId === node.id;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
|
<Show
|
||||||
|
when={isRenaming()}
|
||||||
|
fallback={
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
classList={{
|
classList={{
|
||||||
@@ -420,6 +271,16 @@ const ProjectFolderBranch = (props: {
|
|||||||
<span class={styles.itemMeta}>{node.meta}</span>
|
<span class={styles.itemMeta}>{node.meta}</span>
|
||||||
</Show>
|
</Show>
|
||||||
</button>
|
</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)}>
|
<Show when={!isCollapsed() && ((node.children?.length ?? 0) > 0 || props.pendingFolderDraft?.parentId === node.id)}>
|
||||||
<ProjectFolderBranch
|
<ProjectFolderBranch
|
||||||
@@ -439,6 +300,11 @@ const ProjectFolderBranch = (props: {
|
|||||||
onPendingFolderNameChange={props.onPendingFolderNameChange}
|
onPendingFolderNameChange={props.onPendingFolderNameChange}
|
||||||
onSubmitPendingFolder={props.onSubmitPendingFolder}
|
onSubmitPendingFolder={props.onSubmitPendingFolder}
|
||||||
onCancelPendingFolder={props.onCancelPendingFolder}
|
onCancelPendingFolder={props.onCancelPendingFolder}
|
||||||
|
pendingFolderRename={props.pendingFolderRename}
|
||||||
|
pendingFolderRenameName={props.pendingFolderRenameName}
|
||||||
|
onPendingFolderRenameChange={props.onPendingFolderRenameChange}
|
||||||
|
onSubmitPendingFolderRename={props.onSubmitPendingFolderRename}
|
||||||
|
onCancelPendingFolderRename={props.onCancelPendingFolderRename}
|
||||||
dragState={props.dragState}
|
dragState={props.dragState}
|
||||||
isTreeClickSuppressed={props.isTreeClickSuppressed}
|
isTreeClickSuppressed={props.isTreeClickSuppressed}
|
||||||
/>
|
/>
|
||||||
@@ -509,6 +375,8 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
);
|
);
|
||||||
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingProjectFolderDraft | null>(null);
|
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingProjectFolderDraft | null>(null);
|
||||||
const [pendingFolderName, setPendingFolderName] = createSignal("");
|
const [pendingFolderName, setPendingFolderName] = createSignal("");
|
||||||
|
const [pendingFolderRename, setPendingFolderRename] = createSignal<PendingProjectFolderRename | null>(null);
|
||||||
|
const [pendingFolderRenameName, setPendingFolderRenameName] = createSignal("");
|
||||||
const [dragState, setDragState] = createSignal<ProjectDragState | null>(null);
|
const [dragState, setDragState] = createSignal<ProjectDragState | null>(null);
|
||||||
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
||||||
let rootRef: HTMLDivElement | undefined;
|
let rootRef: HTMLDivElement | undefined;
|
||||||
@@ -550,7 +418,7 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
|
|
||||||
const syncProjectTree = (): void => {
|
const syncProjectTree = (): void => {
|
||||||
const nextTree = buildProjectTree(appShellData.projectItems(), persistedFolders());
|
const nextTree = buildProjectTree(appShellData.projectItems(), persistedFolders());
|
||||||
const availableFolderIds = new Set(collectProjectFolderIds(nextTree));
|
const availableFolderIds = new Set(collectBranchNodeIds(nextTree, projectTreeAdapter));
|
||||||
|
|
||||||
setProjectTreeNodes(nextTree);
|
setProjectTreeNodes(nextTree);
|
||||||
setCollapsedFolderIds((current) => current.filter((folderId) => availableFolderIds.has(folderId)));
|
setCollapsedFolderIds((current) => current.filter((folderId) => availableFolderIds.has(folderId)));
|
||||||
@@ -560,10 +428,12 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
setCollapsedFolderIds([]);
|
setCollapsedFolderIds([]);
|
||||||
setPendingFolderDraft(null);
|
setPendingFolderDraft(null);
|
||||||
setPendingFolderName("");
|
setPendingFolderName("");
|
||||||
|
setPendingFolderRename(null);
|
||||||
|
setPendingFolderRenameName("");
|
||||||
setDragState(null);
|
setDragState(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
const folderIds = (): string[] => collectProjectFolderIds(projectTreeNodes());
|
const folderIds = (): string[] => collectBranchNodeIds(projectTreeNodes(), projectTreeAdapter);
|
||||||
|
|
||||||
const expandAllFolders = (): void => {
|
const expandAllFolders = (): void => {
|
||||||
setCollapsedFolderIds([]);
|
setCollapsedFolderIds([]);
|
||||||
@@ -599,6 +469,11 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!isUuidString(projectId)) {
|
||||||
|
setPersistedFolders([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||||
headers: {
|
headers: {
|
||||||
@@ -712,9 +587,49 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
suppressTreeClickTemporarily();
|
suppressTreeClickTemporarily();
|
||||||
setProjectTreeNodes((current) =>
|
|
||||||
moveProjectTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as ProjectDragTarget),
|
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 as ProjectDragTarget, 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;
|
||||||
|
// The preview tree includes project leaves and folders, but the backend only
|
||||||
|
// stores sibling order for folders. Persist a folder-only index so the server
|
||||||
|
// can reapply the same position against the authoritative ordered tree.
|
||||||
|
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 as ProjectDragTarget, projectTreeAdapter),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
setDragState(null);
|
setDragState(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -765,7 +680,7 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const selectProject = (projectId: string): void => {
|
const selectProject = (projectId: string): void => {
|
||||||
const location = findProjectNodeLocation(projectTreeNodes(), projectId);
|
const location = findTreeNodeLocation(projectTreeNodes(), projectId, projectTreeAdapter);
|
||||||
|
|
||||||
if (!location || location.node.kind !== "project") {
|
if (!location || location.node.kind !== "project") {
|
||||||
return;
|
return;
|
||||||
@@ -780,13 +695,28 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
|
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setPendingFolderRename(null);
|
||||||
|
setPendingFolderRenameName("");
|
||||||
setPendingFolderName("");
|
setPendingFolderName("");
|
||||||
setPendingFolderDraft({ parentId, depth });
|
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 submitPendingFolder = async (): Promise<void> => {
|
||||||
const name = pendingFolderName().trim();
|
const name = pendingFolderName().trim();
|
||||||
const draft = pendingFolderDraft();
|
const draft = pendingFolderDraft();
|
||||||
|
const projectId = selectedProject().id;
|
||||||
|
|
||||||
if (!draft) {
|
if (!draft) {
|
||||||
return;
|
return;
|
||||||
@@ -798,8 +728,19 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (!isUuidString(projectId)) {
|
||||||
|
cancelPendingFolder();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const parentFolderPath = draft.parentId ? resolveFolderPath(draft.parentId) : null;
|
||||||
|
if (draft.parentId && !parentFolderPath) {
|
||||||
|
cancelPendingFolder();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch(`${resolveAPIBase()}/projects/${selectedProject().id}/folders`, {
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
Accept: "application/json",
|
Accept: "application/json",
|
||||||
@@ -807,7 +748,7 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
},
|
},
|
||||||
body: JSON.stringify({
|
body: JSON.stringify({
|
||||||
name,
|
name,
|
||||||
parentFolderId: draft.parentId,
|
parentFolderId: parentFolderPath,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
|
|
||||||
@@ -825,29 +766,174 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
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 response = await fetch(
|
||||||
|
`${resolveAPIBase()}/projects/${projectId}/folders?folderId=${encodeURIComponent(folderPath)}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const body = (await response.json()) as ProjectFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to delete project folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedFolders(body));
|
||||||
|
setCollapsedFolderIds((current) => current.filter((id) => id !== folderId));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const 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 response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders/move`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
folderId: folderPath,
|
||||||
|
folderNodeId: folderStableId,
|
||||||
|
parentFolderId: parentFolderPath,
|
||||||
|
parentNodeId: parentStableId,
|
||||||
|
targetIndex,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as ProjectFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to move project folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
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 response = await fetch(`${resolveAPIBase()}/projects/${projectId}/folders`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
folderId: folderPath,
|
||||||
|
name,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as ProjectFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to rename project folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedFolders(body));
|
||||||
|
setPendingFolderRename(null);
|
||||||
|
setPendingFolderRenameName("");
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const cancelPendingFolder = (): void => {
|
const cancelPendingFolder = (): void => {
|
||||||
setPendingFolderDraft(null);
|
setPendingFolderDraft(null);
|
||||||
setPendingFolderName("");
|
setPendingFolderName("");
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleContextActionSelect = (action: { id: string; label: string }, target: ProjectMenuTarget): void => {
|
const cancelPendingFolderRename = (): void => {
|
||||||
if (action.id !== "new-folder") {
|
setPendingFolderRename(null);
|
||||||
return;
|
setPendingFolderRenameName("");
|
||||||
}
|
};
|
||||||
|
|
||||||
|
const handleContextActionSelect = (action: { id: string; label: string }, target: ProjectMenuTarget): void => {
|
||||||
|
switch (action.id) {
|
||||||
|
case "new-folder":
|
||||||
switch (target.kind) {
|
switch (target.kind) {
|
||||||
case "surface":
|
case "surface":
|
||||||
beginFolderDraft(null, 0);
|
beginFolderDraft(null, 0);
|
||||||
return;
|
return;
|
||||||
case "folder":
|
case "folder":
|
||||||
beginFolderDraft(target.id, (findProjectNodeDepth(projectTreeNodes(), target.id) ?? 0) + 1);
|
beginFolderDraft(target.id, (findTreeNodeDepth(projectTreeNodes(), target.id, projectTreeAdapter) ?? 0) + 1);
|
||||||
return;
|
return;
|
||||||
case "project": {
|
case "project": {
|
||||||
const parentId = findProjectNodeLocation(projectTreeNodes(), target.id)?.parentId ?? null;
|
const parentId = findTreeNodeLocation(projectTreeNodes(), target.id, projectTreeAdapter)?.parentId ?? null;
|
||||||
beginFolderDraft(parentId, parentId ? (findProjectNodeDepth(projectTreeNodes(), parentId) ?? 0) + 1 : 0);
|
beginFolderDraft(parentId, parentId ? (findTreeNodeDepth(projectTreeNodes(), parentId, projectTreeAdapter) ?? 0) + 1 : 0);
|
||||||
return;
|
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 => {
|
const handleSurfaceContextMenu = (event: MouseEvent): void => {
|
||||||
@@ -886,50 +972,20 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const currentTarget = event.currentTarget;
|
const relativeY = getPointerRelativeY(event);
|
||||||
if (!(currentTarget instanceof HTMLElement)) {
|
if (relativeY === null) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bounds = 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({
|
setDragState({
|
||||||
...nextDragState,
|
...nextDragState,
|
||||||
dropTarget: nextTarget,
|
dropTarget: resolveTreeDropTarget({
|
||||||
|
parentId,
|
||||||
|
index,
|
||||||
|
node,
|
||||||
|
relativeY,
|
||||||
|
adapter: projectTreeAdapter,
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -1047,6 +1103,11 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
|||||||
onPendingFolderNameChange={setPendingFolderName}
|
onPendingFolderNameChange={setPendingFolderName}
|
||||||
onSubmitPendingFolder={submitPendingFolder}
|
onSubmitPendingFolder={submitPendingFolder}
|
||||||
onCancelPendingFolder={cancelPendingFolder}
|
onCancelPendingFolder={cancelPendingFolder}
|
||||||
|
pendingFolderRename={pendingFolderRename()}
|
||||||
|
pendingFolderRenameName={pendingFolderRenameName()}
|
||||||
|
onPendingFolderRenameChange={setPendingFolderRenameName}
|
||||||
|
onSubmitPendingFolderRename={submitPendingFolderRename}
|
||||||
|
onCancelPendingFolderRename={cancelPendingFolderRename}
|
||||||
dragState={dragState()}
|
dragState={dragState()}
|
||||||
isTreeClickSuppressed={suppressNextTreeClick}
|
isTreeClickSuppressed={suppressNextTreeClick}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -1,3 +1,5 @@
|
|||||||
|
@use "../shared/tree-nav" as treeNav;
|
||||||
|
|
||||||
.sidebar {
|
.sidebar {
|
||||||
--sidebar-nav-item-min-height: var(--control-size-lg);
|
--sidebar-nav-item-min-height: var(--control-size-lg);
|
||||||
position: relative;
|
position: relative;
|
||||||
@@ -117,56 +119,25 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.treeSectionLabel {
|
.treeSectionLabel {
|
||||||
@include text-caption;
|
@include treeNav.section-label;
|
||||||
margin: var(--space-3) 0 var(--space-2);
|
margin: var(--space-3) 0 var(--space-2);
|
||||||
padding: 0 var(--space-3);
|
padding: 0 var(--space-3);
|
||||||
color: var(--color-text-subtle);
|
|
||||||
text-transform: uppercase;
|
|
||||||
letter-spacing: 0.04em;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeList {
|
.treeList {
|
||||||
list-style: none;
|
@include treeNav.tree-list;
|
||||||
display: grid;
|
|
||||||
gap: var(--space-1);
|
|
||||||
padding: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeEmptySlot {
|
.treeEmptySlot {
|
||||||
min-height: calc(var(--control-size-lg) - var(--space-2));
|
@include treeNav.empty-slot;
|
||||||
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 {
|
.treeInputRow {
|
||||||
width: 100%;
|
@include treeNav.input-row;
|
||||||
min-width: 0;
|
|
||||||
display: grid;
|
|
||||||
grid-template-columns: auto minmax(0, 1fr);
|
|
||||||
align-items: center;
|
|
||||||
gap: var(--space-2);
|
|
||||||
min-height: calc(var(--control-size-lg) - var(--space-2));
|
|
||||||
padding: var(--space-2) var(--space-3);
|
|
||||||
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
|
||||||
border: 1px solid color-mix(in srgb, var(--color-border) 42%, transparent);
|
|
||||||
border-radius: var(--radius-lg);
|
|
||||||
background: color-mix(in srgb, var(--color-surface) 94%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeInput {
|
.treeInput {
|
||||||
width: 100%;
|
@include treeNav.input;
|
||||||
min-width: 0;
|
|
||||||
border: 0;
|
|
||||||
background: transparent;
|
|
||||||
color: var(--color-text);
|
|
||||||
font: inherit;
|
|
||||||
outline: none;
|
|
||||||
}
|
|
||||||
|
|
||||||
.treeInput::placeholder {
|
|
||||||
color: var(--color-text-muted);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.navItem {
|
.navItem {
|
||||||
@@ -184,74 +155,44 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.treeItem {
|
.treeItem {
|
||||||
width: 100%;
|
@include treeNav.item;
|
||||||
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);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItem:hover,
|
.treeItem:hover,
|
||||||
.treeItem:focus-visible {
|
.treeItem:focus-visible {
|
||||||
background: color-mix(in srgb, var(--color-surface-hover) 80%, var(--color-accent-soft) 20%);
|
@include treeNav.item-hover;
|
||||||
color: var(--color-text);
|
|
||||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemFolder {
|
.treeItemFolder {
|
||||||
color: var(--color-text);
|
@include treeNav.item-folder;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemDragging {
|
.treeItemDragging {
|
||||||
opacity: 0.45;
|
@include treeNav.item-dragging;
|
||||||
transform: scale(0.985);
|
|
||||||
box-shadow: none;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemDropBefore {
|
.treeItemDropBefore {
|
||||||
box-shadow: inset 0 2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
@include treeNav.item-drop-before;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemDropAfter {
|
.treeItemDropAfter {
|
||||||
box-shadow: inset 0 -2px 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
@include treeNav.item-drop-after;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemDropInside {
|
.treeItemDropInside {
|
||||||
border-color: color-mix(in srgb, var(--color-accent-strong) 55%, transparent);
|
@include treeNav.item-drop-inside;
|
||||||
background: color-mix(in srgb, var(--color-accent-soft) 36%, var(--color-surface));
|
|
||||||
color: var(--color-text);
|
|
||||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.folderChevron {
|
.folderChevron {
|
||||||
color: var(--color-text-muted);
|
@include treeNav.folder-chevron;
|
||||||
transition: transform 160ms var(--easing-standard);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.folderChevronOpen {
|
.folderChevronOpen {
|
||||||
transform: rotate(90deg);
|
@include treeNav.folder-chevron-open;
|
||||||
}
|
}
|
||||||
|
|
||||||
.treeItemActive {
|
.treeItemActive {
|
||||||
border-color: var(--color-border);
|
@include treeNav.item-active;
|
||||||
background: var(--color-surface);
|
|
||||||
color: var(--color-text);
|
|
||||||
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.navItemActive {
|
.navItemActive {
|
||||||
@@ -262,18 +203,15 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.icon {
|
.icon {
|
||||||
color: inherit;
|
@include treeNav.icon;
|
||||||
opacity: 0.85;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.label {
|
.label {
|
||||||
@include text-label;
|
@include treeNav.label;
|
||||||
min-width: 0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.itemMeta {
|
.itemMeta {
|
||||||
@include text-caption;
|
@include treeNav.item-meta;
|
||||||
color: var(--color-text-muted);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.sidebarCollapsed {
|
.sidebarCollapsed {
|
||||||
|
|||||||
@@ -1,9 +1,21 @@
|
|||||||
// Path: Frontend/src/components/shell/WorkspaceSidebar/WorkspaceSidebar.tsx
|
// Path: Frontend/src/components/shell/WorkspaceSidebar/WorkspaceSidebar.tsx
|
||||||
|
|
||||||
import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
||||||
import { ChevronLeft, ChevronRight, Folder } from "../../../lib/icons";
|
import { resolveAPIBase } from "../../../lib/api";
|
||||||
|
import { ChevronLeft, ChevronRight, Folder, ListCollapse, UnfoldVertical } from "../../../lib/icons";
|
||||||
import { useAppShellData } from "../data/app-shell.context";
|
import { useAppShellData } from "../data/app-shell.context";
|
||||||
import { ProjectSelector } from "../ProjectSelector/ProjectSelector";
|
import { ProjectSelector } from "../ProjectSelector/ProjectSelector";
|
||||||
|
import {
|
||||||
|
collectBranchNodeIds,
|
||||||
|
findTreeNodeDepth,
|
||||||
|
findTreeNodeLocation,
|
||||||
|
getPointerRelativeY,
|
||||||
|
isUuidString,
|
||||||
|
moveTreeNode,
|
||||||
|
resolveTreeDropTarget,
|
||||||
|
type NavTreeAdapter,
|
||||||
|
type NavTreeDropTarget,
|
||||||
|
} from "../shared/navTreeDnd";
|
||||||
import {
|
import {
|
||||||
createWorkspaceStaticTarget,
|
createWorkspaceStaticTarget,
|
||||||
createWorkspaceSurfaceTarget,
|
createWorkspaceSurfaceTarget,
|
||||||
@@ -31,217 +43,72 @@ type PendingWorkspaceFolderDraft = {
|
|||||||
depth: number;
|
depth: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
type WorkspaceDragTarget = {
|
type WorkspaceDragTarget = NavTreeDropTarget;
|
||||||
parentId: string | null;
|
|
||||||
index: number;
|
|
||||||
intent: "before" | "after" | "inside";
|
|
||||||
targetNodeId?: string;
|
|
||||||
};
|
|
||||||
|
|
||||||
type WorkspaceDragState = {
|
type WorkspaceDragState = {
|
||||||
draggedNodeId: string;
|
draggedNodeId: string;
|
||||||
dropTarget: WorkspaceDragTarget | null;
|
dropTarget: WorkspaceDragTarget | null;
|
||||||
};
|
};
|
||||||
|
|
||||||
type WorkspaceNodeLocation = {
|
type PersistedWorkspaceFolderRecord = {
|
||||||
parentId: string | null;
|
id: string;
|
||||||
index: number;
|
path: string;
|
||||||
node: WorkspaceTreeNode;
|
label: string;
|
||||||
|
children?: PersistedWorkspaceFolderRecord[];
|
||||||
|
};
|
||||||
|
|
||||||
|
type WorkspaceFoldersResponse = {
|
||||||
|
data?: {
|
||||||
|
folders?: PersistedWorkspaceFolderRecord[];
|
||||||
|
renamedFolder?: PersistedWorkspaceFolderRecord;
|
||||||
|
movedFolder?: PersistedWorkspaceFolderRecord;
|
||||||
|
previousFolderId?: string;
|
||||||
|
previousFolderPath?: string;
|
||||||
|
};
|
||||||
|
error?: string;
|
||||||
|
message?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
type PendingWorkspaceFolderRename = {
|
||||||
|
folderId: string;
|
||||||
|
depth: number;
|
||||||
};
|
};
|
||||||
|
|
||||||
const LONG_PRESS_MS = 320;
|
const LONG_PRESS_MS = 320;
|
||||||
|
|
||||||
const createWorkspaceFolderId = (): string => `folder-${Math.random().toString(36).slice(2, 10)}`;
|
|
||||||
|
|
||||||
const getWorkspaceTreeNodeId = (node: WorkspaceTreeNode): string => node.id;
|
const getWorkspaceTreeNodeId = (node: WorkspaceTreeNode): string => node.id;
|
||||||
|
|
||||||
const insertWorkspaceFolderNode = (
|
const buildPersistedWorkspaceFolderNodes = (
|
||||||
nodes: readonly WorkspaceTreeNode[],
|
folders: readonly PersistedWorkspaceFolderRecord[],
|
||||||
parentId: string | null,
|
): WorkspaceTreeNode[] =>
|
||||||
folder: WorkspaceTreeNode,
|
folders.map((folder) => ({
|
||||||
): readonly WorkspaceTreeNode[] => {
|
id: folder.id,
|
||||||
if (parentId === null) {
|
path: folder.path,
|
||||||
return [...nodes, folder];
|
label: folder.label,
|
||||||
}
|
kind: "folder",
|
||||||
|
icon: Folder,
|
||||||
|
children: buildPersistedWorkspaceFolderNodes(folder.children ?? []),
|
||||||
|
}));
|
||||||
|
|
||||||
return nodes.map((node) => {
|
const readPersistedWorkspaceFolders = (body: WorkspaceFoldersResponse): PersistedWorkspaceFolderRecord[] =>
|
||||||
if (node.kind !== "folder") {
|
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
||||||
return node;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (node.id === parentId) {
|
const countWorkspaceFolderSiblingsBeforeIndex = (
|
||||||
return {
|
siblings: readonly WorkspaceTreeNode[],
|
||||||
...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,
|
index: number,
|
||||||
nodeToInsert: WorkspaceTreeNode,
|
): number => siblings.slice(0, index).filter((node) => node.kind === "folder").length;
|
||||||
): 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) => {
|
const workspaceTreeAdapter: NavTreeAdapter<WorkspaceTreeNode> = {
|
||||||
if (node.kind !== "folder") {
|
getNodeId: getWorkspaceTreeNodeId,
|
||||||
return node;
|
isBranchNode: (node) => node.kind === "folder",
|
||||||
}
|
getChildren: (node) => (node.kind === "folder" ? (node.children ?? []) : []),
|
||||||
|
withChildren: (node, children) =>
|
||||||
if (node.id === parentId) {
|
node.kind === "folder"
|
||||||
const nextChildren = [...(node.children ?? [])];
|
? {
|
||||||
nextChildren.splice(Math.max(0, Math.min(index, nextChildren.length)), 0, nodeToInsert);
|
|
||||||
return {
|
|
||||||
...node,
|
...node,
|
||||||
children: nextChildren,
|
children: [...children],
|
||||||
};
|
|
||||||
}
|
}
|
||||||
|
: node,
|
||||||
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: {
|
const FolderDraftRow = (props: {
|
||||||
@@ -292,10 +159,6 @@ const WorkspaceHomeEntry = (props: {
|
|||||||
item: WorkspaceStaticItem;
|
item: WorkspaceStaticItem;
|
||||||
onOpenContextMenu: (event: MouseEvent, target: WorkspaceContextMenuTarget) => void;
|
onOpenContextMenu: (event: MouseEvent, target: WorkspaceContextMenuTarget) => void;
|
||||||
onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void;
|
onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void;
|
||||||
onNodePointerDown: (event: PointerEvent, nodeId: string) => void;
|
|
||||||
onNodePointerMove: (event: PointerEvent, parentId: string | null, index: number, node: WorkspaceTreeNode) => void;
|
|
||||||
dragState: WorkspaceDragState | null;
|
|
||||||
isTreeClickSuppressed: () => boolean;
|
|
||||||
}): JSX.Element => {
|
}): JSX.Element => {
|
||||||
const Icon = props.item.icon;
|
const Icon = props.item.icon;
|
||||||
const target = createWorkspaceStaticTarget(props.item);
|
const target = createWorkspaceStaticTarget(props.item);
|
||||||
@@ -348,8 +211,17 @@ const WorkspaceTreeBranch = (props: {
|
|||||||
onPendingFolderNameChange: (value: string) => void;
|
onPendingFolderNameChange: (value: string) => void;
|
||||||
onSubmitPendingFolder: () => void;
|
onSubmitPendingFolder: () => void;
|
||||||
onCancelPendingFolder: () => void;
|
onCancelPendingFolder: () => void;
|
||||||
|
pendingFolderRename: PendingWorkspaceFolderRename | null;
|
||||||
|
pendingFolderRenameName: string;
|
||||||
|
onPendingFolderRenameChange: (value: string) => void;
|
||||||
|
onSubmitPendingFolderRename: () => void;
|
||||||
|
onCancelPendingFolderRename: () => void;
|
||||||
onOpenContextMenu: (event: MouseEvent, target: WorkspaceContextMenuTarget) => void;
|
onOpenContextMenu: (event: MouseEvent, target: WorkspaceContextMenuTarget) => void;
|
||||||
onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void;
|
onOpenContextMenuFromKeyboard: (element: HTMLElement, target: WorkspaceContextMenuTarget) => void;
|
||||||
|
onNodePointerDown: (event: PointerEvent, nodeId: string) => void;
|
||||||
|
onNodePointerMove: (event: PointerEvent, parentId: string | null, index: number, node: WorkspaceTreeNode) => void;
|
||||||
|
dragState: WorkspaceDragState | null;
|
||||||
|
isTreeClickSuppressed: () => boolean;
|
||||||
}): JSX.Element => {
|
}): JSX.Element => {
|
||||||
const depth = () => props.depth ?? 0;
|
const depth = () => props.depth ?? 0;
|
||||||
const parentId = () => props.parentId ?? null;
|
const parentId = () => props.parentId ?? null;
|
||||||
@@ -366,6 +238,7 @@ const WorkspaceTreeBranch = (props: {
|
|||||||
const Icon = getWorkspaceNodeIcon(node);
|
const Icon = getWorkspaceNodeIcon(node);
|
||||||
const target = createWorkspaceTreeTarget(node);
|
const target = createWorkspaceTreeTarget(node);
|
||||||
const isCollapsed = (): boolean => (node.kind === "folder" ? props.isFolderCollapsed(node.id) : false);
|
const isCollapsed = (): boolean => (node.kind === "folder" ? props.isFolderCollapsed(node.id) : false);
|
||||||
|
const isRenaming = (): boolean => props.pendingFolderRename?.folderId === node.id;
|
||||||
const isDraggedNode = (): boolean => props.dragState?.draggedNodeId === node.id;
|
const isDraggedNode = (): boolean => props.dragState?.draggedNodeId === node.id;
|
||||||
const dropIntent = (): WorkspaceDragTarget["intent"] | null => {
|
const dropIntent = (): WorkspaceDragTarget["intent"] | null => {
|
||||||
if (props.dragState?.dropTarget?.targetNodeId !== node.id) {
|
if (props.dragState?.dropTarget?.targetNodeId !== node.id) {
|
||||||
@@ -377,6 +250,9 @@ const WorkspaceTreeBranch = (props: {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<li>
|
<li>
|
||||||
|
<Show
|
||||||
|
when={node.kind === "folder" && isRenaming()}
|
||||||
|
fallback={
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
classList={{
|
classList={{
|
||||||
@@ -444,6 +320,16 @@ const WorkspaceTreeBranch = (props: {
|
|||||||
<span class={styles.itemMeta}>{node.meta}</span>
|
<span class={styles.itemMeta}>{node.meta}</span>
|
||||||
</Show>
|
</Show>
|
||||||
</button>
|
</button>
|
||||||
|
}
|
||||||
|
>
|
||||||
|
<FolderDraftRow
|
||||||
|
depth={props.pendingFolderRename?.depth ?? depth()}
|
||||||
|
value={props.pendingFolderRenameName}
|
||||||
|
onInput={props.onPendingFolderRenameChange}
|
||||||
|
onSubmit={props.onSubmitPendingFolderRename}
|
||||||
|
onCancel={props.onCancelPendingFolderRename}
|
||||||
|
/>
|
||||||
|
</Show>
|
||||||
|
|
||||||
<Show when={node.kind === "folder" && !isCollapsed() && (((node.children?.length ?? 0) > 0) || props.pendingFolderDraft?.parentId === node.id)}>
|
<Show when={node.kind === "folder" && !isCollapsed() && (((node.children?.length ?? 0) > 0) || props.pendingFolderDraft?.parentId === node.id)}>
|
||||||
<WorkspaceTreeBranch
|
<WorkspaceTreeBranch
|
||||||
@@ -457,6 +343,11 @@ const WorkspaceTreeBranch = (props: {
|
|||||||
onPendingFolderNameChange={props.onPendingFolderNameChange}
|
onPendingFolderNameChange={props.onPendingFolderNameChange}
|
||||||
onSubmitPendingFolder={props.onSubmitPendingFolder}
|
onSubmitPendingFolder={props.onSubmitPendingFolder}
|
||||||
onCancelPendingFolder={props.onCancelPendingFolder}
|
onCancelPendingFolder={props.onCancelPendingFolder}
|
||||||
|
pendingFolderRename={props.pendingFolderRename}
|
||||||
|
pendingFolderRenameName={props.pendingFolderRenameName}
|
||||||
|
onPendingFolderRenameChange={props.onPendingFolderRenameChange}
|
||||||
|
onSubmitPendingFolderRename={props.onSubmitPendingFolderRename}
|
||||||
|
onCancelPendingFolderRename={props.onCancelPendingFolderRename}
|
||||||
onOpenContextMenu={props.onOpenContextMenu}
|
onOpenContextMenu={props.onOpenContextMenu}
|
||||||
onOpenContextMenuFromKeyboard={props.onOpenContextMenuFromKeyboard}
|
onOpenContextMenuFromKeyboard={props.onOpenContextMenuFromKeyboard}
|
||||||
onNodePointerDown={props.onNodePointerDown}
|
onNodePointerDown={props.onNodePointerDown}
|
||||||
@@ -485,24 +376,109 @@ const WorkspaceTreeBranch = (props: {
|
|||||||
|
|
||||||
export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||||
const appShellData = useAppShellData();
|
const appShellData = useAppShellData();
|
||||||
|
const activeProject = () => appShellData.activeProject();
|
||||||
const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false);
|
const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false);
|
||||||
const [workspaceTreeNodes, setWorkspaceTreeNodes] = createSignal<readonly WorkspaceTreeNode[]>(appShellData.workspaceTree());
|
const [workspaceTreeNodes, setWorkspaceTreeNodes] = createSignal<readonly WorkspaceTreeNode[]>(appShellData.workspaceTree());
|
||||||
|
const [persistedFolders, setPersistedFolders] = createSignal<readonly PersistedWorkspaceFolderRecord[]>([]);
|
||||||
const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]);
|
const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]);
|
||||||
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingWorkspaceFolderDraft | null>(null);
|
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingWorkspaceFolderDraft | null>(null);
|
||||||
const [pendingFolderName, setPendingFolderName] = createSignal("");
|
const [pendingFolderName, setPendingFolderName] = createSignal("");
|
||||||
|
const [pendingFolderRename, setPendingFolderRename] = createSignal<PendingWorkspaceFolderRename | null>(null);
|
||||||
|
const [pendingFolderRenameName, setPendingFolderRenameName] = createSignal("");
|
||||||
const [dragState, setDragState] = createSignal<WorkspaceDragState | null>(null);
|
const [dragState, setDragState] = createSignal<WorkspaceDragState | null>(null);
|
||||||
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
||||||
|
let lastSelectedProjectId: string | null = null;
|
||||||
|
let latestPersistedFoldersRequest = 0;
|
||||||
const contextMenu = createWorkspaceContextMenuController();
|
const contextMenu = createWorkspaceContextMenuController();
|
||||||
let longPressTimer: number | undefined;
|
let longPressTimer: number | undefined;
|
||||||
let suppressClickTimer: number | undefined;
|
let suppressClickTimer: number | undefined;
|
||||||
const railToggleLabel = (): string => (props.railCollapsed ? "Expand server rail" : "Collapse server rail");
|
const railToggleLabel = (): string => (props.railCollapsed ? "Expand server rail" : "Collapse server rail");
|
||||||
const sidebarContextMenuTarget = createWorkspaceSurfaceTarget(appShellData.activeProject());
|
const sidebarContextMenuTarget = createWorkspaceSurfaceTarget(appShellData.activeProject());
|
||||||
const isFolderCollapsed = (folderId: string): boolean => collapsedFolderIds().includes(folderId);
|
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 => {
|
const toggleFolder = (folderId: string): void => {
|
||||||
setCollapsedFolderIds((current) =>
|
setCollapsedFolderIds((current) =>
|
||||||
current.includes(folderId) ? current.filter((id) => id !== folderId) : [...current, folderId],
|
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 syncWorkspaceTree = (): void => {
|
||||||
|
const nextTree = activeProject()?.id
|
||||||
|
? buildPersistedWorkspaceFolderNodes(persistedFolders())
|
||||||
|
: appShellData.workspaceTree();
|
||||||
|
const availableFolderIds = new Set(collectBranchNodeIds(nextTree, workspaceTreeAdapter));
|
||||||
|
|
||||||
|
setWorkspaceTreeNodes(nextTree);
|
||||||
|
setCollapsedFolderIds((current) => current.filter((id) => availableFolderIds.has(id)));
|
||||||
|
};
|
||||||
|
const loadPersistedFolders = async (projectId: string): Promise<void> => {
|
||||||
|
const requestId = latestPersistedFoldersRequest + 1;
|
||||||
|
latestPersistedFoldersRequest = requestId;
|
||||||
|
|
||||||
|
if (!projectId) {
|
||||||
|
setPersistedFolders([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isUuidString(projectId)) {
|
||||||
|
setPersistedFolders([]);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (requestId !== latestPersistedFoldersRequest) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to load project tree folders.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
|
} catch (error) {
|
||||||
|
if (requestId !== latestPersistedFoldersRequest) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.error(error);
|
||||||
|
setPersistedFolders([]);
|
||||||
|
}
|
||||||
|
};
|
||||||
const clearLongPressTimer = (): void => {
|
const clearLongPressTimer = (): void => {
|
||||||
if (longPressTimer !== undefined) {
|
if (longPressTimer !== undefined) {
|
||||||
window.clearTimeout(longPressTimer);
|
window.clearTimeout(longPressTimer);
|
||||||
@@ -523,11 +499,27 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
createEffect(() => {
|
createEffect(() => {
|
||||||
setWorkspaceTreeNodes(appShellData.workspaceTree());
|
syncWorkspaceTree();
|
||||||
setCollapsedFolderIds([]);
|
});
|
||||||
setPendingFolderDraft(null);
|
|
||||||
setPendingFolderName("");
|
createEffect(() => {
|
||||||
setDragState(null);
|
const projectId = activeProject()?.id ?? null;
|
||||||
|
|
||||||
|
if (lastSelectedProjectId === null) {
|
||||||
|
lastSelectedProjectId = projectId;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (projectId === lastSelectedProjectId) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
lastSelectedProjectId = projectId;
|
||||||
|
resetWorkspaceTreeInteractionState();
|
||||||
|
});
|
||||||
|
|
||||||
|
createEffect(() => {
|
||||||
|
void loadPersistedFolders(activeProject()?.id ?? "");
|
||||||
});
|
});
|
||||||
|
|
||||||
onMount(() => {
|
onMount(() => {
|
||||||
@@ -545,9 +537,48 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
}
|
}
|
||||||
|
|
||||||
suppressTreeClickTemporarily();
|
suppressTreeClickTemporarily();
|
||||||
setWorkspaceTreeNodes((current) =>
|
|
||||||
moveWorkspaceTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget),
|
const currentNodes = workspaceTreeNodes();
|
||||||
|
const draggedLocation = findTreeNodeLocation(currentNodes, nextDragState.draggedNodeId, workspaceTreeAdapter);
|
||||||
|
const canPersistMove = isUuidString(activeProject()?.id ?? "");
|
||||||
|
const draggedFolderPath = draggedLocation?.node.kind === "folder" ? draggedLocation.node.path ?? null : null;
|
||||||
|
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 persistedParentFolderPath = persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.path ?? null : null;
|
||||||
|
const previewSiblings = previewLocation?.parentId
|
||||||
|
? persistedParentLocation?.node.kind === "folder"
|
||||||
|
? persistedParentLocation.node.children ?? []
|
||||||
|
: []
|
||||||
|
: previewNodes;
|
||||||
|
// The tree preview can include static/workspace items, but persisted ordering
|
||||||
|
// only applies to folder siblings. Convert the preview position into a folder-
|
||||||
|
// only index before sending it to the backend move endpoint.
|
||||||
|
const targetIndex = previewLocation
|
||||||
|
? countWorkspaceFolderSiblingsBeforeIndex(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 {
|
||||||
|
setWorkspaceTreeNodes((current) =>
|
||||||
|
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
setDragState(null);
|
setDragState(null);
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -583,13 +614,28 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
|
setCollapsedFolderIds((current) => current.filter((id) => id !== parentId));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setPendingFolderRename(null);
|
||||||
|
setPendingFolderRenameName("");
|
||||||
setPendingFolderName("");
|
setPendingFolderName("");
|
||||||
setPendingFolderDraft({ parentId, depth });
|
setPendingFolderDraft({ parentId, depth });
|
||||||
};
|
};
|
||||||
|
|
||||||
const submitPendingFolder = (): void => {
|
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(workspaceTreeNodes(), folderId, workspaceTreeAdapter);
|
||||||
|
return location?.node.kind === "folder" ? location.node.path ?? null : null;
|
||||||
|
};
|
||||||
|
|
||||||
|
const submitPendingFolder = async (): Promise<void> => {
|
||||||
const name = pendingFolderName().trim();
|
const name = pendingFolderName().trim();
|
||||||
const draft = pendingFolderDraft();
|
const draft = pendingFolderDraft();
|
||||||
|
const projectId = activeProject()?.id ?? "";
|
||||||
|
|
||||||
if (!draft) {
|
if (!draft) {
|
||||||
return;
|
return;
|
||||||
@@ -601,17 +647,169 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
setWorkspaceTreeNodes((current) =>
|
if (!projectId || !isUuidString(projectId)) {
|
||||||
insertWorkspaceFolderNode(current, draft.parentId, {
|
cancelPendingFolder();
|
||||||
id: createWorkspaceFolderId(),
|
return;
|
||||||
label: name,
|
}
|
||||||
kind: "folder",
|
|
||||||
icon: Folder,
|
const parentFolderPath = draft.parentId ? resolveFolderPath(draft.parentId) : null;
|
||||||
children: [],
|
if (draft.parentId && !parentFolderPath) {
|
||||||
|
cancelPendingFolder();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
name,
|
||||||
|
parentFolderId: parentFolderPath,
|
||||||
}),
|
}),
|
||||||
);
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to create project tree folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
setPendingFolderDraft(null);
|
setPendingFolderDraft(null);
|
||||||
setPendingFolderName("");
|
setPendingFolderName("");
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const deletePersistedFolder = async (folderId: string): Promise<void> => {
|
||||||
|
const projectId = activeProject()?.id ?? "";
|
||||||
|
const folderPath = resolveFolderPath(folderId);
|
||||||
|
if (!folderId || !projectId || !isUuidString(projectId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!folderPath) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(
|
||||||
|
`${resolveAPIBase()}/projects/${projectId}/tree/folders?folderId=${encodeURIComponent(folderPath)}`,
|
||||||
|
{
|
||||||
|
method: "DELETE",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to delete project tree folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
|
setCollapsedFolderIds((current) => current.filter((id) => id !== folderId));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const movePersistedFolder = async (
|
||||||
|
folderPath: string,
|
||||||
|
parentFolderPath: string | null,
|
||||||
|
folderStableId: string,
|
||||||
|
parentStableId: string | null,
|
||||||
|
targetIndex: number,
|
||||||
|
): Promise<void> => {
|
||||||
|
const projectId = activeProject()?.id ?? "";
|
||||||
|
if (!folderPath || !folderStableId || !projectId || !isUuidString(projectId)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders/move`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
folderId: folderPath,
|
||||||
|
folderNodeId: folderStableId,
|
||||||
|
parentFolderId: parentFolderPath,
|
||||||
|
parentNodeId: parentStableId,
|
||||||
|
targetIndex,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to move project tree folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/folders`, {
|
||||||
|
method: "PATCH",
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
body: JSON.stringify({
|
||||||
|
folderId: folderPath,
|
||||||
|
name,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const body = (await response.json()) as WorkspaceFoldersResponse;
|
||||||
|
|
||||||
|
if (!response.ok) {
|
||||||
|
throw new Error(body.message || "Failed to rename project tree folder.");
|
||||||
|
}
|
||||||
|
|
||||||
|
setPersistedFolders(readPersistedWorkspaceFolders(body));
|
||||||
|
setPendingFolderRename(null);
|
||||||
|
setPendingFolderRenameName("");
|
||||||
|
} catch (error) {
|
||||||
|
console.error(error);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const cancelPendingFolder = (): void => {
|
const cancelPendingFolder = (): void => {
|
||||||
@@ -619,6 +817,22 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
setPendingFolderName("");
|
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 handleNodePointerDown = (event: PointerEvent, nodeId: string): void => {
|
const handleNodePointerDown = (event: PointerEvent, nodeId: string): void => {
|
||||||
if (event.button !== 0 || pendingFolderDraft()) {
|
if (event.button !== 0 || pendingFolderDraft()) {
|
||||||
return;
|
return;
|
||||||
@@ -643,52 +857,52 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
const bounds = event.currentTarget.getBoundingClientRect();
|
const relativeY = getPointerRelativeY(event);
|
||||||
const relativeY = bounds.height <= 0 ? 0.5 : (event.clientY - bounds.top) / bounds.height;
|
if (relativeY === null) {
|
||||||
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
setDragState({
|
||||||
|
...nextDragState,
|
||||||
|
dropTarget: resolveTreeDropTarget({
|
||||||
|
parentId,
|
||||||
|
index,
|
||||||
|
node,
|
||||||
|
relativeY,
|
||||||
|
adapter: workspaceTreeAdapter,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleContextActionSelect = (action: WorkspaceContextMenuAction, target: WorkspaceContextMenuTarget): void => {
|
||||||
|
switch (action.id) {
|
||||||
|
case "new-folder":
|
||||||
switch (target.kind) {
|
switch (target.kind) {
|
||||||
case "workspace":
|
case "workspace":
|
||||||
case "home":
|
case "home":
|
||||||
beginFolderDraft(null, 0);
|
beginFolderDraft(null, 0);
|
||||||
return;
|
return;
|
||||||
case "folder":
|
case "folder":
|
||||||
beginFolderDraft(target.id, (findWorkspaceFolderDepth(workspaceTreeNodes(), target.id) ?? 0) + 1);
|
beginFolderDraft(target.id, (findTreeNodeDepth(workspaceTreeNodes(), target.id, workspaceTreeAdapter) ?? 0) + 1);
|
||||||
return;
|
return;
|
||||||
case "settings":
|
case "settings":
|
||||||
case "item":
|
case "item":
|
||||||
return;
|
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;
|
||||||
|
default:
|
||||||
|
return;
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -731,10 +945,28 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
|
|
||||||
<For each={workspaceSidebarHeaderActions}>
|
<For each={workspaceSidebarHeaderActions}>
|
||||||
{(action): JSX.Element => {
|
{(action): JSX.Element => {
|
||||||
const Icon = action.icon;
|
const label =
|
||||||
|
action.id === "toggle-workspace-folders"
|
||||||
|
? workspaceFolderToggleLabel()
|
||||||
|
: action.label;
|
||||||
|
const Icon =
|
||||||
|
action.id === "toggle-workspace-folders"
|
||||||
|
? areAllFoldersCollapsed()
|
||||||
|
? UnfoldVertical
|
||||||
|
: ListCollapse
|
||||||
|
: action.icon;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<button type="button" class={styles.headerActionButton} aria-label={action.label} title={action.label} data-slot="workspace-sidebar-header-action" data-action-id={action.id}>
|
<button
|
||||||
|
type="button"
|
||||||
|
class={styles.headerActionButton}
|
||||||
|
aria-label={label}
|
||||||
|
title={label}
|
||||||
|
data-slot="workspace-sidebar-header-action"
|
||||||
|
data-action-id={action.id}
|
||||||
|
disabled={action.id === "toggle-workspace-folders" && totalFolderCount() === 0}
|
||||||
|
onClick={(): void => handleHeaderActionClick(action.id)}
|
||||||
|
>
|
||||||
<Icon size={16} strokeWidth={2} />
|
<Icon size={16} strokeWidth={2} />
|
||||||
</button>
|
</button>
|
||||||
);
|
);
|
||||||
@@ -794,6 +1026,11 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
|||||||
onPendingFolderNameChange={setPendingFolderName}
|
onPendingFolderNameChange={setPendingFolderName}
|
||||||
onSubmitPendingFolder={submitPendingFolder}
|
onSubmitPendingFolder={submitPendingFolder}
|
||||||
onCancelPendingFolder={cancelPendingFolder}
|
onCancelPendingFolder={cancelPendingFolder}
|
||||||
|
pendingFolderRename={pendingFolderRename()}
|
||||||
|
pendingFolderRenameName={pendingFolderRenameName()}
|
||||||
|
onPendingFolderRenameChange={setPendingFolderRenameName}
|
||||||
|
onSubmitPendingFolderRename={submitPendingFolderRename}
|
||||||
|
onCancelPendingFolderRename={cancelPendingFolderRename}
|
||||||
onOpenContextMenu={contextMenu.openMenu}
|
onOpenContextMenu={contextMenu.openMenu}
|
||||||
onOpenContextMenuFromKeyboard={contextMenu.openMenuFromElement}
|
onOpenContextMenuFromKeyboard={contextMenu.openMenuFromElement}
|
||||||
onNodePointerDown={handleNodePointerDown}
|
onNodePointerDown={handleNodePointerDown}
|
||||||
|
|||||||
@@ -40,6 +40,8 @@ type AppShellInstallation = {
|
|||||||
protocol: string;
|
protocol: string;
|
||||||
host: string;
|
host: string;
|
||||||
isBootstrapped: boolean;
|
isBootstrapped: boolean;
|
||||||
|
materializationStatus: "not_started" | "pending" | "running" | "succeeded" | "failed" | string;
|
||||||
|
materializationError?: string;
|
||||||
};
|
};
|
||||||
|
|
||||||
type AppShellAdmin = {
|
type AppShellAdmin = {
|
||||||
@@ -101,8 +103,29 @@ type AppShellPayload = {
|
|||||||
workspaces: AppShellWorkspace[];
|
workspaces: AppShellWorkspace[];
|
||||||
};
|
};
|
||||||
|
|
||||||
|
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,
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const normalizeAppShellPayload = (payload: AppShellPayload | null | undefined): AppShellPayload => ({
|
const normalizeAppShellPayload = (payload: AppShellPayload | null | undefined): AppShellPayload => ({
|
||||||
installation: payload?.installation,
|
installation: normalizeInstallation(payload?.installation),
|
||||||
admin: payload?.admin,
|
admin: payload?.admin,
|
||||||
organizations: Array.isArray(payload?.organizations) ? payload.organizations : [],
|
organizations: Array.isArray(payload?.organizations) ? payload.organizations : [],
|
||||||
departments: Array.isArray(payload?.departments) ? payload.departments : [],
|
departments: Array.isArray(payload?.departments) ? payload.departments : [],
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import {
|
|||||||
Home,
|
Home,
|
||||||
Keyboard,
|
Keyboard,
|
||||||
LayoutGrid,
|
LayoutGrid,
|
||||||
|
ListCollapse,
|
||||||
LogOut,
|
LogOut,
|
||||||
Repeat,
|
Repeat,
|
||||||
Search,
|
Search,
|
||||||
@@ -128,6 +129,7 @@ export type WorkspaceStaticItem = SidebarItem & {
|
|||||||
|
|
||||||
export type WorkspaceFolderNode = {
|
export type WorkspaceFolderNode = {
|
||||||
id: string;
|
id: string;
|
||||||
|
path?: string;
|
||||||
label: string;
|
label: string;
|
||||||
kind: "folder";
|
kind: "folder";
|
||||||
icon: ShellIcon;
|
icon: ShellIcon;
|
||||||
@@ -476,6 +478,7 @@ export const workspaceTree: readonly WorkspaceTreeNode[] = [
|
|||||||
|
|
||||||
export const workspaceSidebarHeaderActions: readonly SidebarHeaderAction[] = [
|
export const workspaceSidebarHeaderActions: readonly SidebarHeaderAction[] = [
|
||||||
{ id: "search-workspace", label: "Search workspace", icon: Search },
|
{ id: "search-workspace", label: "Search workspace", icon: Search },
|
||||||
|
{ id: "toggle-workspace-folders", label: "Collapse all folders", icon: ListCollapse },
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
export const mobileBottomNavItems: readonly MobileBottomNavItem[] = [
|
export const mobileBottomNavItems: readonly MobileBottomNavItem[] = [
|
||||||
@@ -556,8 +559,6 @@ export const getWorkspaceContextMenuSections = (
|
|||||||
id: "organize",
|
id: "organize",
|
||||||
label: undefined,
|
label: undefined,
|
||||||
items: [
|
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" },
|
{ id: "delete-folder", label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -579,8 +580,6 @@ export const getWorkspaceContextMenuSections = (
|
|||||||
id: "organize",
|
id: "organize",
|
||||||
label: undefined,
|
label: undefined,
|
||||||
items: [
|
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" },
|
{ id: `delete-${actionPrefix}`, label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -595,6 +594,12 @@ const getProjectCreateActions = (): readonly ProjectContextMenuAction[] =>
|
|||||||
{ id: "new-folder", label: "New folder" },
|
{ id: "new-folder", label: "New folder" },
|
||||||
] as const;
|
] 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 => ({
|
export const createProjectSurfaceTarget = (label = "Projects"): ProjectMenuTarget => ({
|
||||||
id: "project-surface",
|
id: "project-surface",
|
||||||
label,
|
label,
|
||||||
@@ -641,6 +646,10 @@ export const getProjectContextMenuSections = (target: ProjectMenuTarget): readon
|
|||||||
id: "create",
|
id: "create",
|
||||||
items: createActions,
|
items: createActions,
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
id: "organize",
|
||||||
|
items: getProjectFolderDangerActions(),
|
||||||
|
},
|
||||||
] as const;
|
] as const;
|
||||||
case "project":
|
case "project":
|
||||||
return [
|
return [
|
||||||
|
|||||||
@@ -0,0 +1,188 @@
|
|||||||
|
@use "../../../styles/tools/mixins" as *;
|
||||||
|
|
||||||
|
@mixin section-label {
|
||||||
|
@include text-caption;
|
||||||
|
color: var(--color-text-subtle);
|
||||||
|
text-transform: uppercase;
|
||||||
|
letter-spacing: 0.04em;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin tree-list {
|
||||||
|
list-style: none;
|
||||||
|
display: grid;
|
||||||
|
gap: var(--space-1);
|
||||||
|
padding: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin empty-slot {
|
||||||
|
min-height: calc(var(--control-size-lg) - var(--space-2));
|
||||||
|
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
border: 1px dashed color-mix(in srgb, var(--color-border) 38%, transparent);
|
||||||
|
opacity: 0.35;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin input-row {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: auto minmax(0, 1fr);
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
min-height: calc(var(--control-size-lg) - var(--space-2));
|
||||||
|
padding: var(--space-2) var(--space-3);
|
||||||
|
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||||
|
border: 1px solid color-mix(in srgb, var(--color-border) 42%, transparent);
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
background: color-mix(in srgb, var(--color-surface) 94%, transparent);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin input {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
border: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--color-text);
|
||||||
|
font: inherit;
|
||||||
|
outline: none;
|
||||||
|
|
||||||
|
&::placeholder {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item {
|
||||||
|
width: 100%;
|
||||||
|
min-width: 0;
|
||||||
|
display: grid;
|
||||||
|
position: relative;
|
||||||
|
isolation: isolate;
|
||||||
|
grid-template-columns: auto auto minmax(0, 1fr) auto;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
min-height: calc(var(--control-size-lg) - var(--space-2));
|
||||||
|
padding: var(--space-2) var(--space-3);
|
||||||
|
padding-left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||||
|
border: 0;
|
||||||
|
border-radius: 0;
|
||||||
|
background: transparent;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
text-align: left;
|
||||||
|
transition:
|
||||||
|
color 160ms var(--easing-standard),
|
||||||
|
box-shadow 160ms var(--easing-standard),
|
||||||
|
transform 180ms var(--easing-standard);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
inset: 0;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: var(--radius-lg);
|
||||||
|
background: transparent;
|
||||||
|
transition:
|
||||||
|
background 160ms var(--easing-standard),
|
||||||
|
border-color 160ms var(--easing-standard),
|
||||||
|
box-shadow 160ms var(--easing-standard);
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
> * {
|
||||||
|
position: relative;
|
||||||
|
z-index: 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-hover {
|
||||||
|
color: var(--color-text);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
background: color-mix(in srgb, var(--color-surface-hover) 80%, var(--color-accent-soft) 20%);
|
||||||
|
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-folder {
|
||||||
|
color: var(--color-text);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-dragging {
|
||||||
|
opacity: 0.45;
|
||||||
|
transform: scale(0.985);
|
||||||
|
box-shadow: none;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-drop-before {
|
||||||
|
&::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||||
|
right: var(--space-3);
|
||||||
|
top: calc((var(--space-1) * -0.5) - 1px);
|
||||||
|
height: 2px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-drop-after {
|
||||||
|
&::before {
|
||||||
|
content: "";
|
||||||
|
position: absolute;
|
||||||
|
left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||||
|
right: var(--space-3);
|
||||||
|
bottom: calc((var(--space-1) * -0.5) - 1px);
|
||||||
|
height: 2px;
|
||||||
|
border-radius: 999px;
|
||||||
|
background: color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||||
|
pointer-events: none;
|
||||||
|
z-index: 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-drop-inside {
|
||||||
|
color: var(--color-text);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
border-color: color-mix(in srgb, var(--color-accent-strong) 55%, transparent);
|
||||||
|
background: color-mix(in srgb, var(--color-accent-soft) 36%, var(--color-surface));
|
||||||
|
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin folder-chevron {
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
transition: transform 160ms var(--easing-standard);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin folder-chevron-open {
|
||||||
|
transform: rotate(90deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-active {
|
||||||
|
color: var(--color-text);
|
||||||
|
|
||||||
|
&::after {
|
||||||
|
border-color: var(--color-border);
|
||||||
|
background: var(--color-surface);
|
||||||
|
box-shadow: inset 0 1px 0 color-mix(in srgb, white 4%, transparent);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin icon {
|
||||||
|
color: inherit;
|
||||||
|
opacity: 0.85;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin label {
|
||||||
|
@include text-label;
|
||||||
|
min-width: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
@mixin item-meta {
|
||||||
|
@include text-caption;
|
||||||
|
color: var(--color-text-muted);
|
||||||
|
}
|
||||||
@@ -0,0 +1,278 @@
|
|||||||
|
export type NavTreeDropIntent = "before" | "after" | "inside";
|
||||||
|
|
||||||
|
export type NavTreeDropTarget = {
|
||||||
|
parentId: string | null;
|
||||||
|
index: number;
|
||||||
|
intent: NavTreeDropIntent;
|
||||||
|
targetNodeId?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type NavTreeDragState = {
|
||||||
|
draggedNodeId: string;
|
||||||
|
dropTarget: NavTreeDropTarget | null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type NavTreeLocation<TNode> = {
|
||||||
|
parentId: string | null;
|
||||||
|
index: number;
|
||||||
|
node: TNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type NavTreeAdapter<TNode> = {
|
||||||
|
getNodeId: (node: TNode) => string;
|
||||||
|
isBranchNode: (node: TNode) => boolean;
|
||||||
|
getChildren: (node: TNode) => readonly TNode[];
|
||||||
|
withChildren: (node: TNode, children: readonly TNode[]) => TNode;
|
||||||
|
};
|
||||||
|
|
||||||
|
const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
|
||||||
|
|
||||||
|
export const isUuidString = (value: string | null | undefined): boolean => {
|
||||||
|
if (typeof value !== "string") {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
return UUID_PATTERN.test(value.trim());
|
||||||
|
};
|
||||||
|
|
||||||
|
export const collectBranchNodeIds = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): string[] => {
|
||||||
|
const ids: string[] = [];
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (!adapter.isBranchNode(node)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
ids.push(adapter.getNodeId(node));
|
||||||
|
ids.push(...collectBranchNodeIds(adapter.getChildren(node), adapter));
|
||||||
|
}
|
||||||
|
|
||||||
|
return ids;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const findTreeNodeLocation = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
nodeId: string,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
parentId: string | null = null,
|
||||||
|
): NavTreeLocation<TNode> | null => {
|
||||||
|
for (let index = 0; index < nodes.length; index += 1) {
|
||||||
|
const node = nodes[index];
|
||||||
|
|
||||||
|
if (adapter.getNodeId(node) === nodeId) {
|
||||||
|
return { parentId, index, node };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adapter.isBranchNode(node)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nestedLocation = findTreeNodeLocation(adapter.getChildren(node), nodeId, adapter, adapter.getNodeId(node));
|
||||||
|
if (nestedLocation) {
|
||||||
|
return nestedLocation;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const findTreeNodeDepth = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
nodeId: string,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
depth = 0,
|
||||||
|
): number | null => {
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (adapter.getNodeId(node) === nodeId) {
|
||||||
|
return depth;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!adapter.isBranchNode(node)) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const nestedDepth = findTreeNodeDepth(adapter.getChildren(node), nodeId, adapter, depth + 1);
|
||||||
|
if (nestedDepth !== null) {
|
||||||
|
return nestedDepth;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const treeContainsNode = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
nodeId: string,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): boolean => {
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (adapter.getNodeId(node) === nodeId) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (adapter.isBranchNode(node) && treeContainsNode(adapter.getChildren(node), nodeId, adapter)) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const removeTreeNode = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
nodeId: string,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): { nodes: TNode[]; removed: TNode | null } => {
|
||||||
|
const nextNodes: TNode[] = [];
|
||||||
|
let removed: TNode | null = null;
|
||||||
|
|
||||||
|
for (const node of nodes) {
|
||||||
|
if (adapter.getNodeId(node) === nodeId) {
|
||||||
|
removed = node;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (adapter.isBranchNode(node)) {
|
||||||
|
const result = removeTreeNode(adapter.getChildren(node), nodeId, adapter);
|
||||||
|
|
||||||
|
if (result.removed) {
|
||||||
|
removed = result.removed;
|
||||||
|
nextNodes.push(adapter.withChildren(node, result.nodes));
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nextNodes.push(node);
|
||||||
|
}
|
||||||
|
|
||||||
|
return { nodes: nextNodes, removed };
|
||||||
|
};
|
||||||
|
|
||||||
|
export const insertTreeNode = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
parentId: string | null,
|
||||||
|
index: number,
|
||||||
|
nodeToInsert: TNode,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): TNode[] => {
|
||||||
|
if (parentId === null) {
|
||||||
|
const nextNodes = [...nodes];
|
||||||
|
nextNodes.splice(Math.max(0, Math.min(index, nextNodes.length)), 0, nodeToInsert);
|
||||||
|
return nextNodes;
|
||||||
|
}
|
||||||
|
|
||||||
|
return nodes.map((node) => {
|
||||||
|
if (!adapter.isBranchNode(node)) {
|
||||||
|
return node;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (adapter.getNodeId(node) === parentId) {
|
||||||
|
const nextChildren = [...adapter.getChildren(node)];
|
||||||
|
nextChildren.splice(Math.max(0, Math.min(index, nextChildren.length)), 0, nodeToInsert);
|
||||||
|
return adapter.withChildren(node, nextChildren);
|
||||||
|
}
|
||||||
|
|
||||||
|
return adapter.withChildren(node, insertTreeNode(adapter.getChildren(node), parentId, index, nodeToInsert, adapter));
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
export const moveTreeNode = <TNode>(
|
||||||
|
nodes: readonly TNode[],
|
||||||
|
draggedNodeId: string,
|
||||||
|
dropTarget: NavTreeDropTarget,
|
||||||
|
adapter: NavTreeAdapter<TNode>,
|
||||||
|
): TNode[] => {
|
||||||
|
const location = findTreeNodeLocation(nodes, draggedNodeId, adapter);
|
||||||
|
|
||||||
|
if (!location) {
|
||||||
|
return [...nodes];
|
||||||
|
}
|
||||||
|
|
||||||
|
if (
|
||||||
|
adapter.isBranchNode(location.node) &&
|
||||||
|
dropTarget.parentId !== null &&
|
||||||
|
(treeContainsNode(adapter.getChildren(location.node), dropTarget.parentId, adapter) ||
|
||||||
|
dropTarget.parentId === adapter.getNodeId(location.node))
|
||||||
|
) {
|
||||||
|
return [...nodes];
|
||||||
|
}
|
||||||
|
|
||||||
|
let normalizedIndex = dropTarget.index;
|
||||||
|
if (dropTarget.parentId === location.parentId && dropTarget.index > location.index) {
|
||||||
|
normalizedIndex -= 1;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (dropTarget.parentId === location.parentId && normalizedIndex === location.index) {
|
||||||
|
return [...nodes];
|
||||||
|
}
|
||||||
|
|
||||||
|
const removalResult = removeTreeNode(nodes, draggedNodeId, adapter);
|
||||||
|
if (!removalResult.removed) {
|
||||||
|
return [...nodes];
|
||||||
|
}
|
||||||
|
|
||||||
|
return insertTreeNode(removalResult.nodes, dropTarget.parentId, normalizedIndex, removalResult.removed, adapter);
|
||||||
|
};
|
||||||
|
|
||||||
|
export const getPointerRelativeY = (event: PointerEvent): number | null => {
|
||||||
|
const currentTarget = event.currentTarget;
|
||||||
|
if (!(currentTarget instanceof HTMLElement)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const bounds = currentTarget.getBoundingClientRect();
|
||||||
|
return bounds.height <= 0 ? 0.5 : (event.clientY - bounds.top) / bounds.height;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const resolveTreeDropTarget = <TNode>(params: {
|
||||||
|
parentId: string | null;
|
||||||
|
index: number;
|
||||||
|
node: TNode;
|
||||||
|
relativeY: number;
|
||||||
|
adapter: NavTreeAdapter<TNode>;
|
||||||
|
beforeThreshold?: number;
|
||||||
|
beforeThresholdFirstSibling?: number;
|
||||||
|
afterThreshold?: number;
|
||||||
|
}): NavTreeDropTarget => {
|
||||||
|
const {
|
||||||
|
parentId,
|
||||||
|
index,
|
||||||
|
node,
|
||||||
|
relativeY,
|
||||||
|
adapter,
|
||||||
|
beforeThreshold = 0.28,
|
||||||
|
beforeThresholdFirstSibling = 0.42,
|
||||||
|
afterThreshold = 0.72,
|
||||||
|
} = params;
|
||||||
|
|
||||||
|
const targetNodeId = adapter.getNodeId(node);
|
||||||
|
|
||||||
|
if (adapter.isBranchNode(node)) {
|
||||||
|
const nextBeforeThreshold = index === 0 ? beforeThresholdFirstSibling : beforeThreshold;
|
||||||
|
|
||||||
|
if (relativeY < nextBeforeThreshold) {
|
||||||
|
return { parentId, index, intent: "before", targetNodeId };
|
||||||
|
}
|
||||||
|
|
||||||
|
if (relativeY > afterThreshold) {
|
||||||
|
return { parentId, index: index + 1, intent: "after", targetNodeId };
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
parentId: targetNodeId,
|
||||||
|
index: adapter.getChildren(node).length,
|
||||||
|
intent: "inside",
|
||||||
|
targetNodeId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
parentId,
|
||||||
|
index: relativeY < 0.5 ? index : index + 1,
|
||||||
|
intent: relativeY < 0.5 ? "before" : "after",
|
||||||
|
targetNodeId,
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -0,0 +1,173 @@
|
|||||||
|
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.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,542 @@
|
|||||||
|
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.hook.ts
|
||||||
|
|
||||||
|
import { createEffect, createMemo, createSignal, onCleanup } from "solid-js";
|
||||||
|
import { createStore } from "solid-js/store";
|
||||||
|
import { resolveAPIBase } from "../../../lib/api";
|
||||||
|
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 "./WorkspaceHome.data";
|
||||||
|
|
||||||
|
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;
|
||||||
|
|
||||||
|
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(", ")})`;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const useWorkspaceHomeWizard = (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 apiBase = (): string => resolveAPIBase();
|
||||||
|
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 {
|
||||||
|
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 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);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
};
|
||||||
@@ -1,3 +1,5 @@
|
|||||||
|
/* Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.module.scss */
|
||||||
|
|
||||||
.viewport,
|
.viewport,
|
||||||
.wizardLayer {
|
.wizardLayer {
|
||||||
--workspace-content-max-width: var(--content-width-wide);
|
--workspace-content-max-width: var(--content-width-wide);
|
||||||
@@ -92,6 +94,21 @@
|
|||||||
flex-wrap: wrap;
|
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 {
|
.title {
|
||||||
@include text-display;
|
@include text-display;
|
||||||
font-family: var(--font-family-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);
|
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"] {
|
.statusBadge[data-status="error"] {
|
||||||
color: var(--color-danger-text, var(--color-text));
|
color: var(--color-danger-text, var(--color-text));
|
||||||
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border)) 68%, transparent);
|
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border)) 68%, transparent);
|
||||||
@@ -240,11 +270,249 @@
|
|||||||
color: var(--color-text-muted);
|
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 {
|
.fieldHelp {
|
||||||
@include text-caption;
|
@include text-caption;
|
||||||
color: var(--color-text-muted);
|
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 input,
|
||||||
.field select {
|
.field select {
|
||||||
min-height: var(--control-size-md);
|
min-height: var(--control-size-md);
|
||||||
@@ -342,7 +610,7 @@
|
|||||||
.primaryButton:hover,
|
.primaryButton:hover,
|
||||||
.secondaryButton:hover,
|
.secondaryButton:hover,
|
||||||
.wizardCloseButton:hover,
|
.wizardCloseButton:hover,
|
||||||
.wizardStepButton:hover {
|
.wizardProgressStep:hover {
|
||||||
transform: translateY(-1px);
|
transform: translateY(-1px);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -417,72 +685,93 @@
|
|||||||
|
|
||||||
.wizardBody {
|
.wizardBody {
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: minmax(17rem, 20rem) minmax(0, 1fr);
|
|
||||||
gap: var(--space-4);
|
gap: var(--space-4);
|
||||||
min-height: 0;
|
min-height: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardSidebar {
|
.wizardProgress {
|
||||||
|
position: relative;
|
||||||
display: grid;
|
display: grid;
|
||||||
gap: var(--space-4);
|
|
||||||
align-content: start;
|
|
||||||
}
|
|
||||||
|
|
||||||
.wizardSidebarSection {
|
|
||||||
gap: var(--space-3);
|
gap: var(--space-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardSteps {
|
.wizardProgressTrack {
|
||||||
display: grid;
|
position: absolute;
|
||||||
gap: var(--space-2);
|
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 {
|
.wizardProgressFill {
|
||||||
width: 100%;
|
height: 100%;
|
||||||
display: grid;
|
border-radius: 999px;
|
||||||
grid-template-columns: auto minmax(0, 1fr);
|
background: color-mix(in srgb, var(--bootstrap-accent) 72%, white 8%);
|
||||||
|
transition: width 220ms var(--easing-standard);
|
||||||
|
}
|
||||||
|
|
||||||
|
.wizardProgressSteps {
|
||||||
|
display: flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
text-align: left;
|
justify-content: space-between;
|
||||||
padding: var(--space-2) var(--space-3);
|
gap: 0;
|
||||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
|
||||||
background: color-mix(in srgb, var(--color-surface-secondary) 84%, transparent);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardStepButton[data-active="true"] {
|
.wizardProgressStep {
|
||||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 42%, transparent);
|
position: relative;
|
||||||
background: color-mix(in srgb, var(--bootstrap-accent) 10%, var(--color-surface));
|
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 {
|
.wizardProgressStep:disabled {
|
||||||
opacity: 0.56;
|
|
||||||
cursor: not-allowed;
|
cursor: not-allowed;
|
||||||
transform: none;
|
transform: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardStepIndex {
|
.wizardProgressIndex {
|
||||||
width: calc(var(--control-size-md) - var(--space-2));
|
width: calc(var(--control-size-md) - var(--space-2));
|
||||||
height: calc(var(--control-size-md) - var(--space-2));
|
height: calc(var(--control-size-md) - var(--space-2));
|
||||||
display: inline-flex;
|
display: inline-flex;
|
||||||
align-items: center;
|
align-items: center;
|
||||||
justify-content: center;
|
justify-content: center;
|
||||||
border-radius: var(--radius-pill);
|
border-radius: 999px;
|
||||||
background: color-mix(in srgb, var(--color-surface) 80%, transparent);
|
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);
|
color: var(--color-text);
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardStepCopy {
|
.wizardProgressStep[data-active="true"] .wizardProgressIndex {
|
||||||
min-width: 0;
|
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bootstrap-accent) 14%, transparent);
|
||||||
display: grid;
|
|
||||||
gap: 0.125rem;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardStepCopy strong {
|
.wizardProgressStep:not(:disabled):hover .wizardProgressIndex,
|
||||||
@include text-label;
|
.wizardProgressStep:not(:disabled):focus-visible .wizardProgressIndex {
|
||||||
}
|
transform: translateY(-1px);
|
||||||
|
border-color: color-mix(in srgb, var(--bootstrap-accent) 36%, var(--color-border));
|
||||||
.wizardStepCopy small {
|
color: var(--color-text);
|
||||||
@include text-caption;
|
|
||||||
color: var(--color-text-muted);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardStepPanel {
|
.wizardStepPanel {
|
||||||
@@ -490,7 +779,116 @@
|
|||||||
gap: var(--space-3);
|
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) {
|
@include respond-down(tablet) {
|
||||||
|
.personaGrid {
|
||||||
|
grid-template-columns: 1fr;
|
||||||
|
}
|
||||||
|
|
||||||
.summaryGrid,
|
.summaryGrid,
|
||||||
.wizardBody {
|
.wizardBody {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
@@ -536,21 +934,20 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.wizardHeader,
|
.wizardHeader,
|
||||||
.wizardBody,
|
.wizardBody {
|
||||||
.wizardSidebar {
|
|
||||||
gap: var(--space-3);
|
gap: var(--space-3);
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardSteps {
|
.wizardProgressSteps {
|
||||||
grid-auto-flow: column;
|
justify-content: flex-start;
|
||||||
grid-auto-columns: minmax(10rem, 1fr);
|
gap: var(--space-8);
|
||||||
overflow-x: auto;
|
overflow-x: auto;
|
||||||
padding-bottom: var(--space-1);
|
padding-bottom: var(--space-1);
|
||||||
scrollbar-width: thin;
|
scrollbar-width: thin;
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardStepButton {
|
.wizardProgressStep {
|
||||||
min-width: 10rem;
|
min-width: calc(var(--control-size-md) - var(--space-2));
|
||||||
}
|
}
|
||||||
|
|
||||||
.wizardFormActions {
|
.wizardFormActions {
|
||||||
|
|||||||
@@ -0,0 +1,285 @@
|
|||||||
|
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 "./WorkspaceHome.data";
|
||||||
|
import styles from "./WorkspaceHome.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>
|
||||||
|
</>
|
||||||
|
);
|
||||||
@@ -1,145 +1,13 @@
|
|||||||
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.tsx
|
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.tsx
|
||||||
|
|
||||||
import { For, Show, createEffect, createMemo, createSignal, type JSX } from "solid-js";
|
import { Show, createMemo, type JSX } from "solid-js";
|
||||||
import { Portal } from "solid-js/web";
|
import { Portal } from "solid-js/web";
|
||||||
import { createStore } from "solid-js/store";
|
|
||||||
import { resolveAPIBase } from "../../../lib/api";
|
|
||||||
import { ChevronLeft, ChevronRight } from "../../../lib/icons";
|
import { ChevronLeft, ChevronRight } from "../../../lib/icons";
|
||||||
import { useAppShellData } from "../../shell/data/app-shell.context";
|
import { useAppShellData } from "../../shell/data/app-shell.context";
|
||||||
|
import { bootstrapPersonaDefinitions } from "./WorkspaceHome.data";
|
||||||
|
import { useWorkspaceHomeWizard } from "./WorkspaceHome.hook";
|
||||||
import styles from "./WorkspaceHome.module.scss";
|
import styles from "./WorkspaceHome.module.scss";
|
||||||
|
import { BootstrapAdminStep, BootstrapFinishingState, BootstrapInstanceStep, BootstrapModeStep, BootstrapPersonaStep, BootstrapStructureStep, BootstrapWizardProgress } from "./WorkspaceHome.parts";
|
||||||
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 = {
|
type WorkspaceHomeProps = {
|
||||||
sidebarCollapsed: boolean;
|
sidebarCollapsed: boolean;
|
||||||
@@ -148,206 +16,61 @@ type WorkspaceHomeProps = {
|
|||||||
|
|
||||||
export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
||||||
const appShellData = useAppShellData();
|
const appShellData = useAppShellData();
|
||||||
const [instanceForm, setInstanceForm] = createStore({ ...defaultInstanceForm });
|
const {
|
||||||
const [modeForm, setModeForm] = createStore({ ...defaultModeForm });
|
instanceForm,
|
||||||
const [adminForm, setAdminForm] = createStore({ ...defaultAdminForm });
|
setInstanceForm,
|
||||||
const [structureForm, setStructureForm] = createStore({ ...defaultStructureForm });
|
modeForm,
|
||||||
const [stepState, setStepState] = createStore<Record<BootstrapStepKey, BootstrapSubmissionState>>({
|
setModeForm,
|
||||||
instance: initialSubmissionState(),
|
adminForm,
|
||||||
mode: initialSubmissionState(),
|
setAdminForm,
|
||||||
admin: initialSubmissionState(),
|
structureForm,
|
||||||
structure: initialSubmissionState(),
|
setStructureForm,
|
||||||
});
|
selectedPersona,
|
||||||
const [isBootstrapStateResolved, setIsBootstrapStateResolved] = createSignal(false);
|
hasChosenPersona,
|
||||||
const [isBootstrapComplete, setIsBootstrapComplete] = createSignal(false);
|
stepState,
|
||||||
const [isWizardOpen, setIsWizardOpen] = createSignal(false);
|
isBootstrapStateResolved,
|
||||||
const [currentStepIndex, setCurrentStepIndex] = createSignal(0);
|
isWizardOpen,
|
||||||
|
setIsWizardOpen,
|
||||||
|
setIsFinishingBootstrapFlow,
|
||||||
|
fieldTooltip,
|
||||||
|
materializationState,
|
||||||
|
isMaterializationInFlight,
|
||||||
|
hasMaterializationFailed,
|
||||||
|
showBootstrapFinishingState,
|
||||||
|
materializationStatusLabel,
|
||||||
|
materializationMessage,
|
||||||
|
personaDefinition,
|
||||||
|
selectedPersonaIsAvailable,
|
||||||
|
usesCondensedBootstrapFlow,
|
||||||
|
activeWizardSteps,
|
||||||
|
bootstrapNamePlaceholder,
|
||||||
|
bootstrapStepCount,
|
||||||
|
currentStep,
|
||||||
|
currentWizardStepIndex,
|
||||||
|
wizardProgressFillWidth,
|
||||||
|
currentStepState,
|
||||||
|
isFirstStep,
|
||||||
|
canDismissWizard,
|
||||||
|
handleCurrentStepSubmit,
|
||||||
|
applyPersonaSelection,
|
||||||
|
statusLabel,
|
||||||
|
showFieldTooltip,
|
||||||
|
hideFieldTooltip,
|
||||||
|
stepStatusLabel,
|
||||||
|
navigateBack,
|
||||||
|
navigateToVisibleStep,
|
||||||
|
} = useWorkspaceHomeWizard(appShellData);
|
||||||
|
const isBootstrapPersisted = createMemo(() => appShellData.installation()?.isBootstrapped ?? false);
|
||||||
|
|
||||||
createEffect(() => {
|
const sidebarToggleLabel = (): string => (props.sidebarCollapsed ? "Expand left workspace sidebar" : "Collapse left workspace sidebar");
|
||||||
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 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 (
|
return (
|
||||||
<>
|
<>
|
||||||
<main class={styles.viewport} data-ui="workspace-home">
|
<main class={styles.viewport} data-ui="workspace-home">
|
||||||
<div class={styles.workspaceTopBar} data-slot="workspace-home-top-bar">
|
<div class={styles.workspaceTopBar} data-slot="workspace-home-top-bar">
|
||||||
<div class={styles.workspaceTopBarStart} data-slot="workspace-home-top-bar-start">
|
<div class={styles.workspaceTopBarStart} data-slot="workspace-home-top-bar-start">
|
||||||
<button
|
<button type="button" class={styles.workspaceCollapseButton} aria-label={sidebarToggleLabel()} title={sidebarToggleLabel()} data-slot="workspace-home-sidebar-toggle" onClick={props.onToggleSidebarCollapse}>
|
||||||
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} />}
|
{props.sidebarCollapsed ? <ChevronRight size={16} strokeWidth={2} /> : <ChevronLeft size={16} strokeWidth={2} />}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -360,10 +83,16 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<section class={styles.hero} data-slot="workspace-home-hero">
|
<section class={styles.hero} data-slot="workspace-home-hero">
|
||||||
<h1 class={styles.title}>{isBootstrapComplete() ? appShellData.activeServer().name : bootstrapTargetLabel()}</h1>
|
<h1 class={styles.title}>{isBootstrapPersisted() ? appShellData.activeServer().name : "Server"}</h1>
|
||||||
<Show when={isBootstrapStateResolved() && !isBootstrapComplete()}>
|
<Show when={isBootstrapStateResolved() && !isBootstrapPersisted()}>
|
||||||
<div class={styles.heroActions}>
|
<div class={styles.heroActions}>
|
||||||
<button type="button" class={styles.primaryButton} onClick={(): void => setIsWizardOpen(true)}>
|
<button
|
||||||
|
type="button"
|
||||||
|
class={styles.primaryButton}
|
||||||
|
onClick={(): void => {
|
||||||
|
setIsWizardOpen(true);
|
||||||
|
}}
|
||||||
|
>
|
||||||
Open bootstrap wizard
|
Open bootstrap wizard
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -380,200 +109,160 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
|||||||
<header class={styles.wizardHeader} data-slot="bootstrap-wizard-header">
|
<header class={styles.wizardHeader} data-slot="bootstrap-wizard-header">
|
||||||
<div class={styles.wizardHeaderCopy}>
|
<div class={styles.wizardHeaderCopy}>
|
||||||
<h2 id="bootstrap-wizard-title" class={styles.wizardTitle}>
|
<h2 id="bootstrap-wizard-title" class={styles.wizardTitle}>
|
||||||
Bootstrap {bootstrapTargetLabel()}
|
Bootstrap Server
|
||||||
</h2>
|
</h2>
|
||||||
</div>
|
</div>
|
||||||
<Show when={canDismissWizard()}>
|
<Show when={canDismissWizard()}>
|
||||||
<button type="button" class={styles.wizardCloseButton} onClick={(): void => setIsWizardOpen(false)}>
|
<button
|
||||||
|
type="button"
|
||||||
|
class={styles.wizardCloseButton}
|
||||||
|
onClick={(): void => {
|
||||||
|
setIsWizardOpen(false);
|
||||||
|
}}
|
||||||
|
>
|
||||||
Close
|
Close
|
||||||
</button>
|
</button>
|
||||||
</Show>
|
</Show>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<div class={styles.wizardBody}>
|
<Show
|
||||||
<aside class={styles.wizardSidebar} data-slot="bootstrap-wizard-sidebar">
|
when={!showBootstrapFinishingState()}
|
||||||
<nav class={styles.wizardSteps} aria-label="Bootstrap steps">
|
fallback={
|
||||||
<For each={bootstrapStepDefinitions}>
|
<BootstrapFinishingState
|
||||||
{(step, index): JSX.Element => (
|
materializationState={materializationState()}
|
||||||
<button
|
statusLabel={materializationStatusLabel()}
|
||||||
type="button"
|
message={materializationMessage()}
|
||||||
class={styles.wizardStepButton}
|
isInFlight={isMaterializationInFlight()}
|
||||||
data-active={step.id === currentStep().id ? "true" : "false"}
|
hasFailed={hasMaterializationFailed()}
|
||||||
disabled={index() > currentStepIndex()}
|
onClose={(): void => {
|
||||||
onClick={(): void => {
|
setIsFinishingBootstrapFlow(false);
|
||||||
if (index() <= currentStepIndex()) {
|
setIsWizardOpen(false);
|
||||||
setCurrentStepIndex(index());
|
|
||||||
}
|
|
||||||
}}
|
}}
|
||||||
|
/>
|
||||||
|
}
|
||||||
>
|
>
|
||||||
<span class={styles.wizardStepIndex}>{index() + 1}</span>
|
<div class={styles.wizardBody}>
|
||||||
<span class={styles.wizardStepCopy}>
|
<Show when={currentStep().id !== "persona"}>
|
||||||
<strong>{step.title}</strong>
|
<BootstrapWizardProgress
|
||||||
<Show when={stepStatusLabel(step)}>
|
steps={activeWizardSteps()}
|
||||||
<small>{stepStatusLabel(step)}</small>
|
currentStepId={currentStep().id}
|
||||||
|
currentWizardStepIndex={currentWizardStepIndex()}
|
||||||
|
stepState={stepState}
|
||||||
|
bootstrapStepCount={bootstrapStepCount()}
|
||||||
|
wizardProgressFillWidth={wizardProgressFillWidth()}
|
||||||
|
stepStatusLabel={stepStatusLabel}
|
||||||
|
onSelectStep={navigateToVisibleStep}
|
||||||
|
/>
|
||||||
</Show>
|
</Show>
|
||||||
</span>
|
|
||||||
</button>
|
|
||||||
)}
|
|
||||||
</For>
|
|
||||||
</nav>
|
|
||||||
</aside>
|
|
||||||
|
|
||||||
<div class={styles.wizardStepPanel} data-slot="bootstrap-wizard-step-panel">
|
<div class={styles.wizardStepPanel} data-slot="bootstrap-wizard-step-panel">
|
||||||
|
<Show when={currentStep().id !== "persona" || statusLabel(currentStepState())}>
|
||||||
<div class={styles.sectionHeader}>
|
<div class={styles.sectionHeader}>
|
||||||
|
<Show when={currentStep().id !== "persona"}>
|
||||||
<div>
|
<div>
|
||||||
<span class={styles.wizardStepEyebrow}>{`Step ${currentStepIndex() + 1} of ${bootstrapStepDefinitions.length}`}</span>
|
<span class={styles.wizardStepEyebrow}>{`Step ${currentWizardStepIndex() + 1} of ${bootstrapStepCount()}`}</span>
|
||||||
<h3 class={styles.sectionTitle}>{currentStep().title}</h3>
|
|
||||||
</div>
|
</div>
|
||||||
<div class={styles.statusBadge} data-status={currentStepState().status}>{statusLabel(currentStepState())}</div>
|
</Show>
|
||||||
|
<Show when={statusLabel(currentStepState())}>
|
||||||
|
<div class={styles.statusBadge} data-status={currentStepState().status}>
|
||||||
|
{statusLabel(currentStepState())}
|
||||||
</div>
|
</div>
|
||||||
|
</Show>
|
||||||
|
</div>
|
||||||
|
</Show>
|
||||||
|
|
||||||
<form class={styles.form} onSubmit={handleCurrentStepSubmit}>
|
<form class={styles.form} onSubmit={handleCurrentStepSubmit}>
|
||||||
<Show when={currentStep().id === "instance"}>
|
<Show when={currentStep().id === "persona"}>
|
||||||
<>
|
<BootstrapPersonaStep
|
||||||
<label class={styles.field}>
|
personas={bootstrapPersonaDefinitions}
|
||||||
<span class={styles.fieldLabel}>Protocol</span>
|
hasChosenPersona={hasChosenPersona()}
|
||||||
<select value={instanceForm.protocol} onInput={(event): void => setInstanceForm("protocol", event.currentTarget.value)}>
|
selectedPersona={selectedPersona()}
|
||||||
<option value="http">http</option>
|
selectedPersonaIsAvailable={selectedPersonaIsAvailable()}
|
||||||
<option value="https">https</option>
|
onSelectPersona={applyPersonaSelection}
|
||||||
</select>
|
/>
|
||||||
</label>
|
</Show>
|
||||||
<label class={styles.field}>
|
|
||||||
<span class={styles.fieldLabel}>Access</span>
|
<Show when={currentStep().id === "instance"}>
|
||||||
<select value={instanceForm.access} onInput={(event): void => setInstanceForm("access", event.currentTarget.value)}>
|
<BootstrapInstanceStep
|
||||||
<option value="local">local</option>
|
instanceForm={instanceForm}
|
||||||
<option value="remote">remote</option>
|
onProtocolChange={(value): void => setInstanceForm("protocol", value)}
|
||||||
</select>
|
onAccessChange={(value): void => setInstanceForm("access", value)}
|
||||||
</label>
|
onHostChange={(value): void => setInstanceForm("host", value)}
|
||||||
<label class={styles.field}>
|
onShowTooltip={showFieldTooltip}
|
||||||
<span class={styles.fieldLabel}>Host</span>
|
onHideTooltip={hideFieldTooltip}
|
||||||
<input
|
|
||||||
type="text"
|
|
||||||
value={instanceForm.host}
|
|
||||||
onInput={(event): void => setInstanceForm("host", event.currentTarget.value)}
|
|
||||||
placeholder="localhost or app.example.com"
|
|
||||||
/>
|
/>
|
||||||
</label>
|
|
||||||
</>
|
|
||||||
</Show>
|
</Show>
|
||||||
|
|
||||||
<Show when={currentStep().id === "mode"}>
|
<Show when={currentStep().id === "mode"}>
|
||||||
<>
|
<BootstrapModeStep
|
||||||
<label class={styles.field}>
|
modeForm={modeForm}
|
||||||
<span class={styles.fieldLabel}>Mode</span>
|
structureForm={structureForm}
|
||||||
<select value={modeForm.mode} onInput={(event): void => setModeForm("mode", event.currentTarget.value)}>
|
usesCondensedBootstrapFlow={usesCondensedBootstrapFlow()}
|
||||||
<option value="personal">personal</option>
|
selectedPersona={selectedPersona()}
|
||||||
<option value="organizational">organizational</option>
|
namePlaceholder={bootstrapNamePlaceholder()}
|
||||||
</select>
|
onNameChange={(value): void => setModeForm("name", value)}
|
||||||
</label>
|
onProjectNameChange={(value): void => setStructureForm("projectName", value)}
|
||||||
<label class={styles.field}>
|
onTeamNameChange={(value): void => setStructureForm("teamName", value)}
|
||||||
<span class={styles.fieldLabel}>Server name</span>
|
onShowTooltip={showFieldTooltip}
|
||||||
<input
|
onHideTooltip={hideFieldTooltip}
|
||||||
type="text"
|
|
||||||
value={modeForm.name}
|
|
||||||
required
|
|
||||||
onInput={(event): void => setModeForm("name", event.currentTarget.value)}
|
|
||||||
placeholder={bootstrapNamePlaceholder()}
|
|
||||||
/>
|
/>
|
||||||
</label>
|
|
||||||
</>
|
|
||||||
</Show>
|
</Show>
|
||||||
|
|
||||||
<Show when={currentStep().id === "admin"}>
|
<Show when={currentStep().id === "admin"}>
|
||||||
<>
|
<BootstrapAdminStep
|
||||||
<label class={styles.field}>
|
adminForm={adminForm}
|
||||||
<span class={styles.fieldLabel}>Display name</span>
|
onDisplayNameChange={(value): void => setAdminForm("displayName", value)}
|
||||||
<input
|
onEmailChange={(value): void => setAdminForm("email", value)}
|
||||||
type="text"
|
onPasswordChange={(value): void => setAdminForm("password", value)}
|
||||||
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>
|
||||||
|
|
||||||
<Show when={currentStep().id === "structure"}>
|
<Show when={currentStep().id === "structure"}>
|
||||||
<>
|
<BootstrapStructureStep
|
||||||
<label class={styles.field}>
|
mode={modeForm.mode}
|
||||||
<span class={styles.fieldLabel}>Department</span>
|
structureForm={structureForm}
|
||||||
<input
|
onDepartmentNameChange={(value): void => setStructureForm("departmentName", value)}
|
||||||
type="text"
|
onTeamNameChange={(value): void => setStructureForm("teamName", value)}
|
||||||
value={structureForm.departmentName}
|
onProjectNameChange={(value): void => setStructureForm("projectName", value)}
|
||||||
disabled={modeForm.mode === "personal"}
|
onShowTooltip={showFieldTooltip}
|
||||||
onInput={(event): void => setStructureForm("departmentName", event.currentTarget.value)}
|
onHideTooltip={hideFieldTooltip}
|
||||||
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>
|
</Show>
|
||||||
|
|
||||||
|
<Show when={currentStep().id !== "persona"}>
|
||||||
<div class={styles.wizardFormActions}>
|
<div class={styles.wizardFormActions}>
|
||||||
<button
|
<button type="button" class={styles.secondaryButton} disabled={isFirstStep()} onClick={navigateBack}>
|
||||||
type="button"
|
|
||||||
class={styles.secondaryButton}
|
|
||||||
disabled={isFirstStep()}
|
|
||||||
onClick={(): void => setCurrentStepIndex((index) => Math.max(index - 1, 0))}
|
|
||||||
>
|
|
||||||
Back
|
Back
|
||||||
</button>
|
</button>
|
||||||
<button
|
<button type="submit" class={styles.primaryButton} disabled={currentStepState().status === "submitting"}>
|
||||||
type="submit"
|
|
||||||
class={styles.primaryButton}
|
|
||||||
disabled={currentStepState().status === "submitting"}
|
|
||||||
>
|
|
||||||
{currentStep().buttonLabel}
|
{currentStep().buttonLabel}
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
|
</Show>
|
||||||
</form>
|
</form>
|
||||||
|
|
||||||
<Show when={currentStepState().error}>
|
<Show when={currentStepState().error}>
|
||||||
<p class={styles.errorText}>{currentStepState().error}</p>
|
<p class={styles.errorText}>{currentStepState().error}</p>
|
||||||
</Show>
|
</Show>
|
||||||
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
</Show>
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
|
<Show when={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>
|
</div>
|
||||||
</Portal>
|
</Portal>
|
||||||
</Show>
|
</Show>
|
||||||
|
|||||||
Reference in New Issue
Block a user