Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,8 @@ def _mutate(self, data, kind, payload):
elif kind == 'canvas.update':
item = self._editable(data, payload.itemId, unlocking=value.get('locked') is False)
item.update({key: val for key, val in value.items() if key != 'itemId' and (val is not None or key == 'parentId')})
if item.get('color') == '':
item.pop('color')
elif kind == 'canvas.hide':
self._editable(data, payload.itemId)['visible'] = False
elif kind == 'canvas.materialize':
Expand Down
2 changes: 2 additions & 0 deletions packages/core/src/opendirector/domain/creation/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@
Revision = Annotated[int, Field(strict=True, ge=1)]
PositiveInt = Annotated[int, Field(strict=True, ge=1)]
Identifier = Annotated[str, Field(min_length=1, max_length=100, pattern=r'\S')]
# Canvas presentation color: #RRGGBB, or '' in an update to restore the default.
CanvasColor = Annotated[str, Field(pattern=r'^(#[0-9a-fA-F]{6})?$')]
Fingerprint = Annotated[str, Field(pattern=r'^sha256:[0-9a-f]{64}$')]
Digest = Annotated[str, Field(pattern=r'^[0-9a-f]{64}$')]
MediaKind = Literal['text', 'image', 'video', 'audio', 'file']
Expand Down
3 changes: 2 additions & 1 deletion packages/core/src/opendirector/domain/creation/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from opendirector.domain.projects import ProjectError

from .assets import AssetRef
from .base import CanvasItemVersion, Contract, Identifier, Point, Positive, ProjectEntity, unique
from .base import CanvasColor, CanvasItemVersion, Contract, Identifier, Point, Positive, ProjectEntity, unique
from .generation import FollowingSource, GenerationSpec, ResolvedReference, validate_generation
from .models import ModelConfigPublic

Expand Down Expand Up @@ -103,6 +103,7 @@ class CanvasItemBase(ProjectEntity):
height: Positive = Field(default=198, description='Height in pixels.')
zIndex: int = Field(default=0, strict=True, description='Canvas stacking order.')
locked: bool = Field(default=False, description='Whether edits to this object are blocked.')
color: CanvasColor | None = Field(default=None, exclude_if=lambda value: not value, description='Group background color in #RRGGBB format.')
visible: bool = Field(default=True, description='Whether this object is displayed.')
parentId: UUID | None = Field(default=None, description='Parent canvas group ID, or null for the root.')
tags: tuple[Identifier, ...] = Field(default=(), description='User-defined search tags.')
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
from pydantic import ConfigDict, Field, TypeAdapter, create_model, model_validator

from .assets import AssetRef, MediaMetadata
from .base import Contract, Digest, GenerationKind, MediaKind, ObjectVersion, Point, Positive, Revision, digest, unique
from .base import CanvasColor, Contract, Digest, GenerationKind, MediaKind, ObjectVersion, Point, Positive, Revision, digest, unique
from .canvas import CanvasItem
from .editors import EditorDocument
from opendirector.domain.rule_facts import PROMPT_MAX_LENGTH
Expand Down Expand Up @@ -109,6 +109,8 @@ class CanvasPresentationUpdate(Contract):
height: Positive | None = Field(default=None, description='Height in pixels.')
zIndex: int | None = Field(default=None, strict=True, description='Canvas stacking order.')
locked: bool | None = Field(default=None, description='Whether edits to this object are blocked.')
# Omitted when unset so commands recorded before this field keep their fingerprint.
color: CanvasColor | None = Field(default=None, exclude_if=lambda value: value is None, description="Group background color in #RRGGBB format, or '' for the default.")
parentId: UUID | None = Field(default=None, description='Parent canvas group ID, or null for the root.')
# Presence of parentId distinguishes retaining a group from ungrouping.

Expand Down
5 changes: 5 additions & 0 deletions src/backend/creationProjection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ const presentationFields = [
"height",
"zIndex",
"locked",
"color",
"parentId",
] as const;
const extension: Record<string, string> = {
Expand Down Expand Up @@ -602,6 +603,7 @@ export class CreationProjection {
width: item.width,
height: item.height,
locked: item.locked,
...(item.color ? { color: item.color } : {}),
zIndex: item.zIndex,
parentId: item.parentId ?? undefined,
};
Expand Down Expand Up @@ -1594,6 +1596,7 @@ export class CreationProjection {
height: node.height,
zIndex: node.zIndex ?? 0,
locked: node.locked ?? false,
...(node.color ? { color: node.color } : {}),
parentId: node.parentId ?? null,
binding,
} as CanvasItem,
Expand All @@ -1613,6 +1616,7 @@ export class CreationProjection {
height: node.height,
zIndex: node.zIndex ?? 0,
locked: node.locked ?? false,
color: node.color ?? "",
parentId: node.parentId ?? null,
};
const oldPresentation = {
Expand All @@ -1621,6 +1625,7 @@ export class CreationProjection {
height: old?.height,
zIndex: old?.zIndex ?? 0,
locked: old?.locked ?? false,
color: old?.color ?? "",
parentId: old?.parentId ?? null,
};
const changedFields = presentationFields.filter(
Expand Down
90 changes: 80 additions & 10 deletions src/canvas/NodeSelectionToolbar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import type { ToolGlyphName } from "./toolGlyphs";
import { TooltipButton } from "./TooltipButton";
import { GridSplitOptions, SelectionToolbarMenu } from "./SelectionToolbarMenu";
import type { CanvasNode } from "./model";
import type { GroupLayout } from "./operations";
import type { CanvasToolId } from "./toolCatalog";
import { useT } from "../i18n/I18nProvider";
import type { MessageKey } from "../i18n/messages";
Expand Down Expand Up @@ -46,8 +47,26 @@ export interface NodeSelectionToolbarProps {
onRename?: () => void;
onDuplicate?: () => void;
onDelete?: () => void;
/** Group actions: run the members' generation workflow, ungroup, arrange, recolor. */
onRunWorkflow?: () => void;
workflowRunning?: boolean;
onUngroup?: () => void;
onLayout?: (layout: GroupLayout) => void;
onGroupColor?: (color: string) => void;
}

/** Group background presets; "" restores the default style. */
export const GROUP_COLORS: readonly [string, MessageKey][] = [
["", "canvas.selection.group.colorDefault"],
["#8b8f9a", "canvas.selection.group.colorGray"],
["#e5484d", "canvas.selection.group.colorRed"],
["#f76b15", "canvas.selection.group.colorOrange"],
["#ffc53d", "canvas.selection.group.colorYellow"],
["#30a46c", "canvas.selection.group.colorGreen"],
["#3e63dd", "canvas.selection.group.colorBlue"],
["#8e4ec6", "canvas.selection.group.colorPurple"],
];

type Action = {
id: string;
label: string;
Expand All @@ -68,6 +87,10 @@ type MenuOption = {
run?: () => void;
grid?: boolean;
disabled?: boolean;
/** Color swatch shown instead of the icon; "" draws the default swatch. */
swatch?: string;
/** Marks the current choice, such as the active background color. */
checked?: boolean;
};
type OpenMenu = {
nodeId: string;
Expand Down Expand Up @@ -122,6 +145,11 @@ export function NodeSelectionToolbar({
onRename,
onDuplicate,
onDelete,
onRunWorkflow,
workflowRunning = false,
onUngroup,
onLayout,
onGroupColor,
}: NodeSelectionToolbarProps) {
const t = useT();
const toolbar = useRef<HTMLDivElement>(null);
Expand Down Expand Up @@ -190,7 +218,38 @@ export function NodeSelectionToolbar({
disabled: locked,
});
};
if (node.type === "image") {
if (node.type === "group") {
if (onRunWorkflow)
editing.push({
id: "run-workflow",
label: workflowRunning ? t("canvas.selection.group.running") : t("canvas.selection.group.run"),
icon: "play",
run: onRunWorkflow,
disabled: workflowRunning || locked,
});
if (onUngroup)
editing.push({ id: "ungroup", label: t("canvas.selection.group.ungroup"), icon: "group", run: onUngroup, disabled: locked });
if (onLayout)
addMenu("layout", t("canvas.selection.group.layout"), "grid", [
{ id: "grid", label: t("canvas.selection.group.layoutGrid"), icon: "grid", run: () => onLayout("grid") },
{ id: "row", label: t("canvas.selection.group.layoutRow"), icon: "referenceArrowsHorizontal", run: () => onLayout("row") },
{ id: "column", label: t("canvas.selection.group.layoutColumn"), icon: "referenceArrowsVertical", run: () => onLayout("column") },
]);
if (onGroupColor)
addMenu(
"group-color",
t("canvas.selection.group.color"),
"palette",
GROUP_COLORS.map(([color, label]) => ({
id: `color-${color || "default"}`,
label: t(label),
icon: "palette",
swatch: color,
checked: (node.color ?? "") === color,
run: () => onGroupColor(color),
})),
);
} else if (node.type === "image") {
for (const [tool, labelKey, icon, glyph] of imageTools)
addTool(tool, t(labelKey), icon, glyph);
addMenu(
Expand Down Expand Up @@ -371,17 +430,18 @@ export function NodeSelectionToolbar({
run: onPreview,
iconOnly: true,
});
if (onDownload && (hasMedia || node.type === "text"))
if (onDownload && (hasMedia || node.type === "text" || node.type === "group"))
outputs.push({
id: "download",
label: t("common.download"),
label: node.type === "group" ? t("canvas.selection.group.download") : t("common.download"),
icon: "download",
run: onDownload,
iconOnly: true,
});

const organization: Action[] = [];
if (onRename)
// A group's bar holds only its own actions; rename and delete stay in the context menu.
if (onRename && node.type !== "group")
organization.push({
id: "rename",
label: t("common.rename"),
Expand All @@ -390,15 +450,15 @@ export function NodeSelectionToolbar({
iconOnly: true,
disabled: locked,
});
if (onDuplicate)
if (onDuplicate && node.type !== "group")
organization.push({
id: "duplicate",
label: t("canvas.selection.duplicate"),
icon: "duplicate",
run: onDuplicate,
iconOnly: true,
});
if (onDelete)
if (onDelete && node.type !== "group")
organization.push({
id: "delete",
label: t("canvas.selection.deleteNode"),
Expand Down Expand Up @@ -495,13 +555,13 @@ export function NodeSelectionToolbar({
}
shortcut={action.id === "output" ? (navigator.platform.includes("Mac") ? "⌘ Enter" : "Ctrl Enter") : undefined}
label={
action.disabled
action.disabled && locked
? t("canvas.selection.locked", { label: action.label })
: action.label
}
tooltipSide="top"
// Labelled buttons already show their text; only icons and lock reasons need a tooltip.
showTooltip={Boolean(action.iconOnly || action.disabled)}
showTooltip={Boolean(action.iconOnly || (action.disabled && locked))}
className={`${action.iconOnly ? "is-icon-only" : ""}${action.destructive ? " is-destructive" : ""}`}
disabled={action.disabled}
onClick={(event) => {
Expand Down Expand Up @@ -590,7 +650,8 @@ export function NodeSelectionToolbar({
<TooltipButton
key={option.id}
data-action={option.id}
role="menuitem"
role={option.checked === undefined ? "menuitem" : "menuitemradio"}
aria-checked={option.checked}
aria-label={option.label}
label={
option.disabled
Expand All @@ -612,12 +673,21 @@ export function NodeSelectionToolbar({
}
}}
>
<CanvasIcon name={option.icon} size={17} />
{option.swatch !== undefined ? (
<span
className={`cw-selection-swatch${option.swatch ? "" : " is-default"}`}
style={option.swatch ? { background: option.swatch } : undefined}
aria-hidden="true"
/>
) : (
<CanvasIcon name={option.icon} size={17} />
)}
<span>
<span>{option.label}</span>
{option.description && <small>{option.description}</small>}
</span>
{option.grid && <CanvasIcon name="chevronRight" size={13} />}
{option.checked && <CanvasIcon name="check" size={14} />}
</TooltipButton>
))
)}
Expand Down
4 changes: 2 additions & 2 deletions src/canvas/SelectionToolbarMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ export function SelectionToolbarMenu({
place();
const items = panel.querySelectorAll<HTMLElement>(
role === "menu"
? '[role="menuitem"]:not(:disabled)'
? '[role="menuitem"]:not(:disabled),[role="menuitemradio"]:not(:disabled)'
: 'input:not(:disabled),button:not(:disabled):not([tabindex="-1"])',
);
(items[initialFocus === "last" ? items.length - 1 : 0] ?? panel).focus({
Expand Down Expand Up @@ -146,7 +146,7 @@ export function SelectionToolbarMenu({
event.preventDefault();
const items = [
...(root.current?.querySelectorAll<HTMLButtonElement>(
'[role="menuitem"]:not(:disabled)',
'[role="menuitem"]:not(:disabled),[role="menuitemradio"]:not(:disabled)',
) ?? []),
];
if (!items.length) return;
Expand Down
80 changes: 80 additions & 0 deletions src/canvas/groupWorkflow.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
import type { CanvasEdge } from "./model.ts";

export interface WorkflowOutcome {
succeeded: string[];
failed: string[];
/** Not run: a referenced member failed, or the step sits on a reference cycle. */
skipped: string[];
}

/**
* Runs workflow steps in reference order. A step starts once every step it
* references, directly or through non-step nodes, has succeeded; steps without pending references run
* concurrently. A failure skips everything downstream of it.
*/
export async function runWorkflowSteps(
stepIds: readonly string[],
edges: readonly Pick<CanvasEdge, "source" | "target" | "intent">[],
runStep: (id: string) => Promise<boolean>,
): Promise<WorkflowOutcome> {
const ids = new Set(stepIds);
const sources = new Map<string, string[]>();
for (const edge of edges)
if (edge.intent !== "post_edit_result" && edge.source !== edge.target)
sources.set(edge.target, [...(sources.get(edge.target) ?? []), edge.source]);
// A step depends on the nearest steps upstream of it, also through
// non-step nodes such as a subject or stack that carries a result onward.
const upstream = new Map(
stepIds.map((id) => {
const found = new Set<string>();
const seen = new Set([id]);
const pending = [...(sources.get(id) ?? [])];
while (pending.length) {
const node = pending.pop()!;
if (seen.has(node)) continue;
seen.add(node);
if (ids.has(node)) found.add(node);
else pending.push(...(sources.get(node) ?? []));
}
return [id, found];
}),
);
const outcome = new Map<string, "succeeded" | "failed" | "skipped">();
const started = new Set<string>();
let running = 0;
await new Promise<void>((resolve) => {
const advance = () => {
let progressed = true;
while (progressed) {
progressed = false;
for (const id of stepIds) {
if (started.has(id)) continue;
const sources = [...upstream.get(id)!];
if (sources.some((source) => ["failed", "skipped"].includes(outcome.get(source) ?? ""))) {
started.add(id);
outcome.set(id, "skipped");
progressed = true;
continue;
}
if (!sources.every((source) => outcome.get(source) === "succeeded")) continue;
started.add(id);
running++;
void runStep(id)
.catch(() => false)
.then((succeeded) => {
running--;
outcome.set(id, succeeded ? "succeeded" : "failed");
advance();
});
}
}
if (running) return;
// Whatever never started is waiting on a reference cycle.
for (const id of stepIds) if (!outcome.has(id)) outcome.set(id, "skipped");
resolve();
};
advance();
});
const pick = (state: string) => stepIds.filter((id) => outcome.get(id) === state);
return { succeeded: pick("succeeded"), failed: pick("failed"), skipped: pick("skipped") };
}
1 change: 1 addition & 0 deletions src/canvas/history.ts
Original file line number Diff line number Diff line change
Expand Up @@ -113,6 +113,7 @@ function sameNode(a: CanvasNode, b: CanvasNode): boolean {
a.width === b.width &&
a.height === b.height &&
a.locked === b.locked &&
(a.color ?? "") === (b.color ?? "") &&
a.zIndex === b.zIndex &&
a.parentId === b.parentId &&
sameNodeData(a.data, b.data)
Expand Down
2 changes: 2 additions & 0 deletions src/canvas/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -254,6 +254,8 @@ export interface CanvasNode {
width: number;
height: number;
locked?: boolean;
/** Group background color (#rrggbb); absent means the default group style. */
color?: string;
zIndex?: number;
/** Child positions are relative to their parent's top-left corner. */
parentId?: string;
Expand Down
Loading
Loading