Refactor the TypeScript data flow for full type safety and auto-generation of Rust types (#3865)

* Migrate Specta to Tsify to auto-generate messages.ts, working except colors and widgets

* Adopt the generated FillColor/Color/GradientStops

* Fix widget typing

* Separate WidgetGroup enum variants into wrapper structs

* Small rename

* Simplify widgets further

* Clean up message type references

* Switch type imports to the auto-generated file

* Remove lowercase serde rename

* Fix FillChoice deserialization

* Fix small regression from #3837

* Improve type safety

* Make WidgetSpan type-safe

* More cleanup and type safety

* More type safety

* More type safety

* Get the rest to type-check without errors; improve widget builder macro to have optional icons; improve Svelte 5 configs

* Cargo fmt

* Fix imports

* Update outdated readme info

* Fix lint command rename references

* Fix typos

* One more typos fix

* Remove unnecessary dep: prefix from the edited Cargo.toml files

* Remove excess parts from Cargo.toml

* Fix compiling on desktop

* Revert "Remove excess parts from Cargo.toml"

This reverts commit 6b711117b3a5d5d8a3ee20f36a43bc74930b7c82.

* Update dev docs with simpler, more accurate instructions
This commit is contained in:
Keavon Chambers
2026-03-09 16:35:04 -07:00
parent fbd2658148
commit 52d2b38a82
199 changed files with 2265 additions and 2811 deletions
@@ -1,6 +1,5 @@
<script lang="ts">
import type { Layout, LayoutTarget } from "@graphite/messages";
import { isWidgetSpanColumn, isWidgetSpanRow, isWidgetTable, isWidgetSection } from "@graphite/utility-functions/widgets";
import type { Layout, LayoutTarget } from "@graphite/../wasm/pkg/graphite_wasm";
import WidgetSection from "@graphite/components/widgets/WidgetSection.svelte";
import WidgetSpan from "@graphite/components/widgets/WidgetSpan.svelte";
@@ -14,12 +13,14 @@
</script>
{#each layout as layoutGroup}
{#if isWidgetSpanRow(layoutGroup) || isWidgetSpanColumn(layoutGroup)}
<WidgetSpan widgetData={layoutGroup} {layoutTarget} class={className} {classes} />
{:else if isWidgetSection(layoutGroup)}
<WidgetSection widgetData={layoutGroup} {layoutTarget} class={className} {classes} />
{:else if isWidgetTable(layoutGroup)}
<WidgetTable widgetData={layoutGroup} {layoutTarget} unstyled={layoutGroup.unstyled} />
{#if "Row" in layoutGroup}
<WidgetSpan direction="row" widgets={layoutGroup.Row.rowWidgets} {layoutTarget} class={className} {classes} />
{:else if "Column" in layoutGroup}
<WidgetSpan direction="column" widgets={layoutGroup.Column.columnWidgets} {layoutTarget} class={className} {classes} />
{:else if "Section" in layoutGroup}
<WidgetSection widgetData={layoutGroup.Section} {layoutTarget} class={className} {classes} />
{:else if "Table" in layoutGroup}
<WidgetTable widgetData={layoutGroup.Table} {layoutTarget} />
{/if}
{/each}
@@ -1,9 +1,8 @@
<script lang="ts">
import { getContext } from "svelte";
import type { LayoutTarget, WidgetSection as WidgetSectionData } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import type { WidgetSection as WidgetSectionData, LayoutTarget } from "@graphite/messages";
import { isWidgetSpanRow, isWidgetSection } from "@graphite/utility-functions/widgets";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
@@ -62,10 +61,10 @@
{#if expanded}
<LayoutCol class="body" data-block-hover-transfer>
{#each widgetData.layout as layoutGroup}
{#if isWidgetSpanRow(layoutGroup)}
<WidgetSpan widgetData={layoutGroup} {layoutTarget} />
{:else if isWidgetSection(layoutGroup)}
<svelte:self widgetData={layoutGroup} {layoutTarget} />
{#if "Row" in layoutGroup}
<WidgetSpan direction="row" widgets={layoutGroup.Row.rowWidgets} {layoutTarget} />
{:else if "Section" in layoutGroup}
<svelte:self widgetData={layoutGroup.Section} {layoutTarget} />
{/if}
{/each}
</LayoutCol>
+104 -78
View File
@@ -1,11 +1,10 @@
<script lang="ts">
import { getContext } from "svelte";
import type { LayoutTarget, Widget, WidgetInstance } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import type { LayoutTarget, WidgetInstance, WidgetPropsNames, WidgetPropsSet, WidgetTypes, WidgetSpanColumn, WidgetSpanRow } from "@graphite/messages";
import { parseFillChoice } from "@graphite/utility-functions/colors";
import { debouncer } from "@graphite/utility-functions/debounce";
import { isWidgetSpanColumn, isWidgetSpanRow, createLayoutGroup } from "@graphite/utility-functions/widgets";
import NodeCatalog from "@graphite/components/floating-menus/NodeCatalog.svelte";
import BreadcrumbTrailButtons from "@graphite/components/widgets/buttons/BreadcrumbTrailButtons.svelte";
@@ -30,9 +29,17 @@
import ShortcutLabel from "@graphite/components/widgets/labels/ShortcutLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
// Extract the discriminant key names from the Widget tagged enum union (e.g. "TextButton" | "CheckboxInput" | ...)
type WidgetKind = Widget extends infer T ? (T extends Record<infer K, unknown> ? K & string : never) : never;
// Extract the props type for a specific widget kind (e.g. WidgetProps<"TextButton"> gives the Wasm-generated TextButton interface)
type WidgetProps<K extends WidgetKind> = Extract<Widget, Record<K, unknown>>[K];
// A Widget tagged enum unwrapped into a correlated [kind, props] tuple
type UnwrappedWidget = { [K in WidgetKind]: [kind: K, props: WidgetProps<K>] }[WidgetKind];
const editor = getContext<Editor>("editor");
export let widgetData: WidgetSpanRow | WidgetSpanColumn;
export let widgets: WidgetInstance[];
export let direction: "row" | "column";
export let layoutTarget: LayoutTarget;
let className = "";
@@ -45,21 +52,6 @@
.flatMap(([className, stateName]) => (stateName ? [className] : []))
.join(" ");
$: direction = watchDirection(widgetData);
$: widgets = watchWidgets(widgetData);
function watchDirection(widgetData: WidgetSpanRow | WidgetSpanColumn): "row" | "column" | undefined {
if (isWidgetSpanRow(widgetData)) return "row";
if (isWidgetSpanColumn(widgetData)) return "column";
}
function watchWidgets(widgetData: WidgetSpanRow | WidgetSpanColumn): WidgetInstance[] {
let widgets: WidgetInstance[] = [];
if (isWidgetSpanRow(widgetData)) widgets = widgetData.rowWidgets;
else if (isWidgetSpanColumn(widgetData)) widgets = widgetData.columnWidgets;
return widgets;
}
function widgetValueCommit(widgetIndex: number, value: unknown) {
editor.handle.widgetValueCommit(layoutTarget, widgets[widgetIndex].widgetId, value);
}
@@ -72,32 +64,66 @@
editor.handle.widgetValueCommitAndUpdate(layoutTarget, widgets[widgetIndex].widgetId, value, resendWidget);
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
function exclude(props: WidgetPropsSet, additional?: string[]): Record<string, any> {
const exclusions = new Set(["kind", ...(additional || [])]);
return Object.fromEntries(Object.entries(props).filter(([key]) => !exclusions.has(key)));
// Extracts the kind and props from a Widget tagged enum, validated against the widget registry.
// The overload declares the precise correlated return type while the implementation uses broader types.
function unwrapWidget(widgetInstance: WidgetInstance): UnwrappedWidget | undefined;
function unwrapWidget(widgetInstance: WidgetInstance) {
const entry = Object.entries(widgetInstance.widget)[0];
if (!entry || !(entry[0] in widgetResolvers)) return undefined;
return entry;
}
type WidgetConfig = {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
component: any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
getProps(props: WidgetPropsSet, widgetIndex: number): Record<string, any> | undefined;
getSlotContent?(props: WidgetPropsSet): string;
// Resolves the unwrapped widget through the registry to get its Svelte component and computed props.
function resolveWidget([kind, widgetProps]: UnwrappedWidget, widgetIndex: number) {
const config = widgetResolvers[kind];
return {
component: config.component,
props: config.getProps(widgetProps, widgetIndex),
slot: config.getSlotContent?.(widgetProps),
};
}
// Svelte has no variance-safe base type for component constructors
// eslint-disable-next-line @typescript-eslint/no-explicit-any
type SvelteComponentAny = any;
type WidgetConfig<K extends WidgetKind> = {
component: SvelteComponentAny;
getProps(props: WidgetProps<K>, widgetIndex: number): Record<string, unknown> | undefined;
getSlotContent?(props: WidgetProps<K>): string;
};
const widgetRegistry: Record<WidgetPropsNames, WidgetConfig> = {
// The union of all individual widget props types (distributed across each WidgetKind member)
type AnyWidgetProps = { [K in WidgetKind]: WidgetProps<K> }[WidgetKind];
// Uniform view for runtime lookup — widens the per-kind config types to a single type that
// accepts any widget props, avoiding the correlated unions problem at the call site
type WidgetResolver = {
component: SvelteComponentAny;
getProps(props: AnyWidgetProps, widgetIndex: number): Record<string, unknown> | undefined;
getSlotContent?(props: AnyWidgetProps): string;
};
// Overload: callers provide the precise mapped type (preserving per-entry type inference).
// Implementation: receives/returns the widened uniform type (no cast needed).
// Method syntax bivariance makes WidgetConfig<K> assignable to WidgetResolver in the overload check.
function createWidgetResolvers(registry: { [K in WidgetKind]: WidgetConfig<K> }): Record<WidgetKind, WidgetResolver>;
function createWidgetResolvers(registry: Record<WidgetKind, WidgetResolver>): Record<WidgetKind, WidgetResolver> {
return registry;
}
const widgetResolvers = createWidgetResolvers({
CheckboxInput: {
component: CheckboxInput,
getProps: (props: WidgetTypes["CheckboxInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
$$events: { checked: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, true) },
}),
},
ColorInput: {
component: ColorInput,
getProps: (props: WidgetTypes["ColorInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
value: parseFillChoice(props.value),
$$events: {
value: (e: CustomEvent) => widgetValueUpdate(index, e.detail, false),
@@ -108,8 +134,8 @@
CurveInput: {
// TODO: CurvesInput is currently unused
component: CurveInput,
getProps: (props: WidgetTypes["CurveInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
$$events: {
value: (e: CustomEvent) => debouncer((value: unknown) => widgetValueCommitAndUpdate(index, value, false), { debounceTime: 120 }).debounceUpdateValue(e.detail),
},
@@ -117,8 +143,8 @@
},
DropdownInput: {
component: DropdownInput,
getProps: (props: WidgetTypes["DropdownInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
$$events: {
hoverInEntry: (e: CustomEvent) => widgetValueUpdate(index, e.detail, false),
hoverOutEntry: (e: CustomEvent) => widgetValueUpdate(index, e.detail, false),
@@ -128,51 +154,51 @@
},
ParameterExposeButton: {
component: ParameterExposeButton,
getProps: (props: WidgetTypes["ParameterExposeButton"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
action: () => widgetValueCommitAndUpdate(index, undefined, true),
}),
},
IconButton: {
component: IconButton,
getProps: (props: WidgetTypes["IconButton"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
action: () => widgetValueCommitAndUpdate(index, undefined, true),
}),
},
IconLabel: {
component: IconLabel,
getProps: (props: WidgetTypes["IconLabel"]) => exclude(props),
getProps: (props) => ({ ...props }),
},
ShortcutLabel: {
component: ShortcutLabel,
getProps: (props: WidgetTypes["ShortcutLabel"]) => {
getProps: (props) => {
if (!props.shortcut) return undefined;
return exclude(props);
return { ...props };
},
},
ImageLabel: {
component: ImageLabel,
getProps: (props: WidgetTypes["ImageLabel"]) => exclude(props),
getProps: (props) => ({ ...props }),
},
ImageButton: {
component: ImageButton,
getProps: (props: WidgetTypes["ImageButton"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
action: () => widgetValueCommitAndUpdate(index, undefined, true),
}),
},
NodeCatalog: {
component: NodeCatalog,
getProps: (props: WidgetTypes["NodeCatalog"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
$$events: { selectNodeType: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, false) },
}),
},
NumberInput: {
component: NumberInput,
getProps: (props: WidgetTypes["NumberInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
incrementCallbackIncrease: () => widgetValueCommitAndUpdate(index, "Increment", false),
incrementCallbackDecrease: () => widgetValueCommitAndUpdate(index, "Decrement", false),
$$events: {
@@ -183,80 +209,80 @@
},
ReferencePointInput: {
component: ReferencePointInput,
getProps: (props: WidgetTypes["ReferencePointInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
$$events: { value: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, true) },
}),
},
PopoverButton: {
component: PopoverButton,
getProps: (props: WidgetTypes["PopoverButton"]) => ({
...exclude(props),
getProps: (props) => ({
...props,
layoutTarget,
popoverLayout: props.popoverLayout.map(createLayoutGroup),
}),
},
RadioInput: {
component: RadioInput,
getProps: (props: WidgetTypes["RadioInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
$$events: { selectedIndex: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, true) },
}),
},
Separator: {
component: Separator,
getProps: (props: WidgetTypes["Separator"]) => exclude(props),
getProps: (props) => ({ ...props }),
},
WorkingColorsInput: {
component: WorkingColorsInput,
getProps: (props: WidgetTypes["WorkingColorsInput"]) => exclude(props),
getProps: (props) => ({ ...props }),
},
TextAreaInput: {
component: TextAreaInput,
getProps: (props: WidgetTypes["TextAreaInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
$$events: { commitText: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, false) },
}),
},
TextButton: {
component: TextButton,
getProps: (props: WidgetTypes["TextButton"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
action: () => widgetValueCommitAndUpdate(index, [], true),
$$events: { selectedEntryValuePath: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, false) },
}),
},
BreadcrumbTrailButtons: {
component: BreadcrumbTrailButtons,
getProps: (props: WidgetTypes["BreadcrumbTrailButtons"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
action: (breadcrumbIndex: number) => widgetValueCommitAndUpdate(index, breadcrumbIndex, true),
}),
},
TextInput: {
component: TextInput,
getProps: (props: WidgetTypes["TextInput"], index) => ({
...exclude(props),
getProps: (props, index) => ({
...props,
$$events: { commitText: (e: CustomEvent) => widgetValueCommitAndUpdate(index, e.detail, true) },
}),
},
TextLabel: {
component: TextLabel,
getProps: (props: WidgetTypes["TextLabel"]) => exclude(props, ["value"]),
getSlotContent: (props: WidgetTypes["TextLabel"]) => props.value,
getProps: ({ value: _, ...rest }) => rest,
getSlotContent: (props) => props.value,
},
};
});
</script>
<div class={`widget-span ${className} ${extraClasses}`.trim()} class:narrow class:row={direction === "row"} class:column={direction === "column"}>
{#each widgets as widget, widgetIndex}
{@const config = widgetRegistry[widget.props.kind]}
{@const props = config?.getProps(widget.props, widgetIndex)}
{@const slot = config?.getSlotContent?.(widget.props)}
{#if props !== undefined && slot !== undefined}
<svelte:component this={config.component} {...props}>{slot}</svelte:component>
{:else if props !== undefined}
<svelte:component this={config.component} {...props} />
{@const unwrapped = unwrapWidget(widget)}
{#if unwrapped}
{@const { component, props, slot } = resolveWidget(unwrapped, widgetIndex)}
{#if props !== undefined && slot !== undefined}
<svelte:component this={component} {...props}>{slot}</svelte:component>
{:else if props !== undefined}
<svelte:component this={component} {...props} />
{/if}
{/if}
{/each}
</div>
@@ -1,22 +1,21 @@
<script lang="ts">
import type { LayoutTarget, WidgetTable as WidgetTableData } from "@graphite/messages";
import type { LayoutTarget, WidgetTable } from "@graphite/../wasm/pkg/graphite_wasm";
import WidgetSpan from "@graphite/components/widgets/WidgetSpan.svelte";
export let widgetData: WidgetTableData;
export let widgetData: WidgetTable;
export let layoutTarget: LayoutTarget;
export let unstyled = false;
$: columns = widgetData.tableWidgets.length > 0 ? widgetData.tableWidgets[0].length : 0;
</script>
<table class:unstyled>
<table class:unstyled={widgetData.unstyled}>
<tbody>
{#each widgetData.tableWidgets as row}
<tr>
{#each row as cell}
<td colspan={row.length < columns ? columns - row.length + 1 : undefined}>
<WidgetSpan widgetData={{ rowWidgets: [cell] }} {layoutTarget} narrow={true} />
<WidgetSpan direction="row" widgets={[cell]} {layoutTarget} narrow={true} />
</td>
{/each}
</tr>
@@ -1,5 +1,5 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/messages";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import TextButton from "@graphite/components/widgets/buttons/TextButton.svelte";
@@ -1,6 +1,6 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName, IconSize } from "@graphite/icons";
import type { ActionShortcut } from "@graphite/messages";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
@@ -1,5 +1,5 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/messages";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { IMAGE_BASE64_STRINGS } from "@graphite/utility-functions/images";
let className = "";
@@ -1,5 +1,5 @@
<script lang="ts">
import type { FrontendGraphDataType, ActionShortcut } from "@graphite/messages";
import type { FrontendGraphDataType, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
@@ -1,8 +1,7 @@
<script lang="ts">
import type { MenuDirection, ActionShortcut, Layout, LayoutTarget } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName, PopoverButtonStyle } from "@graphite/icons";
import type { MenuDirection, ActionShortcut, Layout, LayoutTarget } from "@graphite/messages";
import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconButton from "@graphite/components/widgets/buttons/IconButton.svelte";
@@ -1,8 +1,8 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { MenuListEntry, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName } from "@graphite/icons";
import type { MenuListEntry, ActionShortcut } from "@graphite/messages";
import MenuList from "@graphite/components/floating-menus/MenuList.svelte";
import ConditionalWrapper from "@graphite/components/layout/ConditionalWrapper.svelte";
@@ -53,7 +53,7 @@
}
// Focus the target so that keyboard inputs are sent to the dropdown
(e.target as HTMLElement | undefined)?.focus();
if (e.target instanceof HTMLElement) e.target.focus();
// Open the menu list floating menu
if (self) self.open = true;
@@ -1,8 +1,8 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName } from "@graphite/icons";
import type { ActionShortcut } from "@graphite/messages";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
@@ -12,7 +12,7 @@
// Content
export let checked = false;
export let icon: IconName = "Checkmark";
export let icon: IconName | undefined = undefined;
export let forLabel: bigint | undefined = undefined;
export let disabled = false;
// Tooltips
@@ -23,7 +23,7 @@
let inputElement: HTMLInputElement | undefined;
$: id = forLabel !== undefined ? String(forLabel) : backupId;
$: displayIcon = (!checked && icon === "Checkmark" ? "Empty12px" : icon) as IconName;
$: displayIcon = !checked && (!icon || icon === "Checkmark") ? "Empty12px" : icon || "Checkmark";
export function isChecked() {
return checked;
@@ -34,8 +34,8 @@
}
function toggleCheckboxFromLabel(e: KeyboardEvent) {
const target = (e.target || undefined) as HTMLLabelElement | undefined;
const previousSibling = (target?.previousSibling || undefined) as HTMLInputElement | undefined;
const target = e.target instanceof HTMLLabelElement ? e.target : undefined;
const previousSibling = target?.previousSibling instanceof HTMLInputElement ? target.previousSibling : undefined;
previousSibling?.click();
}
</script>
@@ -1,9 +1,8 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { FillChoice, MenuDirection, ActionShortcut } from "@graphite/messages";
import type { Color } from "@graphite/messages";
import { contrastingOutlineFactor, isColor, isGradient, colorToHexOptionalAlpha, gradientToLinearGradientCSS } from "@graphite/utility-functions/colors";
import type { FillChoice, MenuDirection, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { contrastingOutlineFactor, fillChoiceColor, fillChoiceGradientStops, colorToHexOptionalAlpha, gradientToLinearGradientCSS } from "@graphite/utility-functions/colors";
import ColorPicker from "@graphite/components/floating-menus/ColorPicker.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
@@ -27,9 +26,15 @@
$: outlineFactor = contrastingOutlineFactor(value, ["--color-1-nearblack", "--color-3-darkgray"], 0.01);
$: outlined = outlineFactor > 0.0001;
$: chosenGradient = isGradient(value) ? gradientToLinearGradientCSS(value) : `linear-gradient(${colorToHexOptionalAlpha(value)}, ${colorToHexOptionalAlpha(value)})`;
$: none = isColor(value) ? value.none : false;
$: transparency = isGradient(value) ? value.color.some((color: Color) => color.alpha < 1) : value.alpha < 1;
$: gradientStops = fillChoiceGradientStops(value);
$: solidColor = fillChoiceColor(value);
$: chosenGradient = gradientStops
? gradientToLinearGradientCSS(gradientStops)
: solidColor
? `linear-gradient(${colorToHexOptionalAlpha(solidColor)}, ${colorToHexOptionalAlpha(solidColor)})`
: undefined;
$: none = value === "None";
$: transparency = gradientStops ? gradientStops.color.some((color) => color.alpha < 1) : solidColor ? solidColor.alpha < 1 : false;
</script>
<LayoutCol class="color-button" classes={{ open, disabled, narrow, none, transparency, outlined, "direction-top": menuDirection === "Top" }} {tooltipLabel} {tooltipDescription} {tooltipShortcut}>
@@ -1,7 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { Curve, CurveManipulatorGroup, ActionShortcut } from "@graphite/messages";
import type { Curve, CurveManipulatorGroup, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { clamp } from "@graphite/utility-functions/math";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
@@ -1,14 +1,25 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { MenuListEntry, ActionShortcut } from "@graphite/messages";
import type { MenuListEntry, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import MenuList from "@graphite/components/floating-menus/MenuList.svelte";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
import TextLabel from "@graphite/components/widgets/labels/TextLabel.svelte";
const DASH_ENTRY = { value: "", label: "-" };
const DASH_ENTRY: MenuListEntry = {
value: "",
label: "-",
icon: undefined,
disabled: false,
children: [],
childrenHash: 0n,
font: undefined,
tooltipLabel: "",
tooltipDescription: "",
tooltipShortcut: undefined,
};
const dispatch = createEventDispatcher<{ selectedIndex: number; hoverInEntry: number; hoverOutEntry: number }>();
@@ -49,13 +60,13 @@
}
// Called only when `selectedIndex` is changed from outside this component
function watchSelectedIndex(_?: typeof selectedIndex) {
function watchSelectedIndex(_: typeof selectedIndex) {
activeEntrySkipWatcher = true;
activeEntry = makeActiveEntry();
}
// Called only when `entries` is changed from outside this component
function watchEntries(_?: typeof entries) {
function watchEntries(_: typeof entries) {
activeEntrySkipWatcher = true;
activeEntry = makeActiveEntry();
}
@@ -102,7 +113,7 @@
}
function unFocusDropdownBox(e: FocusEvent) {
const blurTarget = (e.target as HTMLDivElement | undefined)?.closest("[data-dropdown-input]") || undefined;
const blurTarget = (e.target instanceof Element ? e.target.closest("[data-dropdown-input]") : undefined) || undefined;
if (blurTarget !== self?.div?.()) open = false;
}
</script>
@@ -1,7 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ActionShortcut } from "@graphite/messages";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { operatingSystem } from "@graphite/utility-functions/platform";
import { preventEscapeClosingParentFloatingMenu } from "@graphite/components/layout/FloatingMenu.svelte";
@@ -1,11 +1,11 @@
<script lang="ts">
import { createEventDispatcher, onMount, onDestroy, getContext } from "svelte";
import { evaluateMathExpression } from "@graphite/../wasm/pkg/graphite_wasm";
import { evaluateMathExpression, isPlatformNative } from "@graphite/../wasm/pkg/graphite_wasm";
import type { NumberInputMode, NumberInputIncrementBehavior, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import { PRESS_REPEAT_DELAY_MS, PRESS_REPEAT_INTERVAL_MS } from "@graphite/io-managers/input";
import type { NumberInputMode, NumberInputIncrementBehavior, ActionShortcut } from "@graphite/messages";
import { browserVersion, isDesktop } from "@graphite/utility-functions/platform";
import { browserVersion } from "@graphite/utility-functions/platform";
import { preventEscapeClosingParentFloatingMenu } from "@graphite/components/layout/FloatingMenu.svelte";
import FieldInput from "@graphite/components/widgets/inputs/FieldInput.svelte";
@@ -43,8 +43,8 @@
export let isInteger = false;
/// `incrementBehavior` is only applicable with a `mode` of "Increment".
/// "Add"/"Multiply": The value is added or multiplied by `step`.
/// "None": the increment arrows are not shown.
/// "Callback": the functions `incrementCallbackIncrease` and `incrementCallbackDecrease` call custom behavior.
/// "None": the increment arrows are not shown.
export let incrementBehavior: NumberInputIncrementBehavior = "Add";
export let displayDecimalPlaces = 2;
export let unit = "";
@@ -364,7 +364,7 @@
// Because "mousemove" (and similarly, the "pointermove" event we use) is defined as not being a user-initiated "engagement gesture" event,
// Safari never lets us to enter pointer lock while the mouse button is held down and we are awaiting movement to begin dragging the slider.
const isSafari = browserVersion().toLowerCase().includes("safari");
const usePointerLock = !isSafari && !isDesktop();
const usePointerLock = !isSafari && !isPlatformNative();
// On Safari, we use a workaround involving an alternative strategy where we hide the cursor while it's within the web page
// (but we can't hide it when it ventures outside the page), taking advantage of a separate (helpful) Safari bug where it
@@ -377,7 +377,7 @@
// Enter dragging state
if (usePointerLock) target.requestPointerLock();
if (isDesktop()) {
if (isPlatformNative()) {
editor.handle.appWindowPointerLock();
}
initialValueBeforeDragging = value;
@@ -427,11 +427,11 @@
}
ignoredFirstMovement = true;
};
// On desktop we don't get `pointermove` events while in pointer lock (cef doesn't support pointer lock).
// On desktop we don't get `pointermove` events while in pointer lock (CEF doesn't support pointer lock).
// We have to listen for our custom `pointerlockmove` events instead.
const pointerLockMove = (e: Event) => {
if (ignoredFirstMovement && initialValueBeforeDragging !== undefined && e instanceof CustomEvent) {
const delta = (e.detail as { x: number }).x;
const pointerLockMove = ({ detail }: WindowEventMap["pointerlockmove"]) => {
if (ignoredFirstMovement && initialValueBeforeDragging !== undefined) {
const delta = detail.x;
pointerLockMoveUpdate(delta, shiftKeyDown, ctrlKeyDown, initialValueBeforeDragging);
}
ignoredFirstMovement = true;
@@ -1,7 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { RadioEntryData } from "@graphite/messages";
import type { RadioEntryData } from "@graphite/../wasm/pkg/graphite_wasm";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
import IconLabel from "@graphite/components/widgets/labels/IconLabel.svelte";
@@ -1,7 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ReferencePoint, ActionShortcut } from "@graphite/messages";
import type { ReferencePoint, ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
const dispatch = createEventDispatcher<{ value: ReferencePoint }>();
@@ -1,7 +1,3 @@
<script lang="ts" context="module">
export type RulerDirection = "Horizontal" | "Vertical";
</script>
<script lang="ts">
import { onMount } from "svelte";
@@ -10,6 +6,8 @@
const MINOR_MARK_THICKNESS = 6;
const MICRO_MARK_THICKNESS = 3;
type RulerDirection = "Horizontal" | "Vertical";
export let direction: RulerDirection = "Vertical";
export let origin: number;
export let numberInterval: number;
@@ -1,7 +1,3 @@
<script lang="ts" context="module">
export type ScrollbarDirection = "Horizontal" | "Vertical";
</script>
<script lang="ts">
import { createEventDispatcher } from "svelte";
@@ -21,7 +17,7 @@
const dispatch = createEventDispatcher<{ trackShift: number; thumbPosition: number; thumbDragStart: undefined; thumbDragEnd: undefined; thumbDragAbort: undefined }>();
export let direction: ScrollbarDirection = "Vertical";
export let direction: "Horizontal" | "Vertical" = "Vertical";
export let thumbPosition = 0.5;
export let thumbLength = 0.5;
@@ -7,8 +7,8 @@
import { createEventDispatcher, onDestroy } from "svelte";
import { evaluateGradientAtPosition } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Color, Gradient } from "@graphite/messages";
import { createColor, colorToHexOptionalAlpha, colorToRgbCSS, gradientFirstColor, gradientLastColor, gradientToLinearGradientCSS } from "@graphite/utility-functions/colors";
import type { Color, GradientStops } from "@graphite/../wasm/pkg/graphite_wasm";
import { colorToHexOptionalAlpha, colorToRgbCSS, gradientFirstColor, gradientLastColor, gradientToLinearGradientCSS } from "@graphite/utility-functions/colors";
import { preventEscapeClosingParentFloatingMenu } from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
@@ -17,11 +17,11 @@
const BUTTON_LEFT = 0;
const BUTTON_RIGHT = 2;
const dispatch = createEventDispatcher<{ activeMarkerIndexChange: { activeMarkerIndex: number | undefined; activeMarkerIsMidpoint: boolean }; gradient: Gradient; dragging: boolean }>();
const dispatch = createEventDispatcher<{ activeMarkerIndexChange: { activeMarkerIndex: number | undefined; activeMarkerIsMidpoint: boolean }; gradient: GradientStops; dragging: boolean }>();
export let gradient: Gradient;
export let gradient: GradientStops;
export let disabled = false;
export let activeMarkerIndex = 0 as number | undefined;
export let activeMarkerIndex: number | undefined = 0;
export let activeMarkerIsMidpoint = false;
// export let disabled = false;
// export let tooltipLabel: string | undefined = undefined;
@@ -114,9 +114,7 @@
if (index === -1) index = gradient.position.length;
// Determine the color of the new stop by evaluating the gradient at the position of the new stop
type ReturnedColor = { red: number; green: number; blue: number; alpha: number };
const evaluated = evaluateGradientAtPosition(position, new Float64Array(gradient.position), new Float64Array(gradient.midpoint), gradient.color) as ReturnedColor;
const color = createColor(evaluated.red, evaluated.green, evaluated.blue, evaluated.alpha);
const color: Color = evaluateGradientAtPosition(position, new Float64Array(gradient.position), new Float64Array(gradient.midpoint), gradient.color);
// Insert the new stop into the gradient
gradient.position.splice(index, 0, position);
@@ -243,7 +241,7 @@
dispatch("gradient", gradient);
}
function toMarkers(gradient: Gradient): { position: number; midpoint: number; color: Color }[] {
function toMarkers(gradient: GradientStops): { position: number; midpoint: number; color: Color }[] {
return gradient.position.map((position, i) => ({
position,
midpoint: gradient.midpoint[i],
@@ -251,7 +249,7 @@
}));
}
function toMidpoints(gradient: Gradient): number[] {
function toMidpoints(gradient: GradientStops): number[] {
if (gradient.position.length < 2) return [];
return gradient.midpoint.slice(0, -1).map((midpoint, i) => {
@@ -1,7 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ActionShortcut } from "@graphite/messages";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import FieldInput from "@graphite/components/widgets/inputs/FieldInput.svelte";
@@ -1,7 +1,7 @@
<script lang="ts">
import { createEventDispatcher } from "svelte";
import type { ActionShortcut } from "@graphite/messages";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import FieldInput from "@graphite/components/widgets/inputs/FieldInput.svelte";
@@ -1,9 +1,9 @@
<script lang="ts">
import { getContext } from "svelte";
import type { Color } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor";
import type { Color } from "@graphite/messages";
import { isColor, colorToRgbaCSS } from "@graphite/utility-functions/colors";
import { fillChoiceColor, colorToRgbaCSS } from "@graphite/utility-functions/colors";
import ColorPicker from "@graphite/components/floating-menus/ColorPicker.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
@@ -43,8 +43,11 @@
<ColorPicker
open={primaryOpen}
on:open={({ detail }) => (primaryOpen = detail)}
colorOrGradient={primary}
on:colorOrGradient={({ detail }) => isColor(detail) && primaryColorChanged(detail)}
colorOrGradient={{ Solid: primary }}
on:colorOrGradient={({ detail }) => {
const color = fillChoiceColor(detail);
if (color) primaryColorChanged(color);
}}
direction="Right"
/>
</LayoutRow>
@@ -53,8 +56,11 @@
<ColorPicker
open={secondaryOpen}
on:open={({ detail }) => (secondaryOpen = detail)}
colorOrGradient={secondary}
on:colorOrGradient={({ detail }) => isColor(detail) && secondaryColorChanged(detail)}
colorOrGradient={{ Solid: secondary }}
on:colorOrGradient={({ detail }) => {
const color = fillChoiceColor(detail);
if (color) secondaryColorChanged(color);
}}
direction="Right"
/>
</LayoutRow>
@@ -1,7 +1,7 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import { ICONS, ICON_SVG_STRINGS } from "@graphite/icons";
import type { IconName } from "@graphite/icons";
import type { ActionShortcut } from "@graphite/messages";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
@@ -1,5 +1,5 @@
<script lang="ts">
import type { ActionShortcut } from "@graphite/messages";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
let className = "";
export { className as class };
@@ -1,5 +1,5 @@
<script lang="ts">
import type { SeparatorDirection, SeparatorStyle } from "@graphite/messages";
import type { SeparatorDirection, SeparatorStyle } from "@graphite/../wasm/pkg/graphite_wasm";
// Content
export let direction: SeparatorDirection = "Horizontal";
@@ -1,6 +1,6 @@
<script lang="ts">
import type { ActionShortcut, Key, LabeledShortcut, MouseMotion } from "@graphite/../wasm/pkg/graphite_wasm";
import type { IconName } from "@graphite/icons";
import type { ActionShortcut, KeyRaw, LabeledShortcut, MouseMotion } from "@graphite/messages";
import { operatingSystem } from "@graphite/utility-functions/platform";
import LayoutRow from "@graphite/components/layout/LayoutRow.svelte";
@@ -16,7 +16,7 @@
if (typeof labeledKeyOrMouseMotion === "string") return { mouseMotion: labeledKeyOrMouseMotion };
// `key` is the name of the `Key` enum in Rust, while `label` is the localized string to display (if it doesn't become an icon)
let key = labeledKeyOrMouseMotion.key;
let key: Key | "Option" = labeledKeyOrMouseMotion.key;
const label = labeledKeyOrMouseMotion.label;
// Replace Alt and Accel keys with their Mac-specific equivalents
@@ -57,7 +57,7 @@
return consolidatedList;
}
function keyboardHintIcon(input: KeyRaw): IconName | undefined {
function keyboardHintIcon(input: Key | "Option"): IconName | undefined {
switch (input) {
case "ArrowDown":
return "KeyboardArrowDown";
@@ -89,7 +89,20 @@
}
function mouseHintIcon(input: MouseMotion): IconName {
return `MouseHint${input}` as IconName;
return {
None: "MouseHintNone" as const,
Lmb: "MouseHintLmb" as const,
Rmb: "MouseHintRmb" as const,
Mmb: "MouseHintMmb" as const,
ScrollUp: "MouseHintScrollUp" as const,
ScrollDown: "MouseHintScrollDown" as const,
Drag: "MouseHintDrag" as const,
LmbDouble: "MouseHintLmbDouble" as const,
LmbDrag: "MouseHintLmbDrag" as const,
RmbDrag: "MouseHintRmbDrag" as const,
RmbDouble: "MouseHintRmbDouble" as const,
MmbDrag: "MouseHintMmbDrag" as const,
}[input];
}
</script>
@@ -1,7 +1,7 @@
<script lang="ts">
import { onMount, onDestroy } from "svelte";
import type { ActionShortcut } from "@graphite/messages";
import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
let className = "";
export { className as class };