Private
Public Access
feat(palette): add Command dataclass and CommandRegistry
This commit is contained in:
@@ -0,0 +1,46 @@
|
|||||||
|
from __future__ import annotations
|
||||||
|
from dataclasses import dataclass, field
|
||||||
|
from typing import Optional, Callable, List, Dict, Any
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class Command:
|
||||||
|
id: str
|
||||||
|
title: str
|
||||||
|
category: str
|
||||||
|
shortcut: Optional[str] = None
|
||||||
|
description: str = ""
|
||||||
|
enabled_when: Optional[str] = None
|
||||||
|
action: Optional[Callable] = None
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass
|
||||||
|
class ScoredCommand:
|
||||||
|
command: Command
|
||||||
|
score: float
|
||||||
|
|
||||||
|
|
||||||
|
class CommandRegistry:
|
||||||
|
def __init__(self) -> None:
|
||||||
|
self._commands: Dict[str, Command] = {}
|
||||||
|
|
||||||
|
def register(self, command_or_callable: Any) -> Any:
|
||||||
|
if isinstance(command_or_callable, Command):
|
||||||
|
cmd = command_or_callable
|
||||||
|
else:
|
||||||
|
cmd = Command(
|
||||||
|
id=command_or_callable.__name__,
|
||||||
|
title=command_or_callable.__name__.replace("_", " ").title(),
|
||||||
|
category="uncategorized",
|
||||||
|
action=command_or_callable,
|
||||||
|
)
|
||||||
|
if cmd.id in self._commands:
|
||||||
|
raise ValueError(f"Command {cmd.id} already registered")
|
||||||
|
self._commands[cmd.id] = cmd
|
||||||
|
return command_or_callable
|
||||||
|
|
||||||
|
def all(self) -> List[Command]:
|
||||||
|
return list(self._commands.values())
|
||||||
|
|
||||||
|
def get(self, command_id: str) -> Optional[Command]:
|
||||||
|
return self._commands.get(command_id)
|
||||||
Reference in New Issue
Block a user