Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| c47eae1381 | |||
| bcfe73411c | |||
| 32acf6dc17 | |||
| 6b87e8a1fe | |||
| 3247f28c87 |
@@ -50,7 +50,9 @@ var (
|
||||
ErrBootstrapStructureMissing = errors.New("bootstrap structure is incomplete")
|
||||
ErrProjectNotFound = errors.New("project not found")
|
||||
ErrProjectFolderNotFound = errors.New("project folder not found")
|
||||
ErrProjectItemNotFound = errors.New("project item not found")
|
||||
ErrInvalidProjectFolderMove = errors.New("invalid project folder move")
|
||||
ErrInvalidProjectItemMove = errors.New("invalid project item move")
|
||||
)
|
||||
|
||||
type Service struct {
|
||||
@@ -195,6 +197,15 @@ type ProjectHierarchyFolderRecord struct {
|
||||
Children []ProjectHierarchyFolderRecord `json:"children"`
|
||||
}
|
||||
|
||||
type ProjectTreeNodeRecord struct {
|
||||
ID string `json:"id"`
|
||||
Path string `json:"path"`
|
||||
Label string `json:"label"`
|
||||
Kind string `json:"kind"`
|
||||
ItemType string `json:"itemType,omitempty"`
|
||||
Children []ProjectTreeNodeRecord `json:"children,omitempty"`
|
||||
}
|
||||
|
||||
type CreateProjectFolderInput struct {
|
||||
ProjectID string
|
||||
ParentFolderPath string
|
||||
@@ -221,6 +232,27 @@ type MoveProjectFolderInput struct {
|
||||
TargetIndex int
|
||||
}
|
||||
|
||||
type CreateProjectItemInput struct {
|
||||
ProjectID string
|
||||
ParentFolderPath string
|
||||
Name string
|
||||
ItemType string
|
||||
}
|
||||
|
||||
type DeleteProjectItemInput struct {
|
||||
ProjectID string
|
||||
ItemPath string
|
||||
}
|
||||
|
||||
type MoveProjectItemInput struct {
|
||||
ProjectID string
|
||||
ItemPath string
|
||||
ItemStableID string
|
||||
ParentFolderPath string
|
||||
ParentStableID string
|
||||
TargetIndex int
|
||||
}
|
||||
|
||||
type CreateProjectFolderResult struct {
|
||||
ProjectID string `json:"projectId"`
|
||||
CreatedFolder ProjectHierarchyFolderRecord `json:"createdFolder"`
|
||||
@@ -250,6 +282,27 @@ type MoveProjectFolderResult struct {
|
||||
Folders []ProjectHierarchyFolderRecord `json:"folders"`
|
||||
}
|
||||
|
||||
type CreateProjectItemResult struct {
|
||||
ProjectID string `json:"projectId"`
|
||||
CreatedItem ProjectTreeNodeRecord `json:"createdItem"`
|
||||
Nodes []ProjectTreeNodeRecord `json:"nodes"`
|
||||
}
|
||||
|
||||
type DeleteProjectItemResult struct {
|
||||
ProjectID string `json:"projectId"`
|
||||
DeletedItemStableID string `json:"deletedItemId"`
|
||||
DeletedItemPath string `json:"deletedItemPath"`
|
||||
Nodes []ProjectTreeNodeRecord `json:"nodes"`
|
||||
}
|
||||
|
||||
type MoveProjectItemResult struct {
|
||||
ProjectID string `json:"projectId"`
|
||||
PreviousItemStableID string `json:"previousItemId"`
|
||||
PreviousItemPath string `json:"previousItemPath"`
|
||||
MovedItem ProjectTreeNodeRecord `json:"movedItem"`
|
||||
Nodes []ProjectTreeNodeRecord `json:"nodes"`
|
||||
}
|
||||
|
||||
type projectHierarchyFolderRow struct {
|
||||
ID string
|
||||
Path string
|
||||
@@ -257,6 +310,15 @@ type projectHierarchyFolderRow struct {
|
||||
Label string
|
||||
}
|
||||
|
||||
type projectTreeNodeRow struct {
|
||||
ID string
|
||||
Path string
|
||||
ParentPath string
|
||||
Label string
|
||||
Kind string
|
||||
ItemType string
|
||||
}
|
||||
|
||||
func NewService(db *database.DB, posixRoot string) *Service {
|
||||
return &Service{db: db, posixRoot: strings.TrimSpace(posixRoot)}
|
||||
}
|
||||
@@ -815,6 +877,10 @@ func (service *Service) GetProjectTreeFolders(ctx context.Context, projectID str
|
||||
return service.getProjectHierarchyFoldersByRootPath(ctx, projectID, projectTreeRootPath)
|
||||
}
|
||||
|
||||
func (service *Service) GetProjectTreeNodes(ctx context.Context, projectID string) ([]ProjectTreeNodeRecord, error) {
|
||||
return service.getProjectTreeNodesByRootPath(ctx, projectID, projectTreeRootPath)
|
||||
}
|
||||
|
||||
func (service *Service) getProjectHierarchyFoldersByRootPath(
|
||||
ctx context.Context,
|
||||
projectID string,
|
||||
@@ -870,6 +936,64 @@ func (service *Service) getProjectHierarchyFoldersByRootPath(
|
||||
return applyProjectHierarchyFolderOrdering(folders, folderOrder), nil
|
||||
}
|
||||
|
||||
func (service *Service) getProjectTreeNodesByRootPath(
|
||||
ctx context.Context,
|
||||
projectID string,
|
||||
rootPath func(projectSlug string) string,
|
||||
) ([]ProjectTreeNodeRecord, error) {
|
||||
project, err := service.loadProjectByID(ctx, projectID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
rootParentPath := rootPath(project.Slug)
|
||||
|
||||
rows, err := service.db.Pool.Query(ctx, `
|
||||
SELECT
|
||||
COALESCE(node_meta.resource_id, ''),
|
||||
directories.path,
|
||||
COALESCE(directories.parent_path, ''),
|
||||
COALESCE(node_meta.resource_name, directories.resource_name, ''),
|
||||
directories.logical_type,
|
||||
COALESCE(node_meta.content_json->>'type', directories.content_json->>'type', '')
|
||||
FROM posix_nodes AS directories
|
||||
LEFT JOIN posix_nodes AS node_meta
|
||||
ON node_meta.path = directories.path || CASE
|
||||
WHEN directories.logical_type = 'hierarchy_folder' THEN '/folder.json'
|
||||
WHEN directories.logical_type = 'item' THEN '/item.json'
|
||||
ELSE ''
|
||||
END
|
||||
AND node_meta.node_kind = 'file'::posix_node_kind
|
||||
WHERE directories.node_kind = 'directory'::posix_node_kind
|
||||
AND directories.logical_type IN ('hierarchy_folder', 'item')
|
||||
AND directories.project_slug = $1
|
||||
AND directories.path LIKE $2
|
||||
ORDER BY directories.depth ASC, directories.path ASC;
|
||||
`, project.Slug, rootParentPath+"/%")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var nodeRows []projectTreeNodeRow
|
||||
for rows.Next() {
|
||||
var row projectTreeNodeRow
|
||||
if err := rows.Scan(&row.ID, &row.Path, &row.ParentPath, &row.Label, &row.Kind, &row.ItemType); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
nodeRows = append(nodeRows, row)
|
||||
}
|
||||
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
nodes := buildProjectTreeNodeTree(nodeRows, rootParentPath)
|
||||
folderOrder := service.readProjectFolderOrder(project.Slug, rootParentPath)
|
||||
|
||||
return applyProjectTreeNodeOrdering(nodes, folderOrder), nil
|
||||
}
|
||||
|
||||
func (service *Service) CreateProjectFolder(ctx context.Context, input CreateProjectFolderInput) (CreateProjectFolderResult, error) {
|
||||
return service.createProjectHierarchyFolder(ctx, input, projectHierarchyRootPath, service.createProjectHierarchyFolderOnDisk)
|
||||
}
|
||||
@@ -902,6 +1026,18 @@ func (service *Service) MoveProjectTreeFolder(ctx context.Context, input MovePro
|
||||
return service.moveProjectHierarchyFolder(ctx, input, projectTreeRootPath, service.moveProjectTreeFolderOnDisk)
|
||||
}
|
||||
|
||||
func (service *Service) CreateProjectTreeItem(ctx context.Context, input CreateProjectItemInput) (CreateProjectItemResult, error) {
|
||||
return service.createProjectTreeItem(ctx, input, projectTreeRootPath)
|
||||
}
|
||||
|
||||
func (service *Service) DeleteProjectTreeItem(ctx context.Context, input DeleteProjectItemInput) (DeleteProjectItemResult, error) {
|
||||
return service.deleteProjectTreeItem(ctx, input, projectTreeRootPath)
|
||||
}
|
||||
|
||||
func (service *Service) MoveProjectTreeItem(ctx context.Context, input MoveProjectItemInput) (MoveProjectItemResult, error) {
|
||||
return service.moveProjectTreeItem(ctx, input, projectTreeRootPath)
|
||||
}
|
||||
|
||||
func (service *Service) createProjectHierarchyFolder(
|
||||
ctx context.Context,
|
||||
input CreateProjectFolderInput,
|
||||
@@ -1174,6 +1310,226 @@ func (service *Service) moveProjectHierarchyFolder(
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) createProjectTreeItem(
|
||||
ctx context.Context,
|
||||
input CreateProjectItemInput,
|
||||
rootPath func(projectSlug string) string,
|
||||
) (CreateProjectItemResult, error) {
|
||||
project, err := service.loadProjectByID(ctx, strings.TrimSpace(input.ProjectID))
|
||||
if err != nil {
|
||||
return CreateProjectItemResult{}, err
|
||||
}
|
||||
|
||||
currentNodes, err := service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return CreateProjectItemResult{}, err
|
||||
}
|
||||
|
||||
parentOrderID := ""
|
||||
trimmedParentFolderPath := strings.TrimSpace(input.ParentFolderPath)
|
||||
if trimmedParentFolderPath != "" {
|
||||
parentFolder, found := findProjectTreeFolderByPath(currentNodes, trimmedParentFolderPath)
|
||||
if !found {
|
||||
return CreateProjectItemResult{}, ErrProjectFolderNotFound
|
||||
}
|
||||
parentOrderID = parentFolder.ID
|
||||
}
|
||||
|
||||
createdPath, err := service.createProjectTreeItemOnDisk(project.Slug, trimmedParentFolderPath, input.Name, input.ItemType)
|
||||
if err != nil {
|
||||
return CreateProjectItemResult{}, err
|
||||
}
|
||||
|
||||
if err := service.rebuildProjection(ctx); err != nil {
|
||||
return CreateProjectItemResult{}, err
|
||||
}
|
||||
|
||||
nodes, err := service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return CreateProjectItemResult{}, err
|
||||
}
|
||||
|
||||
createdItem, ok := findProjectTreeNodeByPath(nodes, createdPath)
|
||||
if !ok || createdItem.Kind != "item" {
|
||||
return CreateProjectItemResult{}, fmt.Errorf("created project item missing from projection")
|
||||
}
|
||||
|
||||
folderOrder := service.readProjectFolderOrder(project.Slug, rootPath(project.Slug))
|
||||
seedProjectTreeOrderParent(folderOrder, currentNodes, parentOrderID)
|
||||
insertFolderOrder(folderOrder, parentOrderID, createdItem.ID, len(folderOrderChildren(folderOrder, parentOrderID)))
|
||||
if err := service.writeProjectFolderOrder(project.Slug, rootPath(project.Slug), folderOrder); err != nil {
|
||||
return CreateProjectItemResult{}, err
|
||||
}
|
||||
|
||||
nodes, err = service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return CreateProjectItemResult{}, err
|
||||
}
|
||||
|
||||
createdItem, ok = findProjectTreeNodeByPath(nodes, createdPath)
|
||||
if !ok || createdItem.Kind != "item" {
|
||||
return CreateProjectItemResult{}, fmt.Errorf("created project item missing from ordered projection")
|
||||
}
|
||||
|
||||
return CreateProjectItemResult{
|
||||
ProjectID: project.ID,
|
||||
CreatedItem: createdItem,
|
||||
Nodes: nodes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) deleteProjectTreeItem(
|
||||
ctx context.Context,
|
||||
input DeleteProjectItemInput,
|
||||
rootPath func(projectSlug string) string,
|
||||
) (DeleteProjectItemResult, error) {
|
||||
project, err := service.loadProjectByID(ctx, strings.TrimSpace(input.ProjectID))
|
||||
if err != nil {
|
||||
return DeleteProjectItemResult{}, err
|
||||
}
|
||||
|
||||
currentNodes, err := service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return DeleteProjectItemResult{}, err
|
||||
}
|
||||
|
||||
deletedItem, found := findProjectTreeNodeByPath(currentNodes, strings.TrimSpace(input.ItemPath))
|
||||
if !found || deletedItem.Kind != "item" {
|
||||
return DeleteProjectItemResult{}, ErrProjectItemNotFound
|
||||
}
|
||||
|
||||
deletedItemPath, err := service.deleteProjectTreeItemOnDisk(project.Slug, input.ItemPath)
|
||||
if err != nil {
|
||||
return DeleteProjectItemResult{}, err
|
||||
}
|
||||
|
||||
if err := service.rebuildProjection(ctx); err != nil {
|
||||
return DeleteProjectItemResult{}, err
|
||||
}
|
||||
|
||||
nodes, err := service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return DeleteProjectItemResult{}, err
|
||||
}
|
||||
|
||||
if _, found := findProjectTreeNodeByPath(nodes, deletedItemPath); found {
|
||||
return DeleteProjectItemResult{}, fmt.Errorf("deleted project item still present in projection")
|
||||
}
|
||||
|
||||
folderOrder := service.readProjectFolderOrder(project.Slug, rootPath(project.Slug))
|
||||
removeFolderOrderReference(folderOrder, deletedItem.ID)
|
||||
if err := service.writeProjectFolderOrder(project.Slug, rootPath(project.Slug), folderOrder); err != nil {
|
||||
return DeleteProjectItemResult{}, err
|
||||
}
|
||||
|
||||
nodes, err = service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return DeleteProjectItemResult{}, err
|
||||
}
|
||||
|
||||
return DeleteProjectItemResult{
|
||||
ProjectID: project.ID,
|
||||
DeletedItemStableID: deletedItem.ID,
|
||||
DeletedItemPath: deletedItemPath,
|
||||
Nodes: nodes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) moveProjectTreeItem(
|
||||
ctx context.Context,
|
||||
input MoveProjectItemInput,
|
||||
rootPath func(projectSlug string) string,
|
||||
) (MoveProjectItemResult, error) {
|
||||
project, err := service.loadProjectByID(ctx, strings.TrimSpace(input.ProjectID))
|
||||
if err != nil {
|
||||
return MoveProjectItemResult{}, err
|
||||
}
|
||||
|
||||
currentNodes, err := service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return MoveProjectItemResult{}, err
|
||||
}
|
||||
|
||||
currentItem, found := findProjectTreeNodeByPath(currentNodes, strings.TrimSpace(input.ItemPath))
|
||||
if !found || currentItem.Kind != "item" {
|
||||
return MoveProjectItemResult{}, ErrProjectItemNotFound
|
||||
}
|
||||
|
||||
movedItemStableID := currentItem.ID
|
||||
providedItemStableID := strings.TrimSpace(input.ItemStableID)
|
||||
if providedItemStableID != "" && providedItemStableID != movedItemStableID {
|
||||
return MoveProjectItemResult{}, ErrInvalidProjectItemMove
|
||||
}
|
||||
|
||||
parentOrderID := ""
|
||||
trimmedParentFolderPath := strings.TrimSpace(input.ParentFolderPath)
|
||||
providedParentStableID := strings.TrimSpace(input.ParentStableID)
|
||||
if trimmedParentFolderPath != "" {
|
||||
parentFolder, found := findProjectTreeFolderByPath(currentNodes, trimmedParentFolderPath)
|
||||
if !found {
|
||||
return MoveProjectItemResult{}, ErrProjectFolderNotFound
|
||||
}
|
||||
parentOrderID = parentFolder.ID
|
||||
if providedParentStableID != "" && providedParentStableID != parentOrderID {
|
||||
return MoveProjectItemResult{}, ErrInvalidProjectItemMove
|
||||
}
|
||||
} else if providedParentStableID != "" {
|
||||
return MoveProjectItemResult{}, ErrInvalidProjectItemMove
|
||||
}
|
||||
|
||||
previousItemPath, movedItemPath, err := service.moveProjectTreeItemOnDisk(project.Slug, input.ItemPath, input.ParentFolderPath)
|
||||
if err != nil {
|
||||
return MoveProjectItemResult{}, err
|
||||
}
|
||||
|
||||
if err := service.rebuildProjection(ctx); err != nil {
|
||||
return MoveProjectItemResult{}, err
|
||||
}
|
||||
|
||||
nodes, err := service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return MoveProjectItemResult{}, err
|
||||
}
|
||||
|
||||
movedItem, found := findProjectTreeNodeByPath(nodes, movedItemPath)
|
||||
if !found || movedItem.Kind != "item" {
|
||||
return MoveProjectItemResult{}, fmt.Errorf("moved project item missing from projection")
|
||||
}
|
||||
|
||||
if previousItemPath != movedItemPath {
|
||||
if _, found := findProjectTreeNodeByPath(nodes, previousItemPath); found {
|
||||
return MoveProjectItemResult{}, fmt.Errorf("previous project item path still present in projection")
|
||||
}
|
||||
}
|
||||
|
||||
folderOrder := service.readProjectFolderOrder(project.Slug, rootPath(project.Slug))
|
||||
seedProjectTreeOrderParent(folderOrder, currentNodes, parentOrderID)
|
||||
removeFolderOrderReference(folderOrder, movedItemStableID)
|
||||
removeFolderOrderReference(folderOrder, movedItem.ID)
|
||||
insertFolderOrder(folderOrder, parentOrderID, movedItem.ID, input.TargetIndex)
|
||||
if err := service.writeProjectFolderOrder(project.Slug, rootPath(project.Slug), folderOrder); err != nil {
|
||||
return MoveProjectItemResult{}, err
|
||||
}
|
||||
|
||||
nodes, err = service.getProjectTreeNodesByRootPath(ctx, project.ID, rootPath)
|
||||
if err != nil {
|
||||
return MoveProjectItemResult{}, err
|
||||
}
|
||||
|
||||
movedItem, found = findProjectTreeNodeByPath(nodes, movedItemPath)
|
||||
if !found || movedItem.Kind != "item" {
|
||||
return MoveProjectItemResult{}, fmt.Errorf("moved project item missing from ordered projection")
|
||||
}
|
||||
|
||||
return MoveProjectItemResult{
|
||||
ProjectID: project.ID,
|
||||
PreviousItemStableID: movedItem.ID,
|
||||
PreviousItemPath: previousItemPath,
|
||||
MovedItem: movedItem,
|
||||
Nodes: nodes,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (service *Service) listWorkspaces(ctx context.Context) ([]WorkspaceRecord, error) {
|
||||
rows, err := service.db.Pool.Query(ctx, `
|
||||
SELECT id::text, organization_id::text, name, slug, kind::text, department_id::text, team_id::text, project_id::text
|
||||
@@ -1796,6 +2152,218 @@ func (service *Service) moveProjectFolderOnDisk(
|
||||
return folderProjectionPath, movedProjectionPath, nil
|
||||
}
|
||||
|
||||
func (service *Service) createProjectTreeItemOnDisk(
|
||||
projectSlug, parentFolderPath, name, itemType string,
|
||||
) (string, error) {
|
||||
posixRoot := strings.TrimSpace(service.posixRoot)
|
||||
if posixRoot == "" {
|
||||
return "", fmt.Errorf("POSIX root is not configured")
|
||||
}
|
||||
|
||||
trimmedName := strings.TrimSpace(name)
|
||||
if trimmedName == "" {
|
||||
return "", fmt.Errorf("item name is required")
|
||||
}
|
||||
|
||||
canonicalItemType := normalizeProjectTreeItemType(itemType)
|
||||
containerProjectionPath := projectTreeRootPath(projectSlug)
|
||||
parentDir := filepath.Join(posixRoot, filepath.FromSlash(containerProjectionPath))
|
||||
|
||||
if trimmedParentFolderPath := strings.TrimSpace(parentFolderPath); trimmedParentFolderPath != "" {
|
||||
containerProjectionPath = trimmedParentFolderPath
|
||||
parentDir = filepath.Join(posixRoot, filepath.FromSlash(containerProjectionPath))
|
||||
info, err := os.Stat(parentDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "", ErrProjectFolderNotFound
|
||||
}
|
||||
return "", fmt.Errorf("stat parent project folder: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", ErrProjectFolderNotFound
|
||||
}
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(parentDir, 0o755); err != nil {
|
||||
return "", fmt.Errorf("create parent project item path: %w", err)
|
||||
}
|
||||
|
||||
baseSlug := normalizePOSIXSlug(trimmedName)
|
||||
itemDirName := slugDir("item", baseSlug)
|
||||
itemDir := filepath.Join(parentDir, itemDirName)
|
||||
itemSlug := baseSlug
|
||||
|
||||
for attempt := 2; ; attempt += 1 {
|
||||
if _, err := os.Stat(itemDir); os.IsNotExist(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return "", fmt.Errorf("stat candidate project item: %w", err)
|
||||
}
|
||||
|
||||
itemSlug = fmt.Sprintf("%s-%d", baseSlug, attempt)
|
||||
itemDirName = slugDir("item", itemSlug)
|
||||
itemDir = filepath.Join(parentDir, itemDirName)
|
||||
}
|
||||
|
||||
if err := os.MkdirAll(itemDir, 0o755); err != nil {
|
||||
return "", fmt.Errorf("create project item: %w", err)
|
||||
}
|
||||
|
||||
itemID := uuid.NewString()
|
||||
if err := writeJSONFile(filepath.Join(itemDir, "item.json"), map[string]any{
|
||||
"id": itemID,
|
||||
"name": trimmedName,
|
||||
"slug": itemSlug,
|
||||
"type": canonicalItemType,
|
||||
}); err != nil {
|
||||
return "", fmt.Errorf("write project item.json: %w", err)
|
||||
}
|
||||
|
||||
if err := writeJSONFile(filepath.Join(itemDir, "schema.json"), defaultProjectTreeItemSchema(canonicalItemType)); err != nil {
|
||||
return "", fmt.Errorf("write project schema.json: %w", err)
|
||||
}
|
||||
|
||||
if err := writeJSONFile(filepath.Join(itemDir, "data.json"), defaultProjectTreeItemData(canonicalItemType, trimmedName)); err != nil {
|
||||
return "", fmt.Errorf("write project data.json: %w", err)
|
||||
}
|
||||
|
||||
return filepath.ToSlash(filepath.Join(containerProjectionPath, itemDirName)), nil
|
||||
}
|
||||
|
||||
func (service *Service) deleteProjectTreeItemOnDisk(projectSlug, itemPath string) (string, error) {
|
||||
posixRoot := strings.TrimSpace(service.posixRoot)
|
||||
if posixRoot == "" {
|
||||
return "", fmt.Errorf("POSIX root is not configured")
|
||||
}
|
||||
|
||||
rootProjectionPath := projectTreeRootPath(projectSlug)
|
||||
itemProjectionPath := strings.TrimPrefix(filepath.ToSlash(filepath.Clean("/"+strings.TrimSpace(itemPath))), "/")
|
||||
if itemProjectionPath == "." || itemProjectionPath == rootProjectionPath || !strings.HasPrefix(itemProjectionPath, rootProjectionPath+"/") {
|
||||
return "", ErrProjectItemNotFound
|
||||
}
|
||||
|
||||
itemDir := filepath.Join(posixRoot, filepath.FromSlash(itemProjectionPath))
|
||||
info, err := os.Stat(itemDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "", ErrProjectItemNotFound
|
||||
}
|
||||
return "", fmt.Errorf("stat project item: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", ErrProjectItemNotFound
|
||||
}
|
||||
|
||||
if err := os.RemoveAll(itemDir); err != nil {
|
||||
return "", fmt.Errorf("delete project item: %w", err)
|
||||
}
|
||||
|
||||
return itemProjectionPath, nil
|
||||
}
|
||||
|
||||
func (service *Service) moveProjectTreeItemOnDisk(projectSlug, itemPath, parentFolderPath string) (string, string, error) {
|
||||
posixRoot := strings.TrimSpace(service.posixRoot)
|
||||
if posixRoot == "" {
|
||||
return "", "", fmt.Errorf("POSIX root is not configured")
|
||||
}
|
||||
|
||||
rootProjectionPath := projectTreeRootPath(projectSlug)
|
||||
itemProjectionPath := strings.TrimPrefix(filepath.ToSlash(filepath.Clean("/"+strings.TrimSpace(itemPath))), "/")
|
||||
if itemProjectionPath == "." || itemProjectionPath == rootProjectionPath || !strings.HasPrefix(itemProjectionPath, rootProjectionPath+"/") {
|
||||
return "", "", ErrProjectItemNotFound
|
||||
}
|
||||
|
||||
itemDir := filepath.Join(posixRoot, filepath.FromSlash(itemProjectionPath))
|
||||
info, err := os.Stat(itemDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "", "", ErrProjectItemNotFound
|
||||
}
|
||||
return "", "", fmt.Errorf("stat project item: %w", err)
|
||||
}
|
||||
if !info.IsDir() {
|
||||
return "", "", ErrProjectItemNotFound
|
||||
}
|
||||
|
||||
trimmedParentFolderPath := strings.TrimSpace(parentFolderPath)
|
||||
parentProjectionPath := rootProjectionPath
|
||||
parentDir := filepath.Join(posixRoot, filepath.FromSlash(parentProjectionPath))
|
||||
if trimmedParentFolderPath != "" {
|
||||
parentProjectionPath = strings.TrimPrefix(filepath.ToSlash(filepath.Clean("/"+trimmedParentFolderPath)), "/")
|
||||
if parentProjectionPath == "." || parentProjectionPath == rootProjectionPath || !strings.HasPrefix(parentProjectionPath, rootProjectionPath+"/") {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
parentDir = filepath.Join(posixRoot, filepath.FromSlash(parentProjectionPath))
|
||||
}
|
||||
|
||||
parentInfo, err := os.Stat(parentDir)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
return "", "", fmt.Errorf("stat project item parent: %w", err)
|
||||
}
|
||||
if !parentInfo.IsDir() {
|
||||
return "", "", ErrProjectFolderNotFound
|
||||
}
|
||||
|
||||
currentParentDir := filepath.Dir(itemDir)
|
||||
currentBase := filepath.Base(itemDir)
|
||||
itemPayload := readJSONFileMap(filepath.Join(itemDir, "item.json"))
|
||||
itemID, _ := itemPayload["id"].(string)
|
||||
if strings.TrimSpace(itemID) == "" {
|
||||
itemID = uuid.NewString()
|
||||
}
|
||||
itemName, _ := itemPayload["name"].(string)
|
||||
if strings.TrimSpace(itemName) == "" {
|
||||
itemName = fallbackItemLabel(itemProjectionPath)
|
||||
}
|
||||
itemType, _ := itemPayload["type"].(string)
|
||||
canonicalItemType := normalizeProjectTreeItemType(itemType)
|
||||
|
||||
baseSlug := strings.TrimPrefix(currentBase, "item-")
|
||||
if strings.TrimSpace(baseSlug) == "" {
|
||||
baseSlug = normalizePOSIXSlug(itemName)
|
||||
}
|
||||
|
||||
itemSlug := baseSlug
|
||||
itemDirName := slugDir("item", itemSlug)
|
||||
destinationDir := filepath.Join(parentDir, itemDirName)
|
||||
for attempt := 2; ; attempt += 1 {
|
||||
if samePath(destinationDir, itemDir) {
|
||||
break
|
||||
}
|
||||
if _, err := os.Stat(destinationDir); os.IsNotExist(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return "", "", fmt.Errorf("stat candidate moved project item: %w", err)
|
||||
}
|
||||
|
||||
itemSlug = fmt.Sprintf("%s-%d", baseSlug, attempt)
|
||||
itemDirName = slugDir("item", itemSlug)
|
||||
destinationDir = filepath.Join(parentDir, itemDirName)
|
||||
}
|
||||
|
||||
movedProjectionPath := filepath.ToSlash(filepath.Join(parentProjectionPath, itemDirName))
|
||||
if samePath(currentParentDir, parentDir) && currentBase == itemDirName {
|
||||
return itemProjectionPath, itemProjectionPath, nil
|
||||
}
|
||||
|
||||
if err := os.Rename(itemDir, destinationDir); err != nil {
|
||||
return "", "", fmt.Errorf("move project item: %w", err)
|
||||
}
|
||||
|
||||
itemPayload["id"] = itemID
|
||||
itemPayload["name"] = itemName
|
||||
itemPayload["slug"] = itemSlug
|
||||
itemPayload["type"] = canonicalItemType
|
||||
if err := writeJSONFile(filepath.Join(destinationDir, "item.json"), itemPayload); err != nil {
|
||||
return "", "", fmt.Errorf("write moved project item.json: %w", err)
|
||||
}
|
||||
|
||||
return itemProjectionPath, movedProjectionPath, nil
|
||||
}
|
||||
|
||||
func samePath(left, right string) bool {
|
||||
cleanLeft := filepath.Clean(left)
|
||||
cleanRight := filepath.Clean(right)
|
||||
@@ -2144,6 +2712,136 @@ func buildProjectHierarchyFolderTree(rows []projectHierarchyFolderRow, rootParen
|
||||
return build(rootParentPath)
|
||||
}
|
||||
|
||||
func buildProjectTreeNodeTree(rows []projectTreeNodeRow, rootParentPath string) []ProjectTreeNodeRecord {
|
||||
if len(rows) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
nodesByPath := make(map[string]*ProjectTreeNodeRecord, len(rows))
|
||||
childrenByParent := make(map[string][]string)
|
||||
|
||||
for _, row := range rows {
|
||||
nodeKind := normalizeProjectTreeNodeKind(row.Kind)
|
||||
nodeID := strings.TrimSpace(row.ID)
|
||||
if nodeID == "" {
|
||||
nodeID = row.Path
|
||||
}
|
||||
label := strings.TrimSpace(row.Label)
|
||||
if label == "" {
|
||||
if nodeKind == "item" {
|
||||
label = fallbackItemLabel(row.Path)
|
||||
} else {
|
||||
label = fallbackFolderLabel(row.Path)
|
||||
}
|
||||
}
|
||||
|
||||
nodesByPath[row.Path] = &ProjectTreeNodeRecord{
|
||||
ID: nodeID,
|
||||
Path: row.Path,
|
||||
Label: label,
|
||||
Kind: nodeKind,
|
||||
ItemType: normalizeProjectTreeItemType(row.ItemType),
|
||||
Children: []ProjectTreeNodeRecord{},
|
||||
}
|
||||
childrenByParent[normalizeProjectTreeParentPath(nodeKind, row.ParentPath)] = append(childrenByParent[normalizeProjectTreeParentPath(nodeKind, row.ParentPath)], row.Path)
|
||||
}
|
||||
|
||||
var build func(parentPath string) []ProjectTreeNodeRecord
|
||||
build = func(parentPath string) []ProjectTreeNodeRecord {
|
||||
childPaths := childrenByParent[parentPath]
|
||||
if len(childPaths) == 0 {
|
||||
return nil
|
||||
}
|
||||
|
||||
nodes := make([]ProjectTreeNodeRecord, 0, len(childPaths))
|
||||
for _, childPath := range childPaths {
|
||||
node := nodesByPath[childPath]
|
||||
if node == nil {
|
||||
continue
|
||||
}
|
||||
|
||||
nextNode := ProjectTreeNodeRecord{
|
||||
ID: node.ID,
|
||||
Path: node.Path,
|
||||
Label: node.Label,
|
||||
Kind: node.Kind,
|
||||
ItemType: node.ItemType,
|
||||
}
|
||||
if node.Kind == "folder" {
|
||||
nextNode.Children = build(node.Path)
|
||||
}
|
||||
nodes = append(nodes, nextNode)
|
||||
}
|
||||
|
||||
return nodes
|
||||
}
|
||||
|
||||
return build(rootParentPath)
|
||||
}
|
||||
|
||||
func normalizeProjectTreeParentPath(kind, parentPath string) string {
|
||||
if kind == "folder" && strings.HasSuffix(parentPath, "/children") {
|
||||
return filepath.ToSlash(filepath.Dir(parentPath))
|
||||
}
|
||||
|
||||
return parentPath
|
||||
}
|
||||
|
||||
func normalizeProjectTreeNodeKind(kind string) string {
|
||||
switch strings.TrimSpace(kind) {
|
||||
case "item":
|
||||
return "item"
|
||||
case "folder", "hierarchy_folder":
|
||||
return "folder"
|
||||
default:
|
||||
return "folder"
|
||||
}
|
||||
}
|
||||
|
||||
func applyProjectTreeNodeOrdering(nodes []ProjectTreeNodeRecord, folderOrder map[string][]string) []ProjectTreeNodeRecord {
|
||||
return applyProjectTreeNodeOrderingForParent(nodes, "", folderOrder)
|
||||
}
|
||||
|
||||
func applyProjectTreeNodeOrderingForParent(nodes []ProjectTreeNodeRecord, parentID string, folderOrder map[string][]string) []ProjectTreeNodeRecord {
|
||||
if len(nodes) == 0 {
|
||||
return nodes
|
||||
}
|
||||
|
||||
nextNodes := make([]ProjectTreeNodeRecord, len(nodes))
|
||||
copy(nextNodes, nodes)
|
||||
for index := range nextNodes {
|
||||
if nextNodes[index].Kind == "folder" {
|
||||
nextNodes[index].Children = applyProjectTreeNodeOrderingForParent(nextNodes[index].Children, nextNodes[index].ID, folderOrder)
|
||||
}
|
||||
}
|
||||
|
||||
orderIDs := folderOrder[projectFolderOrderParentKey(parentID)]
|
||||
if len(orderIDs) == 0 {
|
||||
return nextNodes
|
||||
}
|
||||
|
||||
rankByID := make(map[string]int, len(orderIDs))
|
||||
for index, id := range orderIDs {
|
||||
if _, exists := rankByID[id]; !exists {
|
||||
rankByID[id] = index
|
||||
}
|
||||
}
|
||||
|
||||
sort.SliceStable(nextNodes, func(left, right int) bool {
|
||||
leftRank, leftOrdered := rankByID[nextNodes[left].ID]
|
||||
rightRank, rightOrdered := rankByID[nextNodes[right].ID]
|
||||
if leftOrdered && rightOrdered {
|
||||
return leftRank < rightRank
|
||||
}
|
||||
if leftOrdered != rightOrdered {
|
||||
return leftOrdered
|
||||
}
|
||||
return false
|
||||
})
|
||||
|
||||
return nextNodes
|
||||
}
|
||||
|
||||
func findProjectHierarchyFolder(folders []ProjectHierarchyFolderRecord, folderID string) (ProjectHierarchyFolderRecord, bool) {
|
||||
for _, folder := range folders {
|
||||
if folder.ID == folderID {
|
||||
@@ -2172,6 +2870,41 @@ func findProjectHierarchyFolderByPath(folders []ProjectHierarchyFolderRecord, fo
|
||||
return ProjectHierarchyFolderRecord{}, false
|
||||
}
|
||||
|
||||
func findProjectTreeNode(nodes []ProjectTreeNodeRecord, nodeID string) (ProjectTreeNodeRecord, bool) {
|
||||
for _, node := range nodes {
|
||||
if node.ID == nodeID {
|
||||
return node, true
|
||||
}
|
||||
if child, ok := findProjectTreeNode(node.Children, nodeID); ok {
|
||||
return child, true
|
||||
}
|
||||
}
|
||||
|
||||
return ProjectTreeNodeRecord{}, false
|
||||
}
|
||||
|
||||
func findProjectTreeNodeByPath(nodes []ProjectTreeNodeRecord, nodePath string) (ProjectTreeNodeRecord, bool) {
|
||||
for _, node := range nodes {
|
||||
if node.Path == nodePath {
|
||||
return node, true
|
||||
}
|
||||
if child, ok := findProjectTreeNodeByPath(node.Children, nodePath); ok {
|
||||
return child, true
|
||||
}
|
||||
}
|
||||
|
||||
return ProjectTreeNodeRecord{}, false
|
||||
}
|
||||
|
||||
func findProjectTreeFolderByPath(nodes []ProjectTreeNodeRecord, folderPath string) (ProjectTreeNodeRecord, bool) {
|
||||
node, ok := findProjectTreeNodeByPath(nodes, folderPath)
|
||||
if !ok || node.Kind != "folder" {
|
||||
return ProjectTreeNodeRecord{}, false
|
||||
}
|
||||
|
||||
return node, true
|
||||
}
|
||||
|
||||
func projectHierarchyRootPath(projectSlug string) string {
|
||||
return filepath.ToSlash(filepath.Join("projects", slugDir("project", projectSlug), "children"))
|
||||
}
|
||||
@@ -2226,6 +2959,80 @@ func fallbackFolderLabel(path string) string {
|
||||
return label
|
||||
}
|
||||
|
||||
func fallbackItemLabel(path string) string {
|
||||
base := filepath.Base(filepath.FromSlash(path))
|
||||
trimmed := strings.TrimPrefix(base, "item-")
|
||||
parts := strings.FieldsFunc(trimmed, func(r rune) bool { return r == '-' || r == '_' })
|
||||
for index, part := range parts {
|
||||
if part == "" {
|
||||
continue
|
||||
}
|
||||
parts[index] = strings.ToUpper(part[:1]) + part[1:]
|
||||
}
|
||||
label := strings.Join(parts, " ")
|
||||
if label == "" {
|
||||
return base
|
||||
}
|
||||
return label
|
||||
}
|
||||
|
||||
func normalizeProjectTreeItemType(itemType string) string {
|
||||
switch strings.TrimSpace(strings.ToLower(itemType)) {
|
||||
case "", "board", "core.board", "core.board.kanban", "kanban":
|
||||
return "core.board.kanban"
|
||||
case "core.doc", "doc", "document":
|
||||
return "core.doc"
|
||||
case "core.board.list", "list", "list-board":
|
||||
return "core.board.list"
|
||||
default:
|
||||
return strings.TrimSpace(itemType)
|
||||
}
|
||||
}
|
||||
|
||||
func seedProjectTreeOrderParent(folderOrder map[string][]string, nodes []ProjectTreeNodeRecord, parentID string) {
|
||||
children := nodes
|
||||
trimmedParentID := strings.TrimSpace(parentID)
|
||||
if trimmedParentID != "" {
|
||||
parent, found := findProjectTreeNode(nodes, trimmedParentID)
|
||||
if !found || parent.Kind != "folder" {
|
||||
return
|
||||
}
|
||||
children = parent.Children
|
||||
}
|
||||
|
||||
parentKey := projectFolderOrderParentKey(parentID)
|
||||
if len(folderOrder[parentKey]) > 0 {
|
||||
return
|
||||
}
|
||||
|
||||
orderedIDs := make([]string, 0, len(children))
|
||||
for _, child := range children {
|
||||
trimmedChildID := strings.TrimSpace(child.ID)
|
||||
if trimmedChildID == "" || slicesContains(orderedIDs, trimmedChildID) {
|
||||
continue
|
||||
}
|
||||
orderedIDs = append(orderedIDs, trimmedChildID)
|
||||
}
|
||||
|
||||
if len(orderedIDs) > 0 {
|
||||
folderOrder[parentKey] = orderedIDs
|
||||
}
|
||||
}
|
||||
|
||||
func defaultProjectTreeItemSchema(itemType string) map[string]any {
|
||||
return map[string]any{
|
||||
"type": "object",
|
||||
"itemType": normalizeProjectTreeItemType(itemType),
|
||||
}
|
||||
}
|
||||
|
||||
func defaultProjectTreeItemData(itemType, name string) map[string]any {
|
||||
return map[string]any{
|
||||
"title": strings.TrimSpace(name),
|
||||
"itemType": normalizeProjectTreeItemType(itemType),
|
||||
}
|
||||
}
|
||||
|
||||
func slugDir(prefix, slug string) string {
|
||||
trimmedSlug := strings.TrimSpace(slug)
|
||||
if trimmedSlug == "" {
|
||||
|
||||
@@ -36,6 +36,24 @@ type moveProjectFolderRequest struct {
|
||||
TargetIndex int `json:"targetIndex"`
|
||||
}
|
||||
|
||||
type createProjectItemRequest struct {
|
||||
Name string `json:"name"`
|
||||
ParentFolderPath string `json:"parentFolderId"`
|
||||
ItemType string `json:"itemType"`
|
||||
}
|
||||
|
||||
type deleteProjectItemRequest struct {
|
||||
ItemPath string `json:"itemId"`
|
||||
}
|
||||
|
||||
type moveProjectItemRequest struct {
|
||||
ItemPath string `json:"itemId"`
|
||||
ItemStableID string `json:"itemNodeId"`
|
||||
ParentFolderPath string `json:"parentFolderId"`
|
||||
ParentStableID string `json:"parentNodeId"`
|
||||
TargetIndex int `json:"targetIndex"`
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleProjectFolders(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
@@ -238,6 +256,30 @@ func (routes apiRoutes) handleProjectTreeFolders(w http.ResponseWriter, r *http.
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleProjectTree(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
nodes, err := routes.bootstrapService().GetProjectTreeNodes(r.Context(), projectID)
|
||||
if err != nil {
|
||||
routes.writeProjectTreeError(w, r, err, "load")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": map[string]any{
|
||||
"projectId": projectID,
|
||||
"nodes": nodes,
|
||||
},
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleCreateProjectTreeFolder(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
@@ -392,6 +434,124 @@ func (routes apiRoutes) handleMoveProjectTreeFolder(w http.ResponseWriter, r *ht
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleCreateProjectTreeItem(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
payload, ok := decodeProjectItemRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.Name = strings.TrimSpace(payload.Name)
|
||||
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||
payload.ItemType = strings.TrimSpace(payload.ItemType)
|
||||
if payload.Name == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Item name is required.")
|
||||
return
|
||||
}
|
||||
if payload.ItemType == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Item type is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().CreateProjectTreeItem(r.Context(), bootstrapservice.CreateProjectItemInput{
|
||||
ProjectID: projectID,
|
||||
ParentFolderPath: payload.ParentFolderPath,
|
||||
Name: payload.Name,
|
||||
ItemType: payload.ItemType,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectTreeError(w, r, err, "persist")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusCreated, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-item-create",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleDeleteProjectTreeItem(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
payload := decodeDeleteProjectItemRequest(r)
|
||||
if strings.TrimSpace(payload.ItemPath) == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Item ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().DeleteProjectTreeItem(r.Context(), bootstrapservice.DeleteProjectItemInput{
|
||||
ProjectID: projectID,
|
||||
ItemPath: payload.ItemPath,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectTreeError(w, r, err, "delete")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-item-delete",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) handleMoveProjectTreeItem(w http.ResponseWriter, r *http.Request) {
|
||||
projectID := strings.TrimSpace(chi.URLParam(r, "projectId"))
|
||||
if projectID == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Project ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
payload, ok := decodeMoveProjectItemRequest(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
|
||||
payload.ItemPath = strings.TrimSpace(payload.ItemPath)
|
||||
payload.ItemStableID = strings.TrimSpace(payload.ItemStableID)
|
||||
payload.ParentFolderPath = strings.TrimSpace(payload.ParentFolderPath)
|
||||
payload.ParentStableID = strings.TrimSpace(payload.ParentStableID)
|
||||
if payload.ItemPath == "" {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", "Item ID is required.")
|
||||
return
|
||||
}
|
||||
|
||||
result, err := routes.bootstrapService().MoveProjectTreeItem(r.Context(), bootstrapservice.MoveProjectItemInput{
|
||||
ProjectID: projectID,
|
||||
ItemPath: payload.ItemPath,
|
||||
ItemStableID: payload.ItemStableID,
|
||||
ParentFolderPath: payload.ParentFolderPath,
|
||||
ParentStableID: payload.ParentStableID,
|
||||
TargetIndex: payload.TargetIndex,
|
||||
})
|
||||
if err != nil {
|
||||
routes.writeProjectTreeError(w, r, err, "move")
|
||||
return
|
||||
}
|
||||
|
||||
WriteJSON(w, http.StatusOK, map[string]any{
|
||||
"data": result,
|
||||
"meta": map[string]any{
|
||||
"resource": "project-tree-item-move",
|
||||
"persisted": true,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.Request, err error, operation string) {
|
||||
switch {
|
||||
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound):
|
||||
@@ -408,6 +568,22 @@ func (routes apiRoutes) writeProjectFolderError(w http.ResponseWriter, r *http.R
|
||||
}
|
||||
}
|
||||
|
||||
func (routes apiRoutes) writeProjectTreeError(w http.ResponseWriter, r *http.Request, err error, operation string) {
|
||||
switch {
|
||||
case errors.Is(err, bootstrapservice.ErrProjectNotFound), errors.Is(err, bootstrapservice.ErrProjectFolderNotFound), errors.Is(err, bootstrapservice.ErrProjectItemNotFound):
|
||||
WriteError(w, http.StatusNotFound, RequestIDFromContext(r.Context()), "not_found", err.Error())
|
||||
case errors.Is(err, bootstrapservice.ErrInvalidProjectFolderMove), errors.Is(err, bootstrapservice.ErrInvalidProjectItemMove):
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_request", err.Error())
|
||||
default:
|
||||
routes.cfg.Logger.Error(operation+" project tree", "error", err, "path", r.URL.Path)
|
||||
message := "Failed to " + operation + " project tree."
|
||||
if routes.cfg.Config.IsDevelopment() {
|
||||
message = message + " " + err.Error()
|
||||
}
|
||||
WriteError(w, http.StatusInternalServerError, RequestIDFromContext(r.Context()), "project_tree_"+operation+"_failed", message)
|
||||
}
|
||||
}
|
||||
|
||||
func decodeMoveProjectFolderRequest(w http.ResponseWriter, r *http.Request) (moveProjectFolderRequest, bool) {
|
||||
var payload moveProjectFolderRequest
|
||||
|
||||
@@ -438,6 +614,12 @@ func decodeDeleteProjectFolderRequest(r *http.Request) deleteProjectFolderReques
|
||||
}
|
||||
}
|
||||
|
||||
func decodeDeleteProjectItemRequest(r *http.Request) deleteProjectItemRequest {
|
||||
return deleteProjectItemRequest{
|
||||
ItemPath: strings.TrimSpace(r.URL.Query().Get("itemId")),
|
||||
}
|
||||
}
|
||||
|
||||
func decodeRenameProjectFolderRequest(w http.ResponseWriter, r *http.Request) (renameProjectFolderRequest, bool) {
|
||||
var payload renameProjectFolderRequest
|
||||
|
||||
@@ -485,3 +667,51 @@ func decodeProjectFolderRequest(w http.ResponseWriter, r *http.Request) (createP
|
||||
|
||||
return payload, true
|
||||
}
|
||||
|
||||
func decodeProjectItemRequest(w http.ResponseWriter, r *http.Request) (createProjectItemRequest, bool) {
|
||||
var payload createProjectItemRequest
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body is required and must be valid JSON.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must be valid JSON.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must contain a single JSON object.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
return payload, true
|
||||
}
|
||||
|
||||
func decodeMoveProjectItemRequest(w http.ResponseWriter, r *http.Request) (moveProjectItemRequest, bool) {
|
||||
var payload moveProjectItemRequest
|
||||
|
||||
decoder := json.NewDecoder(r.Body)
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(&payload); err != nil {
|
||||
if errors.Is(err, io.EOF) {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body is required and must be valid JSON.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must be valid JSON.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
if err := decoder.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
|
||||
WriteError(w, http.StatusBadRequest, RequestIDFromContext(r.Context()), "invalid_json", "The request body must contain a single JSON object.")
|
||||
return payload, false
|
||||
}
|
||||
|
||||
return payload, true
|
||||
}
|
||||
|
||||
@@ -39,11 +39,15 @@ func (routes apiRoutes) Register(router chi.Router) {
|
||||
projectRouter.Patch("/folders", routes.handleRenameProjectFolder)
|
||||
projectRouter.Patch("/folders/move", routes.handleMoveProjectFolder)
|
||||
projectRouter.Delete("/folders", routes.handleDeleteProjectFolder)
|
||||
projectRouter.Get("/tree", routes.handleProjectTree)
|
||||
projectRouter.Get("/tree/folders", routes.handleProjectTreeFolders)
|
||||
projectRouter.Post("/tree/folders", routes.handleCreateProjectTreeFolder)
|
||||
projectRouter.Patch("/tree/folders", routes.handleRenameProjectTreeFolder)
|
||||
projectRouter.Patch("/tree/folders/move", routes.handleMoveProjectTreeFolder)
|
||||
projectRouter.Delete("/tree/folders", routes.handleDeleteProjectTreeFolder)
|
||||
projectRouter.Post("/tree/items", routes.handleCreateProjectTreeItem)
|
||||
projectRouter.Patch("/tree/items/move", routes.handleMoveProjectTreeItem)
|
||||
projectRouter.Delete("/tree/items", routes.handleDeleteProjectTreeItem)
|
||||
})
|
||||
|
||||
if routes.cfg.Config.IsDevelopment() {
|
||||
|
||||
+228
-4
@@ -12,13 +12,13 @@
|
||||
}
|
||||
|
||||
.sheet {
|
||||
min-height: 100dvh;
|
||||
height: 100dvh;
|
||||
display: grid;
|
||||
grid-template-rows: auto minmax(0, 1fr);
|
||||
background:
|
||||
linear-gradient(180deg, color-mix(in srgb, var(--color-surface) 84%, transparent) 0%, transparent 8rem),
|
||||
color-mix(in srgb, var(--color-canvas) 97%, black 3%);
|
||||
overflow: clip;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.sheetHeader {
|
||||
@@ -98,15 +98,21 @@
|
||||
|
||||
.sheetBody {
|
||||
min-height: 0;
|
||||
display: grid;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: stretch;
|
||||
gap: var(--space-5);
|
||||
padding: var(--space-5) var(--space-5) calc(var(--space-12) + var(--space-10) + env(safe-area-inset-bottom, 0px));
|
||||
overflow: auto;
|
||||
overflow-y: auto;
|
||||
overflow-x: hidden;
|
||||
overscroll-behavior: contain;
|
||||
-webkit-overflow-scrolling: touch;
|
||||
}
|
||||
|
||||
.sectionBlock {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.treeList,
|
||||
@@ -187,4 +193,222 @@
|
||||
.treeListNested > .treeListItem > .treeRow {
|
||||
min-height: calc(var(--control-size-lg) + var(--space-1));
|
||||
}
|
||||
|
||||
.dialogLayer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
place-items: center;
|
||||
z-index: calc(var(--z-modal, 30) + 2);
|
||||
padding: var(--space-5);
|
||||
}
|
||||
|
||||
.dialogBackdrop {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border: 0;
|
||||
background: color-mix(in srgb, black 56%, transparent);
|
||||
}
|
||||
|
||||
.dialogCard {
|
||||
position: relative;
|
||||
width: min(100%, 28rem);
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
padding: var(--space-4);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
border-radius: var(--radius-xl);
|
||||
background: color-mix(in srgb, var(--color-surface) 94%, var(--color-canvas) 6%);
|
||||
box-shadow: var(--shadow-strong);
|
||||
}
|
||||
|
||||
.dialogCopy {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.dialogTitle {
|
||||
@include text-title;
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.dialogMessage {
|
||||
@include text-body;
|
||||
margin: 0;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.dialogInput {
|
||||
width: 100%;
|
||||
min-height: var(--control-size-lg);
|
||||
padding: 0 var(--space-3);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border-strong, var(--color-border)) 82%, transparent);
|
||||
border-radius: var(--radius-lg);
|
||||
background: color-mix(in srgb, var(--color-canvas) 92%, var(--color-surface) 8%);
|
||||
color: var(--color-text);
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.moveSheetLayer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
display: block;
|
||||
z-index: calc(var(--z-modal, 30) + 2);
|
||||
}
|
||||
|
||||
.moveSheet {
|
||||
position: absolute;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
max-height: calc(100dvh - (var(--space-12) * 2));
|
||||
display: grid;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-3) calc(var(--space-4) + env(safe-area-inset-bottom, 0px));
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
border-radius: var(--radius-xl) var(--radius-xl) 0 0;
|
||||
background: var(--color-surface);
|
||||
box-shadow: var(--shadow-strong);
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
.moveSheetHandle {
|
||||
width: var(--space-10);
|
||||
height: var(--space-1);
|
||||
margin: 0 auto;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--color-text-muted) 24%, transparent);
|
||||
}
|
||||
|
||||
.moveSheetHeader {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
padding-bottom: var(--space-3);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
}
|
||||
|
||||
.moveSheetHeaderCopy {
|
||||
display: grid;
|
||||
gap: calc(var(--space-1) / 2);
|
||||
}
|
||||
|
||||
.moveSheetEyebrow {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.moveSheetTitle {
|
||||
@include text-title;
|
||||
color: var(--color-text);
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.moveSheetMessage {
|
||||
@include text-body;
|
||||
margin: 0;
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.moveSection {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.moveSectionLabel {
|
||||
@include text-caption;
|
||||
padding-inline: var(--space-1);
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.moveDestinationList {
|
||||
display: grid;
|
||||
overflow: hidden;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
border-radius: var(--radius-lg);
|
||||
background: color-mix(in srgb, var(--color-surface) 88%, var(--color-surface-elevated, var(--color-surface)) 12%);
|
||||
max-height: min(20rem, 45vh);
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.moveDestinationButton {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
min-height: calc(var(--control-size-lg) + var(--space-2));
|
||||
padding: 0 var(--space-3);
|
||||
padding-left: calc(var(--space-3) + (var(--move-depth, 0) * var(--space-4)));
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--color-text);
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.moveDestinationButton:active {
|
||||
background: color-mix(in srgb, var(--color-text) 6%, transparent);
|
||||
}
|
||||
|
||||
.moveDestinationButton + .moveDestinationButton {
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 92%, transparent);
|
||||
}
|
||||
|
||||
.moveDestinationLabel {
|
||||
@include text-label;
|
||||
min-width: 0;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.moveDestinationMeta {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
flex: 0 0 auto;
|
||||
}
|
||||
|
||||
.moveSheetFooter {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
padding-top: var(--space-2);
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
}
|
||||
|
||||
.dialogActions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.dialogSecondaryButton,
|
||||
.dialogPrimaryButton {
|
||||
min-height: var(--control-size-md);
|
||||
padding: 0 var(--space-3);
|
||||
border-radius: 999px;
|
||||
font: inherit;
|
||||
font-weight: var(--font-weight-semibold);
|
||||
}
|
||||
|
||||
.dialogSecondaryButton {
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
background: color-mix(in srgb, var(--color-surface) 92%, transparent);
|
||||
color: var(--color-text-subtle);
|
||||
}
|
||||
|
||||
.dialogPrimaryButton {
|
||||
border: 1px solid color-mix(in srgb, var(--color-border-strong, var(--color-border)) 82%, transparent);
|
||||
background: color-mix(in srgb, var(--color-text) 10%, var(--color-surface) 90%);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.dialogDangerButton {
|
||||
border-color: color-mix(in srgb, var(--color-danger-border, var(--color-border-strong, var(--color-border))) 82%, transparent);
|
||||
background: color-mix(in srgb, var(--color-danger-text, #b42318) 12%, var(--color-surface) 88%);
|
||||
color: var(--color-danger-text, #b42318);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { For, Show, createSignal, type JSX } from "solid-js";
|
||||
import { Portal } from "solid-js/web";
|
||||
import { ChevronRight, Plus, X } from "../../../lib/icons";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import { createLongPressGesture } from "../createLongPressGesture";
|
||||
@@ -6,14 +7,17 @@ import {
|
||||
createWorkspaceStaticTarget,
|
||||
createWorkspaceSurfaceTarget,
|
||||
createWorkspaceTreeTarget,
|
||||
getWorkspaceItemTypeDefinition,
|
||||
getWorkspaceNodeIcon,
|
||||
workspaceStaticItems,
|
||||
type SidebarItem,
|
||||
type WorkspaceContextMenuAction,
|
||||
type WorkspaceContextMenuTarget,
|
||||
type WorkspaceItemTypeId,
|
||||
type WorkspaceStaticItem,
|
||||
type WorkspaceTreeNode,
|
||||
} from "../data/shell.data";
|
||||
import { useWorkspaceTreeData } from "../shared/useWorkspaceTreeData";
|
||||
import { WorkspaceMobileActionSheet } from "../WorkspaceMobileActionSheet/WorkspaceMobileActionSheet";
|
||||
import styles from "./MobileWorkspaceBrowser.module.scss";
|
||||
|
||||
@@ -22,6 +26,89 @@ type MobileWorkspaceBrowserProps = {
|
||||
onClose: VoidFunction;
|
||||
};
|
||||
|
||||
type MobileWorkspaceDialogState =
|
||||
| {
|
||||
kind: "text";
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel: string;
|
||||
initialValue: string;
|
||||
onConfirm: (value: string) => void;
|
||||
}
|
||||
| {
|
||||
kind: "confirm";
|
||||
title: string;
|
||||
message: string;
|
||||
confirmLabel: string;
|
||||
tone?: "danger";
|
||||
onConfirm: () => void;
|
||||
};
|
||||
|
||||
type MobileMoveTargetState = {
|
||||
kind: "folder" | "item";
|
||||
id: string;
|
||||
label: string;
|
||||
};
|
||||
|
||||
type MobileMoveDestination = {
|
||||
id: string | null;
|
||||
label: string;
|
||||
depth: number;
|
||||
meta?: string;
|
||||
};
|
||||
|
||||
const collectMoveDestinations = (
|
||||
nodes: readonly WorkspaceTreeNode[],
|
||||
movingTarget: MobileMoveTargetState,
|
||||
depth = 0,
|
||||
ancestorBlocked = false,
|
||||
): MobileMoveDestination[] => {
|
||||
const destinations: MobileMoveDestination[] = [];
|
||||
|
||||
for (const node of nodes) {
|
||||
if (node.kind !== "folder") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const isBlockedFolder = movingTarget.kind === "folder" && node.id === movingTarget.id;
|
||||
if (!ancestorBlocked && !isBlockedFolder) {
|
||||
destinations.push({
|
||||
id: node.id,
|
||||
label: node.label,
|
||||
depth,
|
||||
meta: "Folder",
|
||||
});
|
||||
}
|
||||
|
||||
destinations.push(
|
||||
...collectMoveDestinations(node.children ?? [], movingTarget, depth + 1, ancestorBlocked || isBlockedFolder),
|
||||
);
|
||||
}
|
||||
|
||||
return destinations;
|
||||
};
|
||||
|
||||
const findTreeNodeById = (nodes: readonly WorkspaceTreeNode[], nodeId: string): WorkspaceTreeNode | null => {
|
||||
for (const node of nodes) {
|
||||
if (node.id === nodeId) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node.kind !== "folder") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const nestedMatch = findTreeNodeById(node.children ?? [], nodeId);
|
||||
if (nestedMatch) {
|
||||
return nestedMatch;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
const isDangerDialogState = (state: MobileWorkspaceDialogState): boolean => state.kind === "confirm" && state.tone === "danger";
|
||||
|
||||
const TreeRow = (props: { node: WorkspaceTreeNode; depth?: number }): JSX.Element => {
|
||||
const depth = props.depth ?? 0;
|
||||
const Icon = getWorkspaceNodeIcon(props.node);
|
||||
@@ -76,6 +163,7 @@ const StaticRow = (props: { item: SidebarItem }): JSX.Element => {
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
const WorkspaceStaticRow = (props: {
|
||||
item: WorkspaceStaticItem;
|
||||
onOpenActionSheet: (target: WorkspaceContextMenuTarget) => void;
|
||||
@@ -149,21 +237,240 @@ const WorkspaceTreeBranch = (props: {
|
||||
export const MobileWorkspaceBrowser = (props: MobileWorkspaceBrowserProps): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
const [actionSheetTarget, setActionSheetTarget] = createSignal<WorkspaceContextMenuTarget | null>(null);
|
||||
const sectionNodes = () => appShellData.workspaceTree().filter((node) => (node.children?.length ?? 0) > 0);
|
||||
const looseNodes = () => appShellData.workspaceTree().filter((node) => (node.children?.length ?? 0) === 0);
|
||||
const [dialogState, setDialogState] = createSignal<MobileWorkspaceDialogState | null>(null);
|
||||
const [dialogValue, setDialogValue] = createSignal("");
|
||||
const [moveTarget, setMoveTarget] = createSignal<MobileMoveTargetState | null>(null);
|
||||
const { workspaceTreeNodes, createFolder, renameFolder, deleteFolder, moveFolder, createItem, deleteItem, moveItem } = useWorkspaceTreeData({
|
||||
activeProjectId: () => appShellData.activeProject().id,
|
||||
fallbackWorkspaceTree: () => appShellData.workspaceTree(),
|
||||
});
|
||||
const workspaceTarget = () => createWorkspaceSurfaceTarget(appShellData.activeProject());
|
||||
|
||||
const moveDestinations = () => {
|
||||
const target = moveTarget();
|
||||
if (!target) {
|
||||
return [] as MobileMoveDestination[];
|
||||
}
|
||||
|
||||
return [
|
||||
{ id: null, label: "Items root", depth: 0, meta: "Root" },
|
||||
...collectMoveDestinations(workspaceTreeNodes(), target),
|
||||
];
|
||||
};
|
||||
|
||||
const resolveCreateItemType = (actionId: string): WorkspaceItemTypeId | null => {
|
||||
switch (actionId) {
|
||||
case "create-doc":
|
||||
return "core.doc";
|
||||
case "create-board":
|
||||
return "core.board.kanban";
|
||||
case "create-list-board":
|
||||
return "core.board.list";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const createPersistedItem = (itemType: WorkspaceItemTypeId, parentId: string | null): void => {
|
||||
const definition = getWorkspaceItemTypeDefinition(itemType);
|
||||
void createItem(definition.defaultCreateLabel, itemType, parentId);
|
||||
};
|
||||
|
||||
const openActionSheet = (target: WorkspaceContextMenuTarget): void => {
|
||||
setActionSheetTarget(target);
|
||||
};
|
||||
|
||||
const closeActionSheet = (): void => {
|
||||
setActionSheetTarget(null);
|
||||
};
|
||||
|
||||
const closeMoveSheet = (): void => {
|
||||
setMoveTarget(null);
|
||||
};
|
||||
|
||||
const openWorkspaceActionSheet = (): void => {
|
||||
openActionSheet(workspaceTarget());
|
||||
};
|
||||
|
||||
const handleActionSelect = (_action: WorkspaceContextMenuAction, _target: WorkspaceContextMenuTarget): void => {
|
||||
// Mobile first pass only establishes the action-sheet IA and long-press behavior.
|
||||
const closeDialog = (): void => {
|
||||
setDialogState(null);
|
||||
setDialogValue("");
|
||||
};
|
||||
|
||||
const openMoveSheet = (target: MobileMoveTargetState): void => {
|
||||
setMoveTarget(target);
|
||||
};
|
||||
|
||||
const openTextDialog = (config: Omit<Extract<MobileWorkspaceDialogState, { kind: "text" }>, "kind">): void => {
|
||||
setDialogValue(config.initialValue);
|
||||
setDialogState({ kind: "text", ...config });
|
||||
};
|
||||
|
||||
const openConfirmDialog = (config: Omit<Extract<MobileWorkspaceDialogState, { kind: "confirm" }>, "kind">): void => {
|
||||
setDialogValue("");
|
||||
setDialogState({ kind: "confirm", ...config });
|
||||
};
|
||||
|
||||
const submitDialog = (): void => {
|
||||
const state = dialogState();
|
||||
if (!state) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (state.kind === "text") {
|
||||
const value = dialogValue().trim();
|
||||
if (!value) {
|
||||
return;
|
||||
}
|
||||
|
||||
closeDialog();
|
||||
state.onConfirm(value);
|
||||
return;
|
||||
}
|
||||
|
||||
closeDialog();
|
||||
state.onConfirm();
|
||||
};
|
||||
|
||||
const handleMoveDestinationSelect = (destinationId: string | null): void => {
|
||||
const target = moveTarget();
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
|
||||
const destinationNode = destinationId ? findTreeNodeById(workspaceTreeNodes(), destinationId) : null;
|
||||
const targetIndex = destinationNode?.kind === "folder"
|
||||
? destinationNode.children?.length ?? 0
|
||||
: destinationId
|
||||
? 0
|
||||
: workspaceTreeNodes().length;
|
||||
|
||||
closeMoveSheet();
|
||||
|
||||
if (target.kind === "folder") {
|
||||
void moveFolder(target.id, destinationId, targetIndex);
|
||||
return;
|
||||
}
|
||||
|
||||
void moveItem(target.id, destinationId, targetIndex);
|
||||
};
|
||||
|
||||
const handleActionSelect = (action: WorkspaceContextMenuAction, target: WorkspaceContextMenuTarget): void => {
|
||||
const createItemType = resolveCreateItemType(action.id);
|
||||
if (createItemType) {
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
case "home":
|
||||
createPersistedItem(createItemType, null);
|
||||
return;
|
||||
case "folder":
|
||||
createPersistedItem(createItemType, target.id);
|
||||
return;
|
||||
case "settings":
|
||||
case "item":
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
switch (action.id) {
|
||||
case "new-folder": {
|
||||
if (target.kind === "settings" || target.kind === "item") {
|
||||
return;
|
||||
}
|
||||
|
||||
openTextDialog({
|
||||
title: "New folder",
|
||||
message: target.kind === "folder" ? `Create a folder inside "${target.label}".` : "Create a folder at the root of Items.",
|
||||
confirmLabel: "Create",
|
||||
initialValue: "Untitled folder",
|
||||
onConfirm: (name) => {
|
||||
void createFolder(name, target.kind === "folder" ? target.id : null);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "rename-folder": {
|
||||
if (target.kind !== "folder") {
|
||||
return;
|
||||
}
|
||||
|
||||
openTextDialog({
|
||||
title: "Rename folder",
|
||||
message: `Update the name for "${target.label}".`,
|
||||
confirmLabel: "Save",
|
||||
initialValue: target.label,
|
||||
onConfirm: (name) => {
|
||||
if (name === target.label) {
|
||||
return;
|
||||
}
|
||||
void renameFolder(target.id, name);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "move-folder": {
|
||||
if (target.kind !== "folder") {
|
||||
return;
|
||||
}
|
||||
|
||||
openMoveSheet({
|
||||
kind: "folder",
|
||||
id: target.id,
|
||||
label: target.label,
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "delete-folder": {
|
||||
if (target.kind !== "folder") {
|
||||
return;
|
||||
}
|
||||
|
||||
openConfirmDialog({
|
||||
title: "Delete folder?",
|
||||
message: `"${target.label}" and everything inside it will be removed.`,
|
||||
confirmLabel: "Delete",
|
||||
tone: "danger",
|
||||
onConfirm: () => {
|
||||
void deleteFolder(target.id);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "move-doc":
|
||||
case "move-board":
|
||||
case "move-list-board": {
|
||||
if (target.kind !== "item") {
|
||||
return;
|
||||
}
|
||||
|
||||
openMoveSheet({
|
||||
kind: "item",
|
||||
id: target.id,
|
||||
label: target.label,
|
||||
});
|
||||
return;
|
||||
}
|
||||
case "delete-doc":
|
||||
case "delete-board":
|
||||
case "delete-list-board": {
|
||||
if (target.kind !== "item") {
|
||||
return;
|
||||
}
|
||||
|
||||
openConfirmDialog({
|
||||
title: "Delete item?",
|
||||
message: `"${target.label}" will be removed from the project tree.`,
|
||||
confirmLabel: "Delete",
|
||||
tone: "danger",
|
||||
onConfirm: () => {
|
||||
void deleteItem(target.id);
|
||||
},
|
||||
});
|
||||
return;
|
||||
}
|
||||
default:
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
const workspaceLongPress = createLongPressGesture({
|
||||
@@ -221,26 +528,110 @@ export const MobileWorkspaceBrowser = (props: MobileWorkspaceBrowserProps): JSX.
|
||||
<section class={styles.sectionBlock} data-slot="mobile-workspace-section" data-section-id="items">
|
||||
<span class={styles.sectionLabel}>Items</span>
|
||||
<ul class={styles.treeList} data-slot="mobile-workspace-list" data-section-id="items">
|
||||
<WorkspaceTreeBranch nodes={sectionNodes()} onOpenActionSheet={openActionSheet} />
|
||||
<WorkspaceTreeBranch nodes={workspaceTreeNodes()} onOpenActionSheet={openActionSheet} />
|
||||
</ul>
|
||||
</section>
|
||||
|
||||
<Show when={looseNodes().length > 0}>
|
||||
<section class={styles.sectionBlock} data-slot="mobile-workspace-section" data-section-id="more">
|
||||
<span class={styles.sectionLabel}>More</span>
|
||||
<ul class={styles.treeList} data-slot="mobile-workspace-list" data-section-id="more">
|
||||
<WorkspaceTreeBranch nodes={looseNodes()} onOpenActionSheet={openActionSheet} />
|
||||
</ul>
|
||||
</section>
|
||||
</Show>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<WorkspaceMobileActionSheet
|
||||
target={actionSheetTarget()}
|
||||
onClose={closeActionSheet}
|
||||
onSelect={handleActionSelect}
|
||||
<WorkspaceMobileActionSheet target={actionSheetTarget()} onClose={closeActionSheet} onSelect={handleActionSelect} />
|
||||
|
||||
<Show when={moveTarget()}>
|
||||
{(state): JSX.Element => (
|
||||
<Portal>
|
||||
<div class={styles.moveSheetLayer} data-ui="mobile-workspace-move-sheet">
|
||||
<button class={styles.dialogBackdrop} type="button" aria-label="Close move sheet" onClick={closeMoveSheet} />
|
||||
<section class={styles.moveSheet} aria-label={`Move ${state().label}`}>
|
||||
<div class={styles.moveSheetHandle} aria-hidden="true" />
|
||||
<div class={styles.moveSheetHeader}>
|
||||
<div class={styles.moveSheetHeaderCopy}>
|
||||
<span class={styles.moveSheetEyebrow}>Move {state().kind}</span>
|
||||
<strong class={styles.moveSheetTitle}>{state().label}</strong>
|
||||
<p class={styles.moveSheetMessage}>Choose a new location in the project tree.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class={styles.moveSection}>
|
||||
<span class={styles.moveSectionLabel}>Destination</span>
|
||||
<div class={styles.moveDestinationList}>
|
||||
<For each={moveDestinations()}>
|
||||
{(destination): JSX.Element => (
|
||||
<button
|
||||
type="button"
|
||||
class={styles.moveDestinationButton}
|
||||
style={{ "--move-depth": `${destination.depth}` }}
|
||||
onClick={(): void => handleMoveDestinationSelect(destination.id)}
|
||||
>
|
||||
<span class={styles.moveDestinationLabel}>{destination.label}</span>
|
||||
<Show when={destination.meta}>
|
||||
<span class={styles.moveDestinationMeta}>{destination.meta}</span>
|
||||
</Show>
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class={styles.moveSheetFooter}>
|
||||
<button class={styles.dialogSecondaryButton} type="button" onClick={closeMoveSheet}>
|
||||
Cancel
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Portal>
|
||||
)}
|
||||
</Show>
|
||||
|
||||
<Show when={dialogState()}>
|
||||
{(state): JSX.Element => (
|
||||
<Portal>
|
||||
<div class={styles.dialogLayer} data-ui="mobile-workspace-dialog">
|
||||
<button class={styles.dialogBackdrop} type="button" aria-label="Close dialog" onClick={closeDialog} />
|
||||
<section class={styles.dialogCard} aria-label={state().title}>
|
||||
<div class={styles.dialogCopy}>
|
||||
<strong class={styles.dialogTitle}>{state().title}</strong>
|
||||
<p class={styles.dialogMessage}>{state().message}</p>
|
||||
</div>
|
||||
|
||||
<Show when={state().kind === "text"}>
|
||||
<input
|
||||
class={styles.dialogInput}
|
||||
type="text"
|
||||
value={dialogValue()}
|
||||
onInput={(event): void => {
|
||||
setDialogValue(event.currentTarget.value);
|
||||
}}
|
||||
onKeyDown={(event): void => {
|
||||
if (event.key === "Enter") {
|
||||
event.preventDefault();
|
||||
submitDialog();
|
||||
}
|
||||
}}
|
||||
autofocus
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<div class={styles.dialogActions}>
|
||||
<button class={styles.dialogSecondaryButton} type="button" onClick={closeDialog}>
|
||||
Cancel
|
||||
</button>
|
||||
<button
|
||||
classList={{
|
||||
[styles.dialogPrimaryButton]: true,
|
||||
[styles.dialogDangerButton]: isDangerDialogState(state()),
|
||||
}}
|
||||
type="button"
|
||||
onClick={submitDialog}
|
||||
>
|
||||
{state().confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</Portal>
|
||||
)}
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
);
|
||||
|
||||
+10
@@ -70,6 +70,15 @@ export const createProjectContextMenuController = () => {
|
||||
setMenuState({ target, x: event.clientX, y: event.clientY });
|
||||
};
|
||||
|
||||
const openMenuFromElement = (element: HTMLElement, target: ProjectMenuTarget): void => {
|
||||
const rect = element.getBoundingClientRect();
|
||||
setMenuState({
|
||||
target,
|
||||
x: rect.left + rect.width / 2,
|
||||
y: rect.top + rect.height / 2,
|
||||
});
|
||||
};
|
||||
|
||||
createEffect(() => {
|
||||
if (!menuState() || typeof window === "undefined") {
|
||||
return;
|
||||
@@ -112,6 +121,7 @@ export const createProjectContextMenuController = () => {
|
||||
return {
|
||||
menuState,
|
||||
openMenu,
|
||||
openMenuFromElement,
|
||||
closeMenu,
|
||||
setMenuRef: (element: HTMLDivElement): void => {
|
||||
menuRef = element;
|
||||
|
||||
@@ -315,6 +315,26 @@
|
||||
@include treeNav.item-meta;
|
||||
}
|
||||
|
||||
.dragGhostLayer {
|
||||
@include treeNav.drag-ghost-layer;
|
||||
}
|
||||
|
||||
.dragGhost {
|
||||
@include treeNav.drag-ghost;
|
||||
}
|
||||
|
||||
.dragGhostCopy {
|
||||
@include treeNav.drag-ghost-copy;
|
||||
}
|
||||
|
||||
.dragGhostTitle {
|
||||
@include treeNav.drag-ghost-title;
|
||||
}
|
||||
|
||||
.dragGhostMeta {
|
||||
@include treeNav.drag-ghost-meta;
|
||||
}
|
||||
|
||||
@media (max-width: 720px) {
|
||||
.rootCompact .scrim,
|
||||
.rootCompact .drawer {
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
// Path: Frontend/src/components/shell/ProjectSelector/ProjectSelector.tsx
|
||||
|
||||
import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
||||
import { ChevronDown, ChevronRight, Folder, LayoutGrid, ListCollapse, UnfoldVertical } from "../../../lib/icons";
|
||||
import { Portal } from "solid-js/web";
|
||||
import { ChevronDown, ChevronRight, Folder, LayoutGrid, ListCollapse, Plus, UnfoldVertical } from "../../../lib/icons";
|
||||
import { ProjectContextMenu } from "../ProjectContextMenu/ProjectContextMenu";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
@@ -85,6 +86,11 @@ type ProjectDragState = {
|
||||
dropTarget: ProjectDragTarget | null;
|
||||
};
|
||||
|
||||
type DragGhostPosition = {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
|
||||
const LONG_PRESS_MS = 320;
|
||||
|
||||
const getProjectTreeNodeId = (node: ProjectTreeNode): string =>
|
||||
@@ -378,6 +384,7 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
const [pendingFolderRename, setPendingFolderRename] = createSignal<PendingProjectFolderRename | null>(null);
|
||||
const [pendingFolderRenameName, setPendingFolderRenameName] = createSignal("");
|
||||
const [dragState, setDragState] = createSignal<ProjectDragState | null>(null);
|
||||
const [dragGhostPosition, setDragGhostPosition] = createSignal<DragGhostPosition>({ x: 0, y: 0 });
|
||||
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
||||
let rootRef: HTMLDivElement | undefined;
|
||||
let triggerRef: HTMLButtonElement | undefined;
|
||||
@@ -395,6 +402,28 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
}
|
||||
};
|
||||
|
||||
const updateDragGhostPosition = (x: number, y: number): void => {
|
||||
setDragGhostPosition({ x: x + 18, y: y + 18 });
|
||||
};
|
||||
|
||||
const draggedNode = (): ProjectTreeNode | null => {
|
||||
const currentDragState = dragState();
|
||||
if (!currentDragState) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return findTreeNodeLocation(projectTreeNodes(), currentDragState.draggedNodeId, projectTreeAdapter)?.node ?? null;
|
||||
};
|
||||
|
||||
const draggedNodeMeta = (): string => {
|
||||
const node = draggedNode();
|
||||
if (!node) {
|
||||
return "";
|
||||
}
|
||||
|
||||
return node.kind === "folder" ? "Folder" : "Project";
|
||||
};
|
||||
|
||||
const suppressTreeClickTemporarily = (): void => {
|
||||
setSuppressNextTreeClick(true);
|
||||
|
||||
@@ -653,9 +682,18 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
triggerRef?.focus();
|
||||
};
|
||||
|
||||
const handlePointerMove = (event: PointerEvent): void => {
|
||||
if (!dragState()) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateDragGhostPosition(event.clientX, event.clientY);
|
||||
};
|
||||
|
||||
document.addEventListener("pointerdown", handlePointerDown);
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
window.addEventListener("pointercancel", handlePointerUp);
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("keydown", handleEscape);
|
||||
|
||||
onCleanup(() => {
|
||||
@@ -666,6 +704,7 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
document.removeEventListener("pointerdown", handlePointerDown);
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("keydown", handleEscape);
|
||||
});
|
||||
});
|
||||
@@ -941,6 +980,10 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
contextMenu.openMenu(event, createProjectSurfaceTarget("Projects"));
|
||||
};
|
||||
|
||||
const openRootCreateMenu = (element: HTMLElement): void => {
|
||||
contextMenu.openMenuFromElement(element, createProjectSurfaceTarget("Projects"));
|
||||
};
|
||||
|
||||
const treeControlLabel = (): string =>
|
||||
areAllFoldersCollapsed() ? "Expand all folders" : "Collapse all folders";
|
||||
|
||||
@@ -949,6 +992,7 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
return;
|
||||
}
|
||||
|
||||
updateDragGhostPosition(event.clientX, event.clientY);
|
||||
clearLongPressTimer();
|
||||
longPressTimer = window.setTimeout(() => {
|
||||
suppressTreeClickTemporarily();
|
||||
@@ -1062,6 +1106,18 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
</Show>
|
||||
|
||||
<div class={styles.treeControls}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.treeControlButton}
|
||||
onClick={(event): void => {
|
||||
event.stopPropagation();
|
||||
openRootCreateMenu(event.currentTarget);
|
||||
}}
|
||||
aria-label="Create in Projects"
|
||||
title="Create"
|
||||
>
|
||||
<Plus size={16} strokeWidth={2.25} />
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.treeControlButton}
|
||||
@@ -1129,6 +1185,32 @@ export const ProjectSelector = (props: ProjectSelectorProps): JSX.Element => {
|
||||
onClose={contextMenu.closeMenu}
|
||||
onSelect={handleContextActionSelect}
|
||||
/>
|
||||
|
||||
<Show when={draggedNode()} keyed>
|
||||
{(node): JSX.Element => {
|
||||
const GhostIcon = node.kind === "folder" ? Folder : LayoutGrid;
|
||||
|
||||
return (
|
||||
<Portal>
|
||||
<div class={styles.dragGhostLayer} aria-hidden="true">
|
||||
<div
|
||||
class={styles.dragGhost}
|
||||
style={{
|
||||
"--drag-ghost-x": `${dragGhostPosition().x}px`,
|
||||
"--drag-ghost-y": `${dragGhostPosition().y}px`,
|
||||
}}
|
||||
>
|
||||
<GhostIcon class={styles.icon} size={18} strokeWidth={2} />
|
||||
<div class={styles.dragGhostCopy}>
|
||||
<div class={styles.dragGhostTitle}>{node.kind === "folder" ? node.label : node.item.name}</div>
|
||||
<div class={styles.dragGhostMeta}>{draggedNodeMeta()}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Portal>
|
||||
);
|
||||
}}
|
||||
</Show>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -124,6 +124,53 @@
|
||||
padding: 0 var(--space-3);
|
||||
}
|
||||
|
||||
.treeSectionHeader {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-2);
|
||||
margin-top: var(--space-3);
|
||||
margin-bottom: var(--space-2);
|
||||
padding-right: var(--space-1);
|
||||
}
|
||||
|
||||
.treeSectionHeader .treeSectionLabel {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.treeControls {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-1);
|
||||
justify-content: flex-end;
|
||||
padding-right: var(--space-2);
|
||||
}
|
||||
|
||||
.treeControlButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
width: calc(var(--control-size-md) - var(--space-1));
|
||||
height: calc(var(--control-size-md) - var(--space-1));
|
||||
padding: 0;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 46%, transparent);
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--color-surface) 95%, transparent);
|
||||
color: var(--color-text-muted);
|
||||
transition:
|
||||
border-color 160ms var(--easing-standard),
|
||||
background 160ms var(--easing-standard),
|
||||
color 160ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.treeControlButton:hover,
|
||||
.treeControlButton:focus-visible {
|
||||
border-color: color-mix(in srgb, var(--color-border-strong) 56%, transparent);
|
||||
background: var(--color-surface-hover);
|
||||
color: var(--color-text);
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.treeList {
|
||||
@include treeNav.tree-list;
|
||||
}
|
||||
@@ -214,6 +261,26 @@
|
||||
@include treeNav.item-meta;
|
||||
}
|
||||
|
||||
.dragGhostLayer {
|
||||
@include treeNav.drag-ghost-layer;
|
||||
}
|
||||
|
||||
.dragGhost {
|
||||
@include treeNav.drag-ghost;
|
||||
}
|
||||
|
||||
.dragGhostCopy {
|
||||
@include treeNav.drag-ghost-copy;
|
||||
}
|
||||
|
||||
.dragGhostTitle {
|
||||
@include treeNav.drag-ghost-title;
|
||||
}
|
||||
|
||||
.dragGhostMeta {
|
||||
@include treeNav.drag-ghost-meta;
|
||||
}
|
||||
|
||||
.sidebarCollapsed {
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3) var(--space-2);
|
||||
@@ -247,6 +314,7 @@
|
||||
|
||||
.sidebarCollapsed .label,
|
||||
.sidebarCollapsed .itemMeta,
|
||||
.sidebarCollapsed .treeSectionHeader,
|
||||
.sidebarCollapsed .treeSectionLabel,
|
||||
.sidebarCollapsed .treeList {
|
||||
display: none;
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
// Path: Frontend/src/components/shell/WorkspaceSidebar/WorkspaceSidebar.tsx
|
||||
|
||||
import { For, Show, createEffect, createSignal, onCleanup, onMount, type JSX } from "solid-js";
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
import { ChevronLeft, ChevronRight, Folder, ListCollapse, UnfoldVertical } from "../../../lib/icons";
|
||||
import { Portal } from "solid-js/web";
|
||||
import { ChevronLeft, ChevronRight, Folder, ListCollapse, Plus, UnfoldVertical } from "../../../lib/icons";
|
||||
import { useAppShellData } from "../data/app-shell.context";
|
||||
import { ProjectSelector } from "../ProjectSelector/ProjectSelector";
|
||||
import {
|
||||
@@ -21,13 +21,16 @@ import {
|
||||
createWorkspaceSurfaceTarget,
|
||||
createWorkspaceTreeTarget,
|
||||
getWorkspaceNodeIcon,
|
||||
getWorkspaceItemTypeDefinition,
|
||||
workspaceSidebarHeaderActions,
|
||||
workspaceStaticItems,
|
||||
type WorkspaceContextMenuAction,
|
||||
type WorkspaceContextMenuTarget,
|
||||
type WorkspaceItemTypeId,
|
||||
type WorkspaceStaticItem,
|
||||
type WorkspaceTreeNode,
|
||||
} from "../data/shell.data";
|
||||
import { useWorkspaceTreeData } from "../shared/useWorkspaceTreeData";
|
||||
import { WorkspaceContextMenu } from "../WorkspaceContextMenu/WorkspaceContextMenu";
|
||||
import { createWorkspaceContextMenuController } from "../WorkspaceContextMenu/createWorkspaceContextMenuController";
|
||||
import styles from "./WorkspaceSidebar.module.scss";
|
||||
@@ -50,23 +53,9 @@ type WorkspaceDragState = {
|
||||
dropTarget: WorkspaceDragTarget | null;
|
||||
};
|
||||
|
||||
type PersistedWorkspaceFolderRecord = {
|
||||
id: string;
|
||||
path: string;
|
||||
label: string;
|
||||
children?: PersistedWorkspaceFolderRecord[];
|
||||
};
|
||||
|
||||
type WorkspaceFoldersResponse = {
|
||||
data?: {
|
||||
folders?: PersistedWorkspaceFolderRecord[];
|
||||
renamedFolder?: PersistedWorkspaceFolderRecord;
|
||||
movedFolder?: PersistedWorkspaceFolderRecord;
|
||||
previousFolderId?: string;
|
||||
previousFolderPath?: string;
|
||||
};
|
||||
error?: string;
|
||||
message?: string;
|
||||
type DragGhostPosition = {
|
||||
x: number;
|
||||
y: number;
|
||||
};
|
||||
|
||||
type PendingWorkspaceFolderRename = {
|
||||
@@ -78,21 +67,6 @@ const LONG_PRESS_MS = 320;
|
||||
|
||||
const getWorkspaceTreeNodeId = (node: WorkspaceTreeNode): string => node.id;
|
||||
|
||||
const buildPersistedWorkspaceFolderNodes = (
|
||||
folders: readonly PersistedWorkspaceFolderRecord[],
|
||||
): WorkspaceTreeNode[] =>
|
||||
folders.map((folder) => ({
|
||||
id: folder.id,
|
||||
path: folder.path,
|
||||
label: folder.label,
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: buildPersistedWorkspaceFolderNodes(folder.children ?? []),
|
||||
}));
|
||||
|
||||
const readPersistedWorkspaceFolders = (body: WorkspaceFoldersResponse): PersistedWorkspaceFolderRecord[] =>
|
||||
Array.isArray(body.data?.folders) ? body.data.folders : [];
|
||||
|
||||
const countWorkspaceFolderSiblingsBeforeIndex = (
|
||||
siblings: readonly WorkspaceTreeNode[],
|
||||
index: number,
|
||||
@@ -378,17 +352,31 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
const activeProject = () => appShellData.activeProject();
|
||||
const [isProjectDrawerOpen, setIsProjectDrawerOpen] = createSignal(false);
|
||||
const [workspaceTreeNodes, setWorkspaceTreeNodes] = createSignal<readonly WorkspaceTreeNode[]>(appShellData.workspaceTree());
|
||||
const [persistedFolders, setPersistedFolders] = createSignal<readonly PersistedWorkspaceFolderRecord[]>([]);
|
||||
const [collapsedFolderIds, setCollapsedFolderIds] = createSignal<readonly string[]>([]);
|
||||
const [pendingFolderDraft, setPendingFolderDraft] = createSignal<PendingWorkspaceFolderDraft | null>(null);
|
||||
const [pendingFolderName, setPendingFolderName] = createSignal("");
|
||||
const [pendingFolderRename, setPendingFolderRename] = createSignal<PendingWorkspaceFolderRename | null>(null);
|
||||
const [pendingFolderRenameName, setPendingFolderRenameName] = createSignal("");
|
||||
const [dragState, setDragState] = createSignal<WorkspaceDragState | null>(null);
|
||||
const [dragGhostPosition, setDragGhostPosition] = createSignal<DragGhostPosition>({ x: 0, y: 0 });
|
||||
const [suppressNextTreeClick, setSuppressNextTreeClick] = createSignal(false);
|
||||
let lastSelectedProjectId: string | null = null;
|
||||
let latestPersistedFoldersRequest = 0;
|
||||
const {
|
||||
workspaceTreeNodes,
|
||||
setWorkspaceTreeNodes,
|
||||
resolveFolderPath,
|
||||
resolveItemPath,
|
||||
createFolder,
|
||||
renameFolder,
|
||||
deleteFolder,
|
||||
moveFolder,
|
||||
createItem,
|
||||
deleteItem,
|
||||
moveItem,
|
||||
} = useWorkspaceTreeData({
|
||||
activeProjectId: () => activeProject()?.id ?? "",
|
||||
fallbackWorkspaceTree: () => appShellData.workspaceTree(),
|
||||
});
|
||||
const contextMenu = createWorkspaceContextMenuController();
|
||||
let longPressTimer: number | undefined;
|
||||
let suppressClickTimer: number | undefined;
|
||||
@@ -430,54 +418,32 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
setPendingFolderRenameName("");
|
||||
setDragState(null);
|
||||
};
|
||||
const syncWorkspaceTree = (): void => {
|
||||
const nextTree = activeProject()?.id
|
||||
? buildPersistedWorkspaceFolderNodes(persistedFolders())
|
||||
: appShellData.workspaceTree();
|
||||
const availableFolderIds = new Set(collectBranchNodeIds(nextTree, workspaceTreeAdapter));
|
||||
|
||||
setWorkspaceTreeNodes(nextTree);
|
||||
const syncCollapsedFolderIds = (): void => {
|
||||
const availableFolderIds = new Set(collectBranchNodeIds(workspaceTreeNodes(), workspaceTreeAdapter));
|
||||
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;
|
||||
const updateDragGhostPosition = (x: number, y: number): void => {
|
||||
setDragGhostPosition({ x: x + 18, y: y + 18 });
|
||||
};
|
||||
const draggedNode = (): WorkspaceTreeNode | null => {
|
||||
const currentDragState = dragState();
|
||||
if (!currentDragState) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!isUuidString(projectId)) {
|
||||
setPersistedFolders([]);
|
||||
return;
|
||||
return findTreeNodeLocation(workspaceTreeNodes(), currentDragState.draggedNodeId, workspaceTreeAdapter)?.node ?? null;
|
||||
};
|
||||
const draggedNodeMeta = (): string => {
|
||||
const node = draggedNode();
|
||||
if (!node) {
|
||||
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 (node.kind === "folder") {
|
||||
return "Folder";
|
||||
}
|
||||
|
||||
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([]);
|
||||
}
|
||||
return getWorkspaceItemTypeDefinition(node.itemType).label;
|
||||
};
|
||||
const clearLongPressTimer = (): void => {
|
||||
if (longPressTimer !== undefined) {
|
||||
@@ -499,7 +465,7 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
};
|
||||
|
||||
createEffect(() => {
|
||||
syncWorkspaceTree();
|
||||
syncCollapsedFolderIds();
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
@@ -518,11 +484,15 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
resetWorkspaceTreeInteractionState();
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
void loadPersistedFolders(activeProject()?.id ?? "");
|
||||
});
|
||||
|
||||
onMount(() => {
|
||||
const handlePointerMove = (event: PointerEvent): void => {
|
||||
if (!dragState()) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateDragGhostPosition(event.clientX, event.clientY);
|
||||
};
|
||||
|
||||
const handlePointerUp = (): void => {
|
||||
clearLongPressTimer();
|
||||
|
||||
@@ -541,13 +511,11 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
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 ?? []
|
||||
@@ -563,16 +531,24 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
if (
|
||||
canPersistMove &&
|
||||
draggedLocation?.node.kind === "folder" &&
|
||||
draggedFolderPath &&
|
||||
(!previewLocation?.parentId || persistedParentLocation?.node.kind === "folder")
|
||||
) {
|
||||
void movePersistedFolder(
|
||||
draggedFolderPath,
|
||||
persistedParentFolderPath,
|
||||
void moveFolder(
|
||||
draggedLocation.node.id,
|
||||
persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.id : null,
|
||||
targetIndex,
|
||||
);
|
||||
} else if (
|
||||
canPersistMove &&
|
||||
draggedLocation?.node.kind === "item" &&
|
||||
resolveItemPath(draggedLocation.node.id) &&
|
||||
(!previewLocation?.parentId || persistedParentLocation?.node.kind === "folder")
|
||||
) {
|
||||
void moveItem(
|
||||
draggedLocation.node.id,
|
||||
persistedParentLocation?.node.kind === "folder" ? persistedParentLocation.node.id : null,
|
||||
previewLocation?.index ?? 0,
|
||||
);
|
||||
} else {
|
||||
setWorkspaceTreeNodes((current) =>
|
||||
moveTreeNode(current, nextDragState.draggedNodeId, nextDragState.dropTarget as WorkspaceDragTarget, workspaceTreeAdapter),
|
||||
@@ -596,6 +572,7 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
|
||||
window.addEventListener("pointerup", handlePointerUp);
|
||||
window.addEventListener("pointercancel", handlePointerUp);
|
||||
window.addEventListener("pointermove", handlePointerMove);
|
||||
window.addEventListener("keydown", handleEscape);
|
||||
|
||||
onCleanup(() => {
|
||||
@@ -605,6 +582,7 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
}
|
||||
window.removeEventListener("pointerup", handlePointerUp);
|
||||
window.removeEventListener("pointercancel", handlePointerUp);
|
||||
window.removeEventListener("pointermove", handlePointerMove);
|
||||
window.removeEventListener("keydown", handleEscape);
|
||||
});
|
||||
});
|
||||
@@ -627,11 +605,6 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
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 draft = pendingFolderDraft();
|
||||
@@ -658,104 +631,17 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
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));
|
||||
const created = await createFolder(name, draft.parentId);
|
||||
if (created) {
|
||||
setPendingFolderDraft(null);
|
||||
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));
|
||||
const deleted = await deleteFolder(folderId);
|
||||
if (deleted) {
|
||||
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);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -785,30 +671,10 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
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));
|
||||
const renamed = await renameFolder(draft.folderId, name);
|
||||
if (renamed) {
|
||||
setPendingFolderRename(null);
|
||||
setPendingFolderRenameName("");
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -833,11 +699,34 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
}
|
||||
};
|
||||
|
||||
const openWorkspaceCreateMenu = (element: HTMLElement): void => {
|
||||
contextMenu.openMenuFromElement(element, sidebarContextMenuTarget);
|
||||
};
|
||||
|
||||
const resolveCreateItemType = (actionId: string): WorkspaceItemTypeId | null => {
|
||||
switch (actionId) {
|
||||
case "create-doc":
|
||||
return "core.doc";
|
||||
case "create-board":
|
||||
return "core.board.kanban";
|
||||
case "create-list-board":
|
||||
return "core.board.list";
|
||||
default:
|
||||
return null;
|
||||
}
|
||||
};
|
||||
|
||||
const createPersistedItem = async (itemType: WorkspaceItemTypeId, parentId: string | null): Promise<void> => {
|
||||
const definition = getWorkspaceItemTypeDefinition(itemType);
|
||||
await createItem(definition.defaultCreateLabel, itemType, parentId);
|
||||
};
|
||||
|
||||
const handleNodePointerDown = (event: PointerEvent, nodeId: string): void => {
|
||||
if (event.button !== 0 || pendingFolderDraft()) {
|
||||
return;
|
||||
}
|
||||
|
||||
updateDragGhostPosition(event.clientX, event.clientY);
|
||||
clearLongPressTimer();
|
||||
longPressTimer = window.setTimeout(() => {
|
||||
suppressTreeClickTemporarily();
|
||||
@@ -875,6 +764,22 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
};
|
||||
|
||||
const handleContextActionSelect = (action: WorkspaceContextMenuAction, target: WorkspaceContextMenuTarget): void => {
|
||||
const createItemType = resolveCreateItemType(action.id);
|
||||
if (createItemType) {
|
||||
switch (target.kind) {
|
||||
case "workspace":
|
||||
case "home":
|
||||
void createPersistedItem(createItemType, null);
|
||||
return;
|
||||
case "folder":
|
||||
void createPersistedItem(createItemType, target.id);
|
||||
return;
|
||||
case "settings":
|
||||
case "item":
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
switch (action.id) {
|
||||
case "new-folder":
|
||||
switch (target.kind) {
|
||||
@@ -900,6 +805,13 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
beginFolderRename(target.id, target.label, findTreeNodeDepth(workspaceTreeNodes(), target.id, workspaceTreeAdapter) ?? 0);
|
||||
}
|
||||
return;
|
||||
case "delete-doc":
|
||||
case "delete-board":
|
||||
case "delete-list-board":
|
||||
if (target.kind === "item") {
|
||||
void deleteItem(target.id);
|
||||
}
|
||||
return;
|
||||
default:
|
||||
return;
|
||||
}
|
||||
@@ -1012,7 +924,23 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
</ul>
|
||||
|
||||
<Show when={!props.collapsed}>
|
||||
<div class={styles.treeSectionHeader}>
|
||||
<div class={styles.treeSectionLabel}>Items</div>
|
||||
<div class={styles.treeControls}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.treeControlButton}
|
||||
onClick={(event): void => {
|
||||
event.stopPropagation();
|
||||
openWorkspaceCreateMenu(event.currentTarget);
|
||||
}}
|
||||
aria-label="Create in Items"
|
||||
title="Create"
|
||||
>
|
||||
<Plus size={16} strokeWidth={2.25} />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<div data-slot="workspace-tree-root">
|
||||
@@ -1058,6 +986,32 @@ export const WorkspaceSidebar = (props: WorkspaceSidebarProps): JSX.Element => {
|
||||
onClose={contextMenu.closeMenu}
|
||||
onSelect={handleContextActionSelect}
|
||||
/>
|
||||
|
||||
<Show when={draggedNode()} keyed>
|
||||
{(node): JSX.Element => {
|
||||
const GhostIcon = getWorkspaceNodeIcon(node);
|
||||
|
||||
return (
|
||||
<Portal>
|
||||
<div class={styles.dragGhostLayer} aria-hidden="true">
|
||||
<div
|
||||
class={styles.dragGhost}
|
||||
style={{
|
||||
"--drag-ghost-x": `${dragGhostPosition().x}px`,
|
||||
"--drag-ghost-y": `${dragGhostPosition().y}px`,
|
||||
}}
|
||||
>
|
||||
<GhostIcon class={styles.icon} size={18} strokeWidth={2} />
|
||||
<div class={styles.dragGhostCopy}>
|
||||
<div class={styles.dragGhostTitle}>{node.label}</div>
|
||||
<div class={styles.dragGhostMeta}>{draggedNodeMeta()}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</Portal>
|
||||
);
|
||||
}}
|
||||
</Show>
|
||||
</>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -140,6 +140,7 @@ export type WorkspaceFolderNode = {
|
||||
|
||||
export type WorkspaceItemNode = {
|
||||
id: string;
|
||||
path?: string;
|
||||
label: string;
|
||||
kind: "item";
|
||||
itemType: WorkspaceItemTypeId;
|
||||
@@ -559,8 +560,7 @@ export const getWorkspaceContextMenuSections = (
|
||||
id: "organize",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: "duplicate-folder", label: "Duplicate", shortcut: { modifiers: ["meta"], key: "d" } },
|
||||
{ id: "move-folder", label: "Move", shortcut: { modifiers: ["meta"], key: "m" } },
|
||||
{ id: "move-folder", label: "Move…", shortcut: { modifiers: ["meta"], key: "m" } },
|
||||
{ id: "delete-folder", label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||
],
|
||||
},
|
||||
@@ -582,8 +582,7 @@ export const getWorkspaceContextMenuSections = (
|
||||
id: "organize",
|
||||
label: undefined,
|
||||
items: [
|
||||
{ id: `duplicate-${actionPrefix}`, label: "Duplicate", shortcut: { modifiers: ["meta"], key: "d" } },
|
||||
{ id: `move-${actionPrefix}`, label: "Move", shortcut: { modifiers: ["meta"], key: "m" } },
|
||||
{ id: `move-${actionPrefix}`, label: "Move…", shortcut: { modifiers: ["meta"], key: "m" } },
|
||||
{ id: `delete-${actionPrefix}`, label: "Delete", shortcut: { modifiers: ["meta"], key: "delete" }, tone: "danger" },
|
||||
],
|
||||
},
|
||||
|
||||
@@ -57,6 +57,7 @@
|
||||
display: grid;
|
||||
position: relative;
|
||||
isolation: isolate;
|
||||
cursor: grab;
|
||||
grid-template-columns: auto auto minmax(0, 1fr) auto;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
@@ -71,7 +72,12 @@
|
||||
transition:
|
||||
color 160ms var(--easing-standard),
|
||||
box-shadow 160ms var(--easing-standard),
|
||||
transform 180ms var(--easing-standard);
|
||||
transform 180ms var(--easing-standard),
|
||||
opacity 160ms var(--easing-standard);
|
||||
|
||||
&:active {
|
||||
cursor: grabbing;
|
||||
}
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
@@ -108,48 +114,61 @@
|
||||
}
|
||||
|
||||
@mixin item-dragging {
|
||||
opacity: 0.45;
|
||||
transform: scale(0.985);
|
||||
box-shadow: none;
|
||||
cursor: grabbing;
|
||||
opacity: 0.88;
|
||||
transform: translateX(2px) scale(0.992);
|
||||
color: var(--color-text);
|
||||
|
||||
&::after {
|
||||
border-color: color-mix(in srgb, var(--color-accent-strong) 24%, var(--color-border));
|
||||
background: color-mix(in srgb, var(--color-surface) 90%, var(--color-accent-soft) 10%);
|
||||
box-shadow:
|
||||
0 10px 24px color-mix(in srgb, black 10%, transparent),
|
||||
inset 0 1px 0 color-mix(in srgb, white 6%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@mixin item-drop-boundary($edge) {
|
||||
&::before {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: calc(var(--space-3) + (var(--tree-depth, 0) * var(--space-4)));
|
||||
right: var(--space-3);
|
||||
#{$edge}: calc(-1 * ((8px - 3px) / 2));
|
||||
height: 8px;
|
||||
border-radius: 999px;
|
||||
background:
|
||||
radial-gradient(circle, color-mix(in srgb, var(--color-accent-strong) 92%, white 8%) 0 3px, transparent 4px)
|
||||
left center / 8px 8px no-repeat,
|
||||
linear-gradient(
|
||||
to right,
|
||||
color-mix(in srgb, var(--color-accent-strong) 88%, white 12%),
|
||||
color-mix(in srgb, var(--color-accent-strong) 72%, transparent)
|
||||
)
|
||||
center / 100% 3px no-repeat;
|
||||
pointer-events: none;
|
||||
z-index: 2;
|
||||
}
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
@include item-drop-boundary(top);
|
||||
}
|
||||
|
||||
@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;
|
||||
}
|
||||
@include item-drop-boundary(bottom);
|
||||
}
|
||||
|
||||
@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);
|
||||
border-color: color-mix(in srgb, var(--color-accent-strong) 72%, transparent);
|
||||
background: color-mix(in srgb, var(--color-accent-soft) 48%, var(--color-surface));
|
||||
box-shadow:
|
||||
0 0 0 1px color-mix(in srgb, var(--color-accent-strong) 18%, transparent),
|
||||
inset 0 1px 0 color-mix(in srgb, white 4%, transparent),
|
||||
inset 4px 0 0 color-mix(in srgb, var(--color-accent-strong) 78%, transparent);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -186,3 +205,71 @@
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
@mixin drag-ghost-layer {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
pointer-events: none;
|
||||
z-index: 60;
|
||||
}
|
||||
|
||||
@mixin drag-ghost {
|
||||
position: fixed;
|
||||
top: 0;
|
||||
left: 0;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
min-height: calc(var(--control-size-lg) - var(--space-2));
|
||||
max-width: min(24rem, calc(100vw - (var(--space-6) * 2)));
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border-radius: var(--radius-lg);
|
||||
border: 1px solid color-mix(in srgb, var(--color-accent-strong) 18%, var(--color-border));
|
||||
background: color-mix(in srgb, var(--color-surface) 92%, var(--color-accent-soft) 8%);
|
||||
box-shadow:
|
||||
0 18px 38px color-mix(in srgb, black 16%, transparent),
|
||||
0 6px 14px color-mix(in srgb, black 8%, transparent),
|
||||
inset 0 1px 0 color-mix(in srgb, white 8%, transparent);
|
||||
color: var(--color-text);
|
||||
transform: translate3d(var(--drag-ghost-x, 0), var(--drag-ghost-y, 0), 0);
|
||||
will-change: transform;
|
||||
backdrop-filter: blur(12px);
|
||||
-webkit-backdrop-filter: blur(12px);
|
||||
|
||||
&::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
border-radius: inherit;
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
color-mix(in srgb, white 10%, transparent),
|
||||
transparent 42%
|
||||
);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
> * {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
}
|
||||
}
|
||||
|
||||
@mixin drag-ghost-copy {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 0.1rem;
|
||||
}
|
||||
|
||||
@mixin drag-ghost-title {
|
||||
@include text-label;
|
||||
min-width: 0;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
|
||||
@mixin drag-ghost-meta {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,393 @@
|
||||
import { createEffect, createSignal, type Accessor, type Setter } from "solid-js";
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
import { Folder } from "../../../lib/icons";
|
||||
import type { WorkspaceItemTypeId, WorkspaceTreeNode } from "../data/shell.data";
|
||||
import { isUuidString } from "./navTreeDnd";
|
||||
|
||||
type PersistedWorkspaceTreeNodeRecord = {
|
||||
id: string;
|
||||
path: string;
|
||||
label: string;
|
||||
kind: "folder" | "item";
|
||||
itemType?: string;
|
||||
children?: PersistedWorkspaceTreeNodeRecord[];
|
||||
};
|
||||
|
||||
type WorkspaceTreeResponse = {
|
||||
data?: {
|
||||
nodes?: PersistedWorkspaceTreeNodeRecord[];
|
||||
};
|
||||
error?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
type WorkspaceMutationResponse = {
|
||||
error?: string;
|
||||
message?: string;
|
||||
};
|
||||
|
||||
const buildPersistedWorkspaceTreeNodes = (
|
||||
nodes: readonly PersistedWorkspaceTreeNodeRecord[],
|
||||
): WorkspaceTreeNode[] =>
|
||||
nodes.map((node) =>
|
||||
node.kind === "folder"
|
||||
? {
|
||||
id: node.id,
|
||||
path: node.path,
|
||||
label: node.label,
|
||||
kind: "folder",
|
||||
icon: Folder,
|
||||
children: buildPersistedWorkspaceTreeNodes(node.children ?? []),
|
||||
}
|
||||
: {
|
||||
id: node.id,
|
||||
path: node.path,
|
||||
label: node.label,
|
||||
kind: "item",
|
||||
itemType: node.itemType ?? "core.board.kanban",
|
||||
}
|
||||
);
|
||||
|
||||
const readPersistedWorkspaceTreeNodes = (body: WorkspaceTreeResponse): PersistedWorkspaceTreeNodeRecord[] =>
|
||||
Array.isArray(body.data?.nodes) ? body.data.nodes : [];
|
||||
|
||||
const findNodeById = (nodes: readonly WorkspaceTreeNode[], nodeId: string): WorkspaceTreeNode | null => {
|
||||
for (const node of nodes) {
|
||||
if (node.id === nodeId) {
|
||||
return node;
|
||||
}
|
||||
|
||||
if (node.kind !== "folder") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const nestedMatch = findNodeById(node.children ?? [], nodeId);
|
||||
if (nestedMatch) {
|
||||
return nestedMatch;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
};
|
||||
|
||||
type UseWorkspaceTreeDataOptions = {
|
||||
activeProjectId: Accessor<string>;
|
||||
fallbackWorkspaceTree: Accessor<readonly WorkspaceTreeNode[]>;
|
||||
};
|
||||
|
||||
type UseWorkspaceTreeDataResult = {
|
||||
workspaceTreeNodes: Accessor<readonly WorkspaceTreeNode[]>;
|
||||
setWorkspaceTreeNodes: Setter<readonly WorkspaceTreeNode[]>;
|
||||
resolveFolderPath: (folderId: string) => string | null;
|
||||
resolveItemPath: (itemId: string) => string | null;
|
||||
createFolder: (name: string, parentId: string | null) => Promise<boolean>;
|
||||
renameFolder: (folderId: string, name: string) => Promise<boolean>;
|
||||
deleteFolder: (folderId: string) => Promise<boolean>;
|
||||
moveFolder: (folderId: string, parentId: string | null, targetIndex: number) => Promise<boolean>;
|
||||
createItem: (name: string, itemType: WorkspaceItemTypeId, parentId: string | null) => Promise<boolean>;
|
||||
deleteItem: (itemId: string) => Promise<boolean>;
|
||||
moveItem: (itemId: string, parentId: string | null, targetIndex: number) => Promise<boolean>;
|
||||
};
|
||||
|
||||
export const useWorkspaceTreeData = (
|
||||
options: UseWorkspaceTreeDataOptions,
|
||||
): UseWorkspaceTreeDataResult => {
|
||||
const [persistedNodes, setPersistedNodes] = createSignal<readonly PersistedWorkspaceTreeNodeRecord[]>([]);
|
||||
const [workspaceTreeNodes, setWorkspaceTreeNodes] = createSignal<readonly WorkspaceTreeNode[]>(
|
||||
options.fallbackWorkspaceTree(),
|
||||
);
|
||||
let latestPersistedTreeRequest = 0;
|
||||
|
||||
const syncWorkspaceTree = (): void => {
|
||||
const nextTree = options.activeProjectId()
|
||||
? buildPersistedWorkspaceTreeNodes(persistedNodes())
|
||||
: options.fallbackWorkspaceTree();
|
||||
|
||||
setWorkspaceTreeNodes(nextTree);
|
||||
};
|
||||
|
||||
const loadPersistedTree = async (projectId: string): Promise<boolean> => {
|
||||
const requestId = latestPersistedTreeRequest + 1;
|
||||
latestPersistedTreeRequest = requestId;
|
||||
|
||||
if (!projectId || !isUuidString(projectId)) {
|
||||
setPersistedNodes([]);
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree`, {
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
});
|
||||
const body = (await response.json()) as WorkspaceTreeResponse;
|
||||
|
||||
if (requestId !== latestPersistedTreeRequest) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to load project tree.");
|
||||
}
|
||||
|
||||
setPersistedNodes(readPersistedWorkspaceTreeNodes(body));
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (requestId !== latestPersistedTreeRequest) {
|
||||
return false;
|
||||
}
|
||||
|
||||
console.error(error);
|
||||
setPersistedNodes([]);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const resolveFolderPath = (folderId: string): string | null => {
|
||||
const node = findNodeById(workspaceTreeNodes(), folderId);
|
||||
return node?.kind === "folder" ? node.path ?? null : null;
|
||||
};
|
||||
|
||||
const resolveItemPath = (itemId: string): string | null => {
|
||||
const node = findNodeById(workspaceTreeNodes(), itemId);
|
||||
return node?.kind === "item" ? node.path ?? null : null;
|
||||
};
|
||||
|
||||
const refreshAfterMutation = async (projectId: string, response: Response): Promise<boolean> => {
|
||||
const body = (await response.json()) as WorkspaceMutationResponse;
|
||||
if (!response.ok) {
|
||||
throw new Error(body.message || "Failed to persist project tree mutation.");
|
||||
}
|
||||
|
||||
return loadPersistedTree(projectId);
|
||||
};
|
||||
|
||||
const createFolder = async (name: string, parentId: string | null): Promise<boolean> => {
|
||||
const projectId = options.activeProjectId();
|
||||
if (!projectId || !isUuidString(projectId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parentFolderPath = parentId ? resolveFolderPath(parentId) : null;
|
||||
if (parentId && !parentFolderPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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,
|
||||
}),
|
||||
});
|
||||
|
||||
return refreshAfterMutation(projectId, response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const renameFolder = async (folderId: string, name: string): Promise<boolean> => {
|
||||
const projectId = options.activeProjectId();
|
||||
const folderPath = resolveFolderPath(folderId);
|
||||
if (!projectId || !isUuidString(projectId) || !folderPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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,
|
||||
}),
|
||||
});
|
||||
|
||||
return refreshAfterMutation(projectId, response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const deleteFolder = async (folderId: string): Promise<boolean> => {
|
||||
const projectId = options.activeProjectId();
|
||||
const folderPath = resolveFolderPath(folderId);
|
||||
if (!projectId || !isUuidString(projectId) || !folderPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${resolveAPIBase()}/projects/${projectId}/tree/folders?folderId=${encodeURIComponent(folderPath)}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return refreshAfterMutation(projectId, response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const moveFolder = async (folderId: string, parentId: string | null, targetIndex: number): Promise<boolean> => {
|
||||
const projectId = options.activeProjectId();
|
||||
const folderPath = resolveFolderPath(folderId);
|
||||
const parentFolderPath = parentId ? resolveFolderPath(parentId) : null;
|
||||
if (!projectId || !isUuidString(projectId) || !folderPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
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: folderId,
|
||||
parentFolderId: parentFolderPath,
|
||||
parentNodeId: parentId,
|
||||
targetIndex,
|
||||
}),
|
||||
});
|
||||
|
||||
return refreshAfterMutation(projectId, response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const createItem = async (
|
||||
name: string,
|
||||
itemType: WorkspaceItemTypeId,
|
||||
parentId: string | null,
|
||||
): Promise<boolean> => {
|
||||
const projectId = options.activeProjectId();
|
||||
if (!projectId || !isUuidString(projectId)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const parentFolderPath = parentId ? resolveFolderPath(parentId) : null;
|
||||
if (parentId && !parentFolderPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/items`, {
|
||||
method: "POST",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
name,
|
||||
itemType,
|
||||
parentFolderId: parentFolderPath,
|
||||
}),
|
||||
});
|
||||
|
||||
return refreshAfterMutation(projectId, response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const deleteItem = async (itemId: string): Promise<boolean> => {
|
||||
const projectId = options.activeProjectId();
|
||||
const itemPath = resolveItemPath(itemId);
|
||||
if (!projectId || !isUuidString(projectId) || !itemPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(
|
||||
`${resolveAPIBase()}/projects/${projectId}/tree/items?itemId=${encodeURIComponent(itemPath)}`,
|
||||
{
|
||||
method: "DELETE",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
return refreshAfterMutation(projectId, response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const moveItem = async (itemId: string, parentId: string | null, targetIndex: number): Promise<boolean> => {
|
||||
const projectId = options.activeProjectId();
|
||||
const itemPath = resolveItemPath(itemId);
|
||||
const parentFolderPath = parentId ? resolveFolderPath(parentId) : null;
|
||||
if (!projectId || !isUuidString(projectId) || !itemPath) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${resolveAPIBase()}/projects/${projectId}/tree/items/move`, {
|
||||
method: "PATCH",
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
body: JSON.stringify({
|
||||
itemId: itemPath,
|
||||
itemNodeId: itemId,
|
||||
parentFolderId: parentFolderPath,
|
||||
parentNodeId: parentId,
|
||||
targetIndex,
|
||||
}),
|
||||
});
|
||||
|
||||
return refreshAfterMutation(projectId, response);
|
||||
} catch (error) {
|
||||
console.error(error);
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
createEffect(() => {
|
||||
syncWorkspaceTree();
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
void loadPersistedTree(options.activeProjectId());
|
||||
});
|
||||
|
||||
return {
|
||||
workspaceTreeNodes,
|
||||
setWorkspaceTreeNodes,
|
||||
resolveFolderPath,
|
||||
resolveItemPath,
|
||||
createFolder,
|
||||
renameFolder,
|
||||
deleteFolder,
|
||||
moveFolder,
|
||||
createItem,
|
||||
deleteItem,
|
||||
moveItem,
|
||||
};
|
||||
};
|
||||
@@ -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,
|
||||
.wizardLayer {
|
||||
--workspace-content-max-width: var(--content-width-wide);
|
||||
@@ -268,11 +270,249 @@
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.fieldLabelRow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.35rem;
|
||||
}
|
||||
|
||||
.fieldInfoButton {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
color: var(--color-text-muted);
|
||||
cursor: help;
|
||||
outline: none;
|
||||
}
|
||||
|
||||
.fieldInfoButton:hover,
|
||||
.fieldInfoButton:focus-visible {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.fieldTooltip {
|
||||
position: fixed;
|
||||
z-index: calc(var(--z-modal, 1000) + 4);
|
||||
pointer-events: none;
|
||||
transform: translateX(-50%);
|
||||
max-width: min(18rem, calc(100vw - 2rem));
|
||||
}
|
||||
|
||||
.fieldTooltip[data-placement="top"] {
|
||||
transform: translate(-50%, -100%);
|
||||
}
|
||||
|
||||
.fieldTooltip[data-placement="bottom"] {
|
||||
transform: translate(-50%, 0);
|
||||
}
|
||||
|
||||
.fieldTooltipBubble {
|
||||
position: relative;
|
||||
padding: 0.45rem 0.6rem;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
border-radius: var(--radius-md);
|
||||
background: color-mix(in srgb, var(--color-surface-elevated, var(--color-surface)) 96%, black 4%);
|
||||
box-shadow: var(--shadow-soft);
|
||||
color: var(--color-text);
|
||||
white-space: normal;
|
||||
text-align: left;
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.fieldTooltipBubble::after {
|
||||
content: "";
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
width: 0.55rem;
|
||||
height: 0.55rem;
|
||||
background: color-mix(in srgb, var(--color-surface-elevated, var(--color-surface)) 96%, black 4%);
|
||||
transform: translateX(-50%) rotate(45deg);
|
||||
}
|
||||
|
||||
.fieldTooltip[data-placement="top"] .fieldTooltipBubble::after {
|
||||
top: calc(100% - 0.3rem);
|
||||
border-right: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
border-bottom: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
}
|
||||
|
||||
.fieldTooltip[data-placement="bottom"] .fieldTooltipBubble::after {
|
||||
bottom: calc(100% - 0.3rem);
|
||||
border-top: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
border-left: 1px solid color-mix(in srgb, var(--color-border-strong) 48%, transparent);
|
||||
}
|
||||
|
||||
.fieldHelp {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.personaIntro {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
}
|
||||
|
||||
.personaGrid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.personaCard {
|
||||
appearance: none;
|
||||
position: relative;
|
||||
display: grid;
|
||||
padding: var(--space-3);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
border-radius: var(--radius-xl);
|
||||
background: color-mix(in srgb, var(--color-surface-secondary) 84%, transparent);
|
||||
text-align: left;
|
||||
overflow: hidden;
|
||||
transition:
|
||||
transform 180ms var(--easing-standard),
|
||||
border-color 160ms var(--easing-standard),
|
||||
background 160ms var(--easing-standard),
|
||||
box-shadow 160ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.personaCard:hover,
|
||||
.personaCard:focus-visible,
|
||||
.personaCard[data-selected="true"] {
|
||||
transform: translateY(-1px);
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 32%, var(--color-border));
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 7%, var(--color-surface));
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
.personaCard:focus-visible {
|
||||
outline: none;
|
||||
box-shadow:
|
||||
var(--shadow-soft),
|
||||
0 0 0 3px color-mix(in srgb, var(--bootstrap-accent) 16%, transparent);
|
||||
}
|
||||
|
||||
.personaCard[data-available="false"] {
|
||||
opacity: 0.9;
|
||||
}
|
||||
|
||||
.personaCard[data-available="false"]:hover,
|
||||
.personaCard[data-available="false"]:focus-visible,
|
||||
.personaCard[data-available="false"][data-selected="true"] {
|
||||
transform: none;
|
||||
border-color: color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
background: color-mix(in srgb, var(--color-surface-secondary) 84%, transparent);
|
||||
box-shadow: none;
|
||||
}
|
||||
|
||||
.personaCardMedia {
|
||||
position: relative;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
justify-self: center;
|
||||
align-self: center;
|
||||
width: min(100%, 16rem);
|
||||
aspect-ratio: 1 / 1;
|
||||
border: 1px dashed color-mix(in srgb, var(--color-border-strong) 40%, transparent);
|
||||
border-radius: calc(var(--radius-xl) - var(--space-1));
|
||||
background: linear-gradient(
|
||||
135deg,
|
||||
color-mix(in srgb, var(--color-surface-elevated) 92%, transparent),
|
||||
color-mix(in srgb, var(--color-surface-secondary) 88%, transparent)
|
||||
);
|
||||
transition:
|
||||
filter 180ms var(--easing-standard),
|
||||
opacity 180ms var(--easing-standard),
|
||||
transform 180ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.personaCardBody {
|
||||
position: absolute;
|
||||
inset: 0;
|
||||
display: grid;
|
||||
align-content: space-between;
|
||||
gap: var(--space-3);
|
||||
padding: var(--space-3);
|
||||
pointer-events: none;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.personaCardTitle {
|
||||
@include text-title;
|
||||
margin: 0;
|
||||
max-width: min(100%, 14rem);
|
||||
padding: 0.35rem 0.65rem;
|
||||
border-radius: var(--radius-md);
|
||||
background: color-mix(in srgb, var(--color-surface) 84%, transparent);
|
||||
backdrop-filter: blur(10px);
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.personaCardDetails {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
max-height: 0;
|
||||
opacity: 0;
|
||||
overflow: hidden;
|
||||
align-self: end;
|
||||
padding: var(--space-3);
|
||||
border-radius: var(--radius-lg);
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
color-mix(in srgb, var(--color-surface) 18%, transparent),
|
||||
color-mix(in srgb, var(--color-surface) 92%, transparent)
|
||||
);
|
||||
backdrop-filter: blur(12px);
|
||||
transition:
|
||||
max-height 180ms var(--easing-standard),
|
||||
opacity 160ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.personaCard:hover .personaCardMedia,
|
||||
.personaCard:focus-visible .personaCardMedia,
|
||||
.personaCard[data-selected="true"] .personaCardMedia {
|
||||
filter: brightness(0.72);
|
||||
opacity: 0.92;
|
||||
transform: scale(0.985);
|
||||
}
|
||||
|
||||
.personaCard:hover .personaCardDetails,
|
||||
.personaCard:focus-visible .personaCardDetails,
|
||||
.personaCard[data-selected="true"] .personaCardDetails {
|
||||
max-height: 12rem;
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.personaCard[data-available="false"]:hover .personaCardMedia,
|
||||
.personaCard[data-available="false"]:focus-visible .personaCardMedia,
|
||||
.personaCard[data-available="false"][data-selected="true"] .personaCardMedia {
|
||||
filter: brightness(0.82);
|
||||
opacity: 0.96;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.personaBestFor,
|
||||
.personaBulletList {
|
||||
margin: 0;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.personaBulletList {
|
||||
padding-left: 1rem;
|
||||
display: grid;
|
||||
gap: 0.25rem;
|
||||
}
|
||||
|
||||
.personaAvailability {
|
||||
@include text-caption;
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.06em;
|
||||
}
|
||||
|
||||
.field input,
|
||||
.field select {
|
||||
min-height: var(--control-size-md);
|
||||
@@ -370,7 +610,7 @@
|
||||
.primaryButton:hover,
|
||||
.secondaryButton:hover,
|
||||
.wizardCloseButton:hover,
|
||||
.wizardStepButton:hover {
|
||||
.wizardProgressStep:hover {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
@@ -445,72 +685,93 @@
|
||||
|
||||
.wizardBody {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(17rem, 20rem) minmax(0, 1fr);
|
||||
gap: var(--space-4);
|
||||
min-height: 0;
|
||||
}
|
||||
|
||||
.wizardSidebar {
|
||||
.wizardProgress {
|
||||
position: relative;
|
||||
display: grid;
|
||||
gap: var(--space-4);
|
||||
align-content: start;
|
||||
}
|
||||
|
||||
.wizardSidebarSection {
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.wizardSteps {
|
||||
display: grid;
|
||||
gap: var(--space-2);
|
||||
.wizardProgressTrack {
|
||||
position: absolute;
|
||||
left: calc((var(--control-size-md) - var(--space-2)) / 2);
|
||||
right: calc((var(--control-size-md) - var(--space-2)) / 2);
|
||||
top: calc((var(--control-size-md) - var(--space-2)) / 2);
|
||||
height: 2px;
|
||||
background: color-mix(in srgb, var(--color-border) 72%, transparent);
|
||||
transform: translateY(-50%);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.wizardStepButton {
|
||||
width: 100%;
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
.wizardProgressFill {
|
||||
height: 100%;
|
||||
border-radius: 999px;
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 72%, white 8%);
|
||||
transition: width 220ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.wizardProgressSteps {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
text-align: left;
|
||||
padding: var(--space-2) var(--space-3);
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
background: color-mix(in srgb, var(--color-surface-secondary) 84%, transparent);
|
||||
justify-content: space-between;
|
||||
gap: 0;
|
||||
}
|
||||
|
||||
.wizardStepButton[data-active="true"] {
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 42%, transparent);
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 10%, var(--color-surface));
|
||||
.wizardProgressStep {
|
||||
position: relative;
|
||||
z-index: 1;
|
||||
flex: 0 0 auto;
|
||||
display: inline-flex;
|
||||
justify-content: center;
|
||||
justify-items: center;
|
||||
text-align: center;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.wizardStepButton:disabled {
|
||||
opacity: 0.56;
|
||||
.wizardProgressStep:disabled {
|
||||
cursor: not-allowed;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
.wizardStepIndex {
|
||||
.wizardProgressIndex {
|
||||
width: calc(var(--control-size-md) - var(--space-2));
|
||||
height: calc(var(--control-size-md) - var(--space-2));
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: var(--radius-pill);
|
||||
background: color-mix(in srgb, var(--color-surface) 80%, transparent);
|
||||
border-radius: 999px;
|
||||
border: 1px solid color-mix(in srgb, var(--color-border) 88%, transparent);
|
||||
background: color-mix(in srgb, var(--color-surface) 92%, transparent);
|
||||
color: var(--color-text-muted);
|
||||
transition:
|
||||
border-color 160ms var(--easing-standard),
|
||||
background 160ms var(--easing-standard),
|
||||
color 160ms var(--easing-standard),
|
||||
box-shadow 160ms var(--easing-standard),
|
||||
transform 180ms var(--easing-standard);
|
||||
}
|
||||
|
||||
.wizardProgressStep[data-active="true"] .wizardProgressIndex,
|
||||
.wizardProgressStep[data-complete="true"] .wizardProgressIndex {
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 42%, transparent);
|
||||
background: color-mix(in srgb, var(--bootstrap-accent) 12%, var(--color-surface));
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.wizardStepCopy {
|
||||
min-width: 0;
|
||||
display: grid;
|
||||
gap: 0.125rem;
|
||||
.wizardProgressStep[data-active="true"] .wizardProgressIndex {
|
||||
box-shadow: 0 0 0 3px color-mix(in srgb, var(--bootstrap-accent) 14%, transparent);
|
||||
}
|
||||
|
||||
.wizardStepCopy strong {
|
||||
@include text-label;
|
||||
}
|
||||
|
||||
.wizardStepCopy small {
|
||||
@include text-caption;
|
||||
color: var(--color-text-muted);
|
||||
.wizardProgressStep:not(:disabled):hover .wizardProgressIndex,
|
||||
.wizardProgressStep:not(:disabled):focus-visible .wizardProgressIndex {
|
||||
transform: translateY(-1px);
|
||||
border-color: color-mix(in srgb, var(--bootstrap-accent) 36%, var(--color-border));
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.wizardStepPanel {
|
||||
@@ -624,6 +885,10 @@
|
||||
}
|
||||
|
||||
@include respond-down(tablet) {
|
||||
.personaGrid {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.summaryGrid,
|
||||
.wizardBody {
|
||||
grid-template-columns: 1fr;
|
||||
@@ -669,21 +934,20 @@
|
||||
}
|
||||
|
||||
.wizardHeader,
|
||||
.wizardBody,
|
||||
.wizardSidebar {
|
||||
.wizardBody {
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.wizardSteps {
|
||||
grid-auto-flow: column;
|
||||
grid-auto-columns: minmax(10rem, 1fr);
|
||||
.wizardProgressSteps {
|
||||
justify-content: flex-start;
|
||||
gap: var(--space-8);
|
||||
overflow-x: auto;
|
||||
padding-bottom: var(--space-1);
|
||||
scrollbar-width: thin;
|
||||
}
|
||||
|
||||
.wizardStepButton {
|
||||
min-width: 10rem;
|
||||
.wizardProgressStep {
|
||||
min-width: calc(var(--control-size-md) - var(--space-2));
|
||||
}
|
||||
|
||||
.wizardFormActions {
|
||||
|
||||
@@ -0,0 +1,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,172 +1,13 @@
|
||||
// Path: Frontend/src/components/workspace-home/WorkspaceHome/WorkspaceHome.tsx
|
||||
|
||||
import { For, Show, createEffect, createMemo, createSignal, onCleanup, type JSX } from "solid-js";
|
||||
import { Show, createMemo, type JSX } from "solid-js";
|
||||
import { Portal } from "solid-js/web";
|
||||
import { createStore } from "solid-js/store";
|
||||
import { resolveAPIBase } from "../../../lib/api";
|
||||
import { ChevronLeft, ChevronRight } from "../../../lib/icons";
|
||||
import { useAppShellData } from "../../shell/data/app-shell.context";
|
||||
import { bootstrapPersonaDefinitions } from "./WorkspaceHome.data";
|
||||
import { useWorkspaceHomeWizard } from "./WorkspaceHome.hook";
|
||||
import styles from "./WorkspaceHome.module.scss";
|
||||
|
||||
type BootstrapStepKey = "instance" | "mode" | "admin" | "structure";
|
||||
|
||||
type BootstrapStepDefinition = {
|
||||
id: BootstrapStepKey;
|
||||
title: string;
|
||||
buttonLabel: string;
|
||||
};
|
||||
|
||||
type BootstrapSubmissionState = {
|
||||
status: "idle" | "submitting" | "success" | "error";
|
||||
error: string;
|
||||
};
|
||||
|
||||
type InstanceForm = {
|
||||
protocol: "http" | "https";
|
||||
access: "local" | "remote";
|
||||
host: string;
|
||||
};
|
||||
|
||||
type ModeForm = {
|
||||
mode: "personal" | "organizational";
|
||||
name: string;
|
||||
};
|
||||
|
||||
type AdminForm = {
|
||||
displayName: string;
|
||||
email: string;
|
||||
password: string;
|
||||
};
|
||||
|
||||
type StructureForm = {
|
||||
departmentName: string;
|
||||
teamName: string;
|
||||
projectName: string;
|
||||
};
|
||||
|
||||
type MaterializationState = "not_started" | "pending" | "running" | "succeeded" | "failed";
|
||||
|
||||
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: InstanceForm = {
|
||||
protocol: "http",
|
||||
access: "local",
|
||||
host: "localhost",
|
||||
};
|
||||
|
||||
const defaultModeForm: ModeForm = {
|
||||
mode: "personal",
|
||||
name: "",
|
||||
};
|
||||
|
||||
const defaultAdminForm: AdminForm = {
|
||||
displayName: "Admin",
|
||||
email: "admin@example.com",
|
||||
password: "",
|
||||
};
|
||||
|
||||
const personalStructureDefaults = {
|
||||
departmentName: "Default",
|
||||
teamName: "Personal",
|
||||
};
|
||||
|
||||
const organizationalStructureDefaults = {
|
||||
departmentName: "Department",
|
||||
teamName: "Team",
|
||||
};
|
||||
|
||||
const defaultStructureForm: StructureForm = {
|
||||
...personalStructureDefaults,
|
||||
projectName: "Project",
|
||||
};
|
||||
|
||||
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(", ")})`;
|
||||
};
|
||||
import { BootstrapAdminStep, BootstrapFinishingState, BootstrapInstanceStep, BootstrapModeStep, BootstrapPersonaStep, BootstrapStructureStep, BootstrapWizardProgress } from "./WorkspaceHome.parts";
|
||||
|
||||
type WorkspaceHomeProps = {
|
||||
sidebarCollapsed: boolean;
|
||||
@@ -175,301 +16,61 @@ type WorkspaceHomeProps = {
|
||||
|
||||
export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
||||
const appShellData = useAppShellData();
|
||||
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 [stepState, setStepState] = createStore<Record<BootstrapStepKey, BootstrapSubmissionState>>({
|
||||
instance: initialSubmissionState(),
|
||||
mode: initialSubmissionState(),
|
||||
admin: initialSubmissionState(),
|
||||
structure: initialSubmissionState(),
|
||||
});
|
||||
const [isBootstrapStateResolved, setIsBootstrapStateResolved] = createSignal(false);
|
||||
const [isBootstrapComplete, setIsBootstrapComplete] = createSignal(false);
|
||||
const [isWizardOpen, setIsWizardOpen] = createSignal(false);
|
||||
const [isFinishingBootstrapFlow, setIsFinishingBootstrapFlow] = createSignal(false);
|
||||
const [currentStepIndex, setCurrentStepIndex] = createSignal(0);
|
||||
const installation = createMemo(() => appShellData.installation());
|
||||
const materializationState = createMemo<MaterializationState>(() => {
|
||||
const status = installation()?.materializationStatus;
|
||||
const {
|
||||
instanceForm,
|
||||
setInstanceForm,
|
||||
modeForm,
|
||||
setModeForm,
|
||||
adminForm,
|
||||
setAdminForm,
|
||||
structureForm,
|
||||
setStructureForm,
|
||||
selectedPersona,
|
||||
hasChosenPersona,
|
||||
stepState,
|
||||
isBootstrapStateResolved,
|
||||
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);
|
||||
|
||||
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 "";
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
if (modeForm.mode === "personal") {
|
||||
setStructureForm("departmentName", personalStructureDefaults.departmentName);
|
||||
setStructureForm("teamName", personalStructureDefaults.teamName);
|
||||
return;
|
||||
}
|
||||
|
||||
if (structureForm.departmentName === personalStructureDefaults.departmentName) {
|
||||
setStructureForm("departmentName", organizationalStructureDefaults.departmentName);
|
||||
}
|
||||
|
||||
if (structureForm.teamName === personalStructureDefaults.teamName) {
|
||||
setStructureForm("teamName", organizationalStructureDefaults.teamName);
|
||||
}
|
||||
});
|
||||
|
||||
createEffect(() => {
|
||||
const shellStatus = appShellData.status();
|
||||
|
||||
if (shellStatus === "idle" || shellStatus === "loading") {
|
||||
return;
|
||||
}
|
||||
|
||||
if (shellStatus !== "success") {
|
||||
return;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
// The final bootstrap step only persists relational state. Poll while the
|
||||
// worker is materializing the POSIX skeleton so the page can transition from
|
||||
// queued/running to ready/failed without a manual refresh.
|
||||
await appShellData.reload();
|
||||
|
||||
if (!cancelled && isBootstrapPersisted() && isMaterializationInFlight()) {
|
||||
scheduleReload();
|
||||
}
|
||||
}, materializationPollIntervalMs);
|
||||
};
|
||||
|
||||
scheduleReload();
|
||||
|
||||
onCleanup(() => {
|
||||
cancelled = true;
|
||||
|
||||
if (timeoutId !== undefined) {
|
||||
window.clearTimeout(timeoutId);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
const sidebarToggleLabel = (): string =>
|
||||
props.sidebarCollapsed ? "Expand left workspace sidebar" : "Collapse left workspace sidebar";
|
||||
const sidebarToggleLabel = (): string => (props.sidebarCollapsed ? "Expand left workspace sidebar" : "Collapse left workspace sidebar");
|
||||
const breadcrumb = (): string => `${appShellData.activeServer().name} / ${appShellData.activeProject().name} / Home`;
|
||||
const apiBase = (): string => resolveAPIBase();
|
||||
const bootstrapTargetLabel = (): string =>
|
||||
modeForm.mode === "personal" ? "Personal server" : "Organization server";
|
||||
const bootstrapNamePlaceholder = (): string =>
|
||||
modeForm.mode === "personal" ? "Personal server name" : "Organization server name";
|
||||
const currentStep = createMemo<BootstrapStepDefinition>(
|
||||
() => bootstrapStepDefinitions[currentStepIndex()] ?? bootstrapStepDefinitions[0]!,
|
||||
);
|
||||
const currentStepState = createMemo<BootstrapSubmissionState>(() => stepState[currentStep().id]);
|
||||
const isFirstStep = (): boolean => currentStepIndex() === 0;
|
||||
const isLastStep = (): boolean => currentStepIndex() === bootstrapStepDefinitions.length - 1;
|
||||
const canDismissWizard = (): boolean => isBootstrapPersisted() && !isMaterializationInFlight();
|
||||
|
||||
const resetWizardState = (): void => {
|
||||
setInstanceForm({ ...defaultInstanceForm });
|
||||
setModeForm({ ...defaultModeForm });
|
||||
setAdminForm({ ...defaultAdminForm });
|
||||
setStructureForm({ ...defaultStructureForm });
|
||||
setStepState({
|
||||
instance: initialSubmissionState(),
|
||||
mode: initialSubmissionState(),
|
||||
admin: initialSubmissionState(),
|
||||
structure: initialSubmissionState(),
|
||||
});
|
||||
setCurrentStepIndex(0);
|
||||
setIsFinishingBootstrapFlow(false);
|
||||
};
|
||||
|
||||
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 shouldShowFinishingState = isBootstrapPersisted() && (isMaterializationInFlight() || hasMaterializationFailed());
|
||||
setIsFinishingBootstrapFlow(shouldShowFinishingState);
|
||||
setIsBootstrapComplete(isBootstrapPersisted() && !isMaterializationInFlight());
|
||||
setIsWizardOpen(!isBootstrapPersisted() || shouldShowFinishingState);
|
||||
setIsBootstrapStateResolved(true);
|
||||
return;
|
||||
}
|
||||
|
||||
setCurrentStepIndex((index) => Math.min(index + 1, bootstrapStepDefinitions.length - 1));
|
||||
};
|
||||
|
||||
const handleCurrentStepSubmit: JSX.EventHandler<HTMLFormElement, SubmitEvent> = (event): void => {
|
||||
event.preventDefault();
|
||||
void submitCurrentStep();
|
||||
};
|
||||
|
||||
const statusLabel = (state: BootstrapSubmissionState): string => {
|
||||
switch (state.status) {
|
||||
case "submitting":
|
||||
return "Sending";
|
||||
case "success":
|
||||
return "Saved";
|
||||
case "error":
|
||||
return "Request failed";
|
||||
default:
|
||||
return "Ready";
|
||||
}
|
||||
};
|
||||
|
||||
const stepStatusLabel = (step: BootstrapStepDefinition): string => {
|
||||
const state = stepState[step.id];
|
||||
|
||||
if (state.status === "success") {
|
||||
return "Done";
|
||||
}
|
||||
|
||||
if (state.status === "error") {
|
||||
return "Needs retry";
|
||||
}
|
||||
|
||||
return "";
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<main class={styles.viewport} data-ui="workspace-home">
|
||||
<div class={styles.workspaceTopBar} data-slot="workspace-home-top-bar">
|
||||
<div class={styles.workspaceTopBarStart} data-slot="workspace-home-top-bar-start">
|
||||
<button
|
||||
type="button"
|
||||
class={styles.workspaceCollapseButton}
|
||||
aria-label={sidebarToggleLabel()}
|
||||
title={sidebarToggleLabel()}
|
||||
data-slot="workspace-home-sidebar-toggle"
|
||||
onClick={props.onToggleSidebarCollapse}
|
||||
>
|
||||
<button type="button" class={styles.workspaceCollapseButton} aria-label={sidebarToggleLabel()} title={sidebarToggleLabel()} data-slot="workspace-home-sidebar-toggle" onClick={props.onToggleSidebarCollapse}>
|
||||
{props.sidebarCollapsed ? <ChevronRight size={16} strokeWidth={2} /> : <ChevronLeft size={16} strokeWidth={2} />}
|
||||
</button>
|
||||
</div>
|
||||
@@ -482,7 +83,7 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
||||
</div>
|
||||
|
||||
<section class={styles.hero} data-slot="workspace-home-hero">
|
||||
<h1 class={styles.title}>{isBootstrapPersisted() ? appShellData.activeServer().name : bootstrapTargetLabel()}</h1>
|
||||
<h1 class={styles.title}>{isBootstrapPersisted() ? appShellData.activeServer().name : "Server"}</h1>
|
||||
<Show when={isBootstrapStateResolved() && !isBootstrapPersisted()}>
|
||||
<div class={styles.heroActions}>
|
||||
<button
|
||||
@@ -508,7 +109,7 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
||||
<header class={styles.wizardHeader} data-slot="bootstrap-wizard-header">
|
||||
<div class={styles.wizardHeaderCopy}>
|
||||
<h2 id="bootstrap-wizard-title" class={styles.wizardTitle}>
|
||||
Bootstrap {bootstrapTargetLabel()}
|
||||
Bootstrap Server
|
||||
</h2>
|
||||
</div>
|
||||
<Show when={canDismissWizard()}>
|
||||
@@ -527,251 +128,141 @@ export const WorkspaceHome = (props: WorkspaceHomeProps): JSX.Element => {
|
||||
<Show
|
||||
when={!showBootstrapFinishingState()}
|
||||
fallback={
|
||||
<div class={styles.wizardFinishPanel} data-slot="bootstrap-wizard-finishing-state">
|
||||
<div class={styles.wizardFinishShell}>
|
||||
<div class={styles.wizardFinishStatusRow}>
|
||||
<div class={styles.wizardFinishIndicator} data-status={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={materializationState()}>
|
||||
{materializationStatusLabel()}
|
||||
</div>
|
||||
<Show when={materializationMessage()}>
|
||||
<p class={styles.wizardFinishMessage} data-status={materializationState()}>
|
||||
{materializationMessage()}
|
||||
</p>
|
||||
</Show>
|
||||
<Show when={isMaterializationInFlight()}>
|
||||
<p class={styles.wizardFinishHint}>This window will close automatically when setup is complete.</p>
|
||||
</Show>
|
||||
</div>
|
||||
<Show when={hasMaterializationFailed()}>
|
||||
<div class={styles.wizardFinishActions}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.secondaryButton}
|
||||
onClick={(): void => {
|
||||
<BootstrapFinishingState
|
||||
materializationState={materializationState()}
|
||||
statusLabel={materializationStatusLabel()}
|
||||
message={materializationMessage()}
|
||||
isInFlight={isMaterializationInFlight()}
|
||||
hasFailed={hasMaterializationFailed()}
|
||||
onClose={(): void => {
|
||||
setIsFinishingBootstrapFlow(false);
|
||||
setIsWizardOpen(false);
|
||||
}}
|
||||
>
|
||||
Close
|
||||
</button>
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
/>
|
||||
}
|
||||
>
|
||||
<div class={styles.wizardBody}>
|
||||
<aside class={styles.wizardSidebar} data-slot="bootstrap-wizard-sidebar">
|
||||
<nav class={styles.wizardSteps} aria-label="Bootstrap steps">
|
||||
<For each={bootstrapStepDefinitions}>
|
||||
{(step, index): JSX.Element => (
|
||||
<button
|
||||
type="button"
|
||||
class={styles.wizardStepButton}
|
||||
data-active={step.id === currentStep().id ? "true" : "false"}
|
||||
disabled={index() > currentStepIndex()}
|
||||
onClick={(): void => {
|
||||
if (index() <= currentStepIndex()) {
|
||||
setCurrentStepIndex(index());
|
||||
}
|
||||
}}
|
||||
>
|
||||
<span class={styles.wizardStepIndex}>{index() + 1}</span>
|
||||
<span class={styles.wizardStepCopy}>
|
||||
<strong>{step.title}</strong>
|
||||
<Show when={stepStatusLabel(step)}>
|
||||
<small>{stepStatusLabel(step)}</small>
|
||||
<Show when={currentStep().id !== "persona"}>
|
||||
<BootstrapWizardProgress
|
||||
steps={activeWizardSteps()}
|
||||
currentStepId={currentStep().id}
|
||||
currentWizardStepIndex={currentWizardStepIndex()}
|
||||
stepState={stepState}
|
||||
bootstrapStepCount={bootstrapStepCount()}
|
||||
wizardProgressFillWidth={wizardProgressFillWidth()}
|
||||
stepStatusLabel={stepStatusLabel}
|
||||
onSelectStep={navigateToVisibleStep}
|
||||
/>
|
||||
</Show>
|
||||
</span>
|
||||
</button>
|
||||
)}
|
||||
</For>
|
||||
</nav>
|
||||
</aside>
|
||||
|
||||
<div class={styles.wizardStepPanel} data-slot="bootstrap-wizard-step-panel">
|
||||
<Show when={currentStep().id !== "persona" || statusLabel(currentStepState())}>
|
||||
<div class={styles.sectionHeader}>
|
||||
<Show when={currentStep().id !== "persona"}>
|
||||
<div>
|
||||
<span class={styles.wizardStepEyebrow}>{`Step ${currentStepIndex() + 1} of ${bootstrapStepDefinitions.length}`}</span>
|
||||
<h3 class={styles.sectionTitle}>{currentStep().title}</h3>
|
||||
<span class={styles.wizardStepEyebrow}>{`Step ${currentWizardStepIndex() + 1} of ${bootstrapStepCount()}`}</span>
|
||||
</div>
|
||||
</Show>
|
||||
<Show when={statusLabel(currentStepState())}>
|
||||
<div class={styles.statusBadge} data-status={currentStepState().status}>
|
||||
{statusLabel(currentStepState())}
|
||||
</div>
|
||||
</Show>
|
||||
</div>
|
||||
</Show>
|
||||
|
||||
<form class={styles.form} onSubmit={handleCurrentStepSubmit}>
|
||||
<Show when={currentStep().id === "instance"}>
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Protocol</span>
|
||||
<select
|
||||
value={instanceForm.protocol}
|
||||
onInput={(event): void =>
|
||||
setInstanceForm("protocol", event.currentTarget.value as InstanceForm["protocol"])
|
||||
}
|
||||
>
|
||||
<option value="http">http</option>
|
||||
<option value="https">https</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Access</span>
|
||||
<select
|
||||
value={instanceForm.access}
|
||||
onInput={(event): void =>
|
||||
setInstanceForm("access", event.currentTarget.value as InstanceForm["access"])
|
||||
}
|
||||
>
|
||||
<option value="local">local</option>
|
||||
<option value="remote">remote</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Host</span>
|
||||
<input
|
||||
type="text"
|
||||
value={instanceForm.host}
|
||||
onInput={(event): void => setInstanceForm("host", event.currentTarget.value)}
|
||||
placeholder="localhost or app.example.com"
|
||||
<Show when={currentStep().id === "persona"}>
|
||||
<BootstrapPersonaStep
|
||||
personas={bootstrapPersonaDefinitions}
|
||||
hasChosenPersona={hasChosenPersona()}
|
||||
selectedPersona={selectedPersona()}
|
||||
selectedPersonaIsAvailable={selectedPersonaIsAvailable()}
|
||||
onSelectPersona={applyPersonaSelection}
|
||||
/>
|
||||
</Show>
|
||||
|
||||
<Show when={currentStep().id === "instance"}>
|
||||
<BootstrapInstanceStep
|
||||
instanceForm={instanceForm}
|
||||
onProtocolChange={(value): void => setInstanceForm("protocol", value)}
|
||||
onAccessChange={(value): void => setInstanceForm("access", value)}
|
||||
onHostChange={(value): void => setInstanceForm("host", value)}
|
||||
onShowTooltip={showFieldTooltip}
|
||||
onHideTooltip={hideFieldTooltip}
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
</Show>
|
||||
|
||||
<Show when={currentStep().id === "mode"}>
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Mode</span>
|
||||
<select
|
||||
value={modeForm.mode}
|
||||
onInput={(event): void => setModeForm("mode", event.currentTarget.value as ModeForm["mode"])}
|
||||
>
|
||||
<option value="personal">personal</option>
|
||||
<option value="organizational">organizational</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Server name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={modeForm.name}
|
||||
required
|
||||
onInput={(event): void => setModeForm("name", event.currentTarget.value)}
|
||||
placeholder={bootstrapNamePlaceholder()}
|
||||
<BootstrapModeStep
|
||||
modeForm={modeForm}
|
||||
structureForm={structureForm}
|
||||
usesCondensedBootstrapFlow={usesCondensedBootstrapFlow()}
|
||||
selectedPersona={selectedPersona()}
|
||||
namePlaceholder={bootstrapNamePlaceholder()}
|
||||
onNameChange={(value): void => setModeForm("name", value)}
|
||||
onProjectNameChange={(value): void => setStructureForm("projectName", value)}
|
||||
onTeamNameChange={(value): void => setStructureForm("teamName", value)}
|
||||
onShowTooltip={showFieldTooltip}
|
||||
onHideTooltip={hideFieldTooltip}
|
||||
/>
|
||||
</label>
|
||||
</>
|
||||
</Show>
|
||||
|
||||
<Show when={currentStep().id === "admin"}>
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Display name</span>
|
||||
<input
|
||||
type="text"
|
||||
value={adminForm.displayName}
|
||||
onInput={(event): void => setAdminForm("displayName", event.currentTarget.value)}
|
||||
placeholder="Admin"
|
||||
<BootstrapAdminStep
|
||||
adminForm={adminForm}
|
||||
onDisplayNameChange={(value): void => setAdminForm("displayName", value)}
|
||||
onEmailChange={(value): void => setAdminForm("email", value)}
|
||||
onPasswordChange={(value): void => setAdminForm("password", value)}
|
||||
/>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Email</span>
|
||||
<input
|
||||
type="email"
|
||||
value={adminForm.email}
|
||||
onInput={(event): void => setAdminForm("email", event.currentTarget.value)}
|
||||
placeholder="admin@example.com"
|
||||
/>
|
||||
</label>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Password</span>
|
||||
<input
|
||||
type="password"
|
||||
value={adminForm.password}
|
||||
onInput={(event): void => setAdminForm("password", event.currentTarget.value)}
|
||||
placeholder="Create a strong password"
|
||||
/>
|
||||
<small class={styles.fieldHelp}>
|
||||
Use at least 12 characters with uppercase, lowercase, numbers, and symbols.
|
||||
</small>
|
||||
</label>
|
||||
</>
|
||||
</Show>
|
||||
|
||||
<Show when={currentStep().id === "structure"}>
|
||||
<>
|
||||
<label class={styles.field}>
|
||||
<span class={styles.fieldLabel}>Department</span>
|
||||
<input
|
||||
type="text"
|
||||
value={structureForm.departmentName}
|
||||
disabled={modeForm.mode === "personal"}
|
||||
onInput={(event): void => setStructureForm("departmentName", event.currentTarget.value)}
|
||||
placeholder={organizationalStructureDefaults.departmentName}
|
||||
<BootstrapStructureStep
|
||||
mode={modeForm.mode}
|
||||
structureForm={structureForm}
|
||||
onDepartmentNameChange={(value): void => setStructureForm("departmentName", value)}
|
||||
onTeamNameChange={(value): void => setStructureForm("teamName", value)}
|
||||
onProjectNameChange={(value): void => setStructureForm("projectName", value)}
|
||||
onShowTooltip={showFieldTooltip}
|
||||
onHideTooltip={hideFieldTooltip}
|
||||
/>
|
||||
</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 when={currentStep().id !== "persona"}>
|
||||
<div class={styles.wizardFormActions}>
|
||||
<button
|
||||
type="button"
|
||||
class={styles.secondaryButton}
|
||||
disabled={isFirstStep()}
|
||||
onClick={(): void => {
|
||||
setCurrentStepIndex((index) => Math.max(index - 1, 0));
|
||||
}}
|
||||
>
|
||||
<button type="button" class={styles.secondaryButton} disabled={isFirstStep()} onClick={navigateBack}>
|
||||
Back
|
||||
</button>
|
||||
<button
|
||||
type="submit"
|
||||
class={styles.primaryButton}
|
||||
disabled={currentStepState().status === "submitting"}
|
||||
>
|
||||
<button type="submit" class={styles.primaryButton} disabled={currentStepState().status === "submitting"}>
|
||||
{currentStep().buttonLabel}
|
||||
</button>
|
||||
</div>
|
||||
</Show>
|
||||
</form>
|
||||
|
||||
<Show when={currentStepState().error}>
|
||||
<p class={styles.errorText}>{currentStepState().error}</p>
|
||||
</Show>
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</Show>
|
||||
</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>
|
||||
</Portal>
|
||||
</Show>
|
||||
|
||||
Reference in New Issue
Block a user