Restructure frontend TS files so managers/stores export destructors instead of returning them from their constructors (#3919)

* Replace parameter passing with getContext and extract destroy functions to module-level exports

* Resend layouts from Rust when editor is re-mounted on HMR

* Code review
This commit is contained in:
Keavon Chambers
2026-03-19 18:25:34 -07:00
committed by GitHub
parent 124b17f609
commit 2e2c4fe180
21 changed files with 983 additions and 897 deletions
@@ -8,6 +8,7 @@ pub enum LayoutMessage {
layout_target: LayoutTarget, layout_target: LayoutTarget,
widget_id: WidgetId, widget_id: WidgetId,
}, },
ResendAllLayouts,
SendLayout { SendLayout {
layout: Layout, layout: Layout,
layout_target: LayoutTarget, layout_target: LayoutTarget,
@@ -33,6 +33,20 @@ impl MessageHandler<LayoutMessage, LayoutMessageContext<'_>> for LayoutMessageHa
// Resend that diff // Resend that diff
self.send_diff(vec![diff], layout_target, responses, action_input_mapping); self.send_diff(vec![diff], layout_target, responses, action_input_mapping);
} }
LayoutMessage::ResendAllLayouts => {
// Collect non-empty layouts and their indices, then clear the stored copies so diffs compute as full re-sends
let layouts_to_resend: Vec<_> = self
.layouts
.iter_mut()
.enumerate()
.filter(|(_, layout)| !layout.0.is_empty())
.map(|(i, layout)| (LayoutTarget::from(i as u8), std::mem::take(layout)))
.collect();
for (layout_target, layout) in layouts_to_resend {
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
}
}
LayoutMessage::SendLayout { layout, layout_target } => { LayoutMessage::SendLayout { layout, layout_target } => {
self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping); self.diff_and_send_layout_to_frontend(layout_target, layout, responses, action_input_mapping);
} }
@@ -20,10 +20,30 @@ impl core::fmt::Display for WidgetId {
} }
} }
macro_rules! define_layout_target {
($($(#[$attr:meta])* $variant:ident),* $(,)?) => {
#[cfg_attr(feature = "wasm", derive(tsify::Tsify))] #[cfg_attr(feature = "wasm", derive(tsify::Tsify))]
#[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)] #[derive(PartialEq, Clone, Debug, Hash, Eq, Copy, serde::Serialize, serde::Deserialize)]
#[repr(u8)] #[repr(u8)]
pub enum LayoutTarget { pub enum LayoutTarget {
$($(#[$attr])* $variant,)*
// KEEP THIS ENUM LAST
// This is a marker that is used to define an array that is used to hold widgets
#[serde(skip)]
_LayoutTargetLength,
}
impl From<u8> for LayoutTarget {
fn from(value: u8) -> Self {
match value {
$(x if x == Self::$variant as u8 => Self::$variant,)*
_ => panic!("Invalid LayoutTarget discriminant: {value}"),
}
}
}
};
}
define_layout_target!(
/// The spreadsheet panel allows for the visualisation of data in the graph. /// The spreadsheet panel allows for the visualisation of data in the graph.
DataPanel, DataPanel,
/// Contains the action buttons at the bottom of the dialog. Must be shown with the `FrontendMessage::DisplayDialog` message. /// Contains the action buttons at the bottom of the dialog. Must be shown with the `FrontendMessage::DisplayDialog` message.
@@ -58,12 +78,7 @@ pub enum LayoutTarget {
WelcomeScreenButtons, WelcomeScreenButtons,
/// The color swatch for the working colors and a flip and reset button found at the bottom of the tool shelf. /// The color swatch for the working colors and a flip and reset button found at the bottom of the tool shelf.
WorkingColors, WorkingColors,
);
// KEEP THIS ENUM LAST
// This is a marker that is used to define an array that is used to hold widgets
#[serde(skip)]
_LayoutTargetLength,
}
/// For use by structs that define a UI widget layout by implementing the layout() function belonging to this trait. /// For use by structs that define a UI widget layout by implementing the layout() function belonging to this trait.
/// The send_layout() function can then be called by other code which is a part of the same struct so as to send the layout to the frontend. /// The send_layout() function can then be called by other code which is a part of the same struct so as to send the layout to the frontend.
+1
View File
@@ -70,6 +70,7 @@ export default defineConfig([
ignoreRestSiblings: true, ignoreRestSiblings: true,
}, },
], ],
"@typescript-eslint/no-non-null-assertion": "error",
"@typescript-eslint/consistent-type-imports": "error", "@typescript-eslint/consistent-type-imports": "error",
"@typescript-eslint/consistent-type-definitions": ["error", "type"], "@typescript-eslint/consistent-type-definitions": ["error", "type"],
"@typescript-eslint/consistent-type-assertions": ["error", { assertionStyle: "never" }], "@typescript-eslint/consistent-type-assertions": ["error", { assertionStyle: "never" }],
+42 -25
View File
@@ -2,20 +2,20 @@
import { onMount, onDestroy, setContext } from "svelte"; import { onMount, onDestroy, setContext } from "svelte";
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
import { createClipboardManager } from "@graphite/managers/clipboard"; import { createClipboardManager, destroyClipboardManager } from "@graphite/managers/clipboard";
import { createFontsManager } from "@graphite/managers/fonts"; import { createFontsManager, destroyFontsManager } from "@graphite/managers/fonts";
import { createHyperlinkManager } from "@graphite/managers/hyperlink"; import { createHyperlinkManager, destroyHyperlinkManager } from "@graphite/managers/hyperlink";
import { createInputManager } from "@graphite/managers/input"; import { createInputManager, destroyInputManager } from "@graphite/managers/input";
import { createLocalizationManager } from "@graphite/managers/localization"; import { createLocalizationManager, destroyLocalizationManager } from "@graphite/managers/localization";
import { createPanicManager } from "@graphite/managers/panic"; import { createPanicManager, destroyPanicManager } from "@graphite/managers/panic";
import { createPersistenceManager } from "@graphite/managers/persistence"; import { createPersistenceManager, destroyPersistenceManager } from "@graphite/managers/persistence";
import { createAppWindowStore } from "@graphite/stores/app-window"; import { createAppWindowStore, destroyAppWindowStore } from "@graphite/stores/app-window";
import { createDialogStore } from "@graphite/stores/dialog"; import { createDialogStore, destroyDialogStore } from "@graphite/stores/dialog";
import { createDocumentStore } from "@graphite/stores/document"; import { createDocumentStore, destroyDocumentStore } from "@graphite/stores/document";
import { createFullscreenStore } from "@graphite/stores/fullscreen"; import { createFullscreenStore, destroyFullscreenStore } from "@graphite/stores/fullscreen";
import { createNodeGraphStore } from "@graphite/stores/node-graph"; import { createNodeGraphStore, destroyNodeGraphStore } from "@graphite/stores/node-graph";
import { createPortfolioStore } from "@graphite/stores/portfolio"; import { createPortfolioStore, destroyPortfolioStore } from "@graphite/stores/portfolio";
import { createTooltipStore } from "@graphite/stores/tooltip"; import { createTooltipStore, destroyTooltipStore } from "@graphite/stores/tooltip";
import MainWindow from "@graphite/components/window/MainWindow.svelte"; import MainWindow from "@graphite/components/window/MainWindow.svelte";
@@ -34,24 +34,41 @@
}; };
Object.entries(stores).forEach(([key, store]) => setContext(key, store)); Object.entries(stores).forEach(([key, store]) => setContext(key, store));
const managers = {
clipboard: createClipboardManager(editor),
hyperlink: createHyperlinkManager(editor),
localization: createLocalizationManager(editor),
panic: createPanicManager(editor),
persistence: createPersistenceManager(editor, stores.portfolio),
fonts: createFontsManager(editor),
input: createInputManager(editor, stores.dialog, stores.portfolio, stores.document, stores.fullscreen),
};
onMount(() => { onMount(() => {
createClipboardManager(editor);
createHyperlinkManager(editor);
createLocalizationManager(editor);
createPanicManager(editor);
createPersistenceManager(editor, stores.portfolio);
createFontsManager(editor);
createInputManager(editor, stores.dialog, stores.portfolio, stores.document);
// Initialize certain setup tasks required by the editor backend to be ready for the user now that the frontend is ready. // Initialize certain setup tasks required by the editor backend to be ready for the user now that the frontend is ready.
// The backend handles idempotency, so this is safe to call again during HMR re-mounts. // The backend handles idempotency, so this is safe to call again during HMR re-mounts.
editor.handle.initAfterFrontendReady(); editor.handle.initAfterFrontendReady();
// Re-send all UI layouts from Rust so the frontend has them after an HMR re-mount
editor.handle.resendAllLayouts();
}); });
onDestroy(() => { onDestroy(() => {
[...Object.values(stores), ...Object.values(managers)].forEach(({ destroy }) => destroy()); // Stores
destroyDialogStore();
destroyTooltipStore();
destroyDocumentStore();
destroyFullscreenStore();
destroyNodeGraphStore();
destroyPortfolioStore();
destroyAppWindowStore();
// Managers
destroyClipboardManager();
destroyHyperlinkManager();
destroyLocalizationManager();
destroyPanicManager();
destroyPersistenceManager();
destroyFontsManager();
destroyInputManager();
}); });
</script> </script>
@@ -3,7 +3,7 @@
import { wipeDocuments } from "@graphite/managers/persistence"; import { wipeDocuments } from "@graphite/managers/persistence";
import type { DialogStore } from "@graphite/stores/dialog"; import type { DialogStore } from "@graphite/stores/dialog";
import { crashReportUrl } from "/src/utility-functions/crash-report"; import { crashReportUrl } from "@graphite/utility-functions/crash-report";
import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte"; import FloatingMenu from "@graphite/components/layout/FloatingMenu.svelte";
import LayoutCol from "@graphite/components/layout/LayoutCol.svelte"; import LayoutCol from "@graphite/components/layout/LayoutCol.svelte";
+11 -12
View File
@@ -1,34 +1,33 @@
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
let currentCleanup: (() => void) | undefined; let editorRef: Editor | undefined = undefined;
let currentArgs: [Editor] | undefined;
export function createClipboardManager(editor: Editor) { export function createClipboardManager(editor: Editor) {
currentArgs = [editor]; editorRef = editor;
// Subscribe to process backend event
editor.subscriptions.subscribeFrontendMessage("TriggerClipboardWrite", (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerClipboardWrite", (data) => {
// If the Clipboard API is supported in the browser, copy text to the clipboard // If the Clipboard API is supported in the browser, copy text to the clipboard
navigator.clipboard?.writeText?.(data.content); navigator.clipboard?.writeText?.(data.content);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerSelectionRead", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerSelectionRead", async (data) => {
editor.handle.readSelection(readAtCaret(data.cut), data.cut); editor.handle.readSelection(readAtCaret(data.cut), data.cut);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerSelectionWrite", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerSelectionWrite", async (data) => {
insertAtCaret(data.content); insertAtCaret(data.content);
}); });
}
export function destroyClipboardManager() {
const editor = editorRef;
if (!editor) return;
function destroy() {
editor.subscriptions.unsubscribeFrontendMessage("TriggerClipboardWrite"); editor.subscriptions.unsubscribeFrontendMessage("TriggerClipboardWrite");
editor.subscriptions.unsubscribeFrontendMessage("TriggerSelectionRead"); editor.subscriptions.unsubscribeFrontendMessage("TriggerSelectionRead");
editor.subscriptions.unsubscribeFrontendMessage("TriggerSelectionWrite"); editor.subscriptions.unsubscribeFrontendMessage("TriggerSelectionWrite");
} }
currentCleanup = destroy;
return { destroy };
}
export type ClipboardManager = ReturnType<typeof createClipboardManager>;
function readAtCaret(cut: boolean): string | undefined { function readAtCaret(cut: boolean): string | undefined {
const element = window.document.activeElement; const element = window.document.activeElement;
@@ -112,6 +111,6 @@ function insertAtCaret(text: string) {
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
currentCleanup?.(); destroyClipboardManager();
if (currentArgs) newModule?.createClipboardManager(...currentArgs); if (editorRef) newModule?.createClipboardManager(editorRef);
}); });
+14 -16
View File
@@ -4,17 +4,16 @@ type ApiResponse = { family: string; variants: string[]; files: Record<string, s
const FONT_LIST_API = "https://api.graphite.art/font-list"; const FONT_LIST_API = "https://api.graphite.art/font-list";
let currentCleanup: (() => void) | undefined; let editorRef: Editor | undefined = undefined;
let currentArgs: [Editor] | undefined; let abortController: AbortController | undefined = undefined;
export function createFontsManager(editor: Editor) { export function createFontsManager(editor: Editor) {
currentArgs = [editor]; editorRef = editor;
const abortController = new AbortController(); abortController = new AbortController();
// Subscribe to process backend events
editor.subscriptions.subscribeFrontendMessage("TriggerFontCatalogLoad", async () => { editor.subscriptions.subscribeFrontendMessage("TriggerFontCatalogLoad", async () => {
try { try {
const response = await fetch(FONT_LIST_API, { signal: abortController.signal }); const response = await fetch(FONT_LIST_API, abortController ? { signal: abortController.signal } : undefined);
if (!response.ok) throw new Error(`Font catalog request failed with status ${response.status}`); if (!response.ok) throw new Error(`Font catalog request failed with status ${response.status}`);
const fontListResponse: { items: ApiResponse } = await response.json(); const fontListResponse: { items: ApiResponse } = await response.json();
const fontListData = fontListResponse.items; const fontListData = fontListResponse.items;
@@ -42,7 +41,7 @@ export function createFontsManager(editor: Editor) {
try { try {
if (!data.url) throw new Error("No URL provided for font data load"); if (!data.url) throw new Error("No URL provided for font data load");
const response = await fetch(data.url, { signal: abortController.signal }); const response = await fetch(data.url, abortController ? { signal: abortController.signal } : undefined);
if (!response.ok) throw new Error(`Font data request failed with status ${response.status}`); if (!response.ok) throw new Error(`Font data request failed with status ${response.status}`);
const buffer = await response.arrayBuffer(); const buffer = await response.arrayBuffer();
const bytes = new Uint8Array(buffer); const bytes = new Uint8Array(buffer);
@@ -54,20 +53,19 @@ export function createFontsManager(editor: Editor) {
console.error("Failed to load font:", error); console.error("Failed to load font:", error);
} }
}); });
}
function destroy() { export function destroyFontsManager() {
abortController.abort(); const editor = editorRef;
if (!editor) return;
abortController?.abort();
editor.subscriptions.unsubscribeFrontendMessage("TriggerFontCatalogLoad"); editor.subscriptions.unsubscribeFrontendMessage("TriggerFontCatalogLoad");
editor.subscriptions.unsubscribeFrontendMessage("TriggerFontDataLoad"); editor.subscriptions.unsubscribeFrontendMessage("TriggerFontDataLoad");
} }
currentCleanup = destroy;
return { destroy };
}
export type FontsManager = ReturnType<typeof createFontsManager>;
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
currentCleanup?.(); destroyFontsManager();
if (currentArgs) newModule?.createFontsManager(...currentArgs); if (editorRef) newModule?.createFontsManager(editorRef);
}); });
+9 -12
View File
@@ -1,27 +1,24 @@
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
let currentCleanup: (() => void) | undefined; let editorRef: Editor | undefined = undefined;
let currentArgs: [Editor] | undefined;
export function createHyperlinkManager(editor: Editor) { export function createHyperlinkManager(editor: Editor) {
currentArgs = [editor]; editorRef = editor;
// Subscribe to process backend event
editor.subscriptions.subscribeFrontendMessage("TriggerVisitLink", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerVisitLink", async (data) => {
window.open(data.url, "_blank", "noopener"); window.open(data.url, "_blank", "noopener");
}); });
}
export function destroyHyperlinkManager() {
const editor = editorRef;
if (!editor) return;
function destroy() {
editor.subscriptions.unsubscribeFrontendMessage("TriggerVisitLink"); editor.subscriptions.unsubscribeFrontendMessage("TriggerVisitLink");
} }
currentCleanup = destroy;
return { destroy };
}
export type HyperlinkManager = ReturnType<typeof createHyperlinkManager>;
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
currentCleanup?.(); destroyHyperlinkManager();
if (currentArgs) newModule?.createHyperlinkManager(...currentArgs); if (editorRef) newModule?.createHyperlinkManager(editorRef);
}); });
+402 -368
View File
@@ -5,7 +5,6 @@ import type { Editor } from "@graphite/editor";
import type { DialogStore } from "@graphite/stores/dialog"; import type { DialogStore } from "@graphite/stores/dialog";
import type { DocumentStore } from "@graphite/stores/document"; import type { DocumentStore } from "@graphite/stores/document";
import { fullscreenModeChanged, toggleFullscreen } from "@graphite/stores/fullscreen"; import { fullscreenModeChanged, toggleFullscreen } from "@graphite/stores/fullscreen";
import type { FullscreenStore } from "@graphite/stores/fullscreen";
import type { PortfolioStore } from "@graphite/stores/portfolio"; import type { PortfolioStore } from "@graphite/stores/portfolio";
import { pasteFile } from "@graphite/utility-functions/files"; import { pasteFile } from "@graphite/utility-functions/files";
import { makeKeyboardModifiersBitfield, textInputCleanup, getLocalizedScanCode } from "@graphite/utility-functions/keyboard-entry"; import { makeKeyboardModifiersBitfield, textInputCleanup, getLocalizedScanCode } from "@graphite/utility-functions/keyboard-entry";
@@ -29,23 +28,17 @@ type EventListenerTarget = {
removeEventListener: typeof window.removeEventListener; removeEventListener: typeof window.removeEventListener;
}; };
let currentCleanup: (() => void) | undefined; let editorRef: Editor | undefined = undefined;
let currentArgs: [Editor, DialogStore, PortfolioStore, DocumentStore, FullscreenStore] | undefined; let dialogStore: DialogStore | undefined = undefined;
let portfolioStore: PortfolioStore | undefined = undefined;
export function createInputManager(editor: Editor, dialog: DialogStore, portfolio: PortfolioStore, document: DocumentStore, fullscreen: FullscreenStore) { let documentStore: DocumentStore | undefined = undefined;
currentArgs = [editor, dialog, portfolio, document, fullscreen];
const appElement = window.document.querySelector("[data-app-container]");
const app = appElement instanceof HTMLElement ? appElement : null;
app?.focus();
let viewportPointerInteractionOngoing = false; let viewportPointerInteractionOngoing = false;
let textToolInteractiveInputElement: HTMLDivElement | undefined = undefined; let textToolInteractiveInputElement: HTMLDivElement | undefined = undefined;
let canvasFocused = true; let canvasFocused = true;
let inPointerLock = false; let inPointerLock = false;
const shakeSamples: { x: number; y: number; time: number }[] = [];
let lastShakeTime = 0; let lastShakeTime = 0;
const shakeSamples: { x: number; y: number; time: number }[] = [];
// Event listeners
const listeners: { target: EventListenerTarget; eventName: EventName; action(event: Event): void; options?: AddEventListenerOptions }[] = [ const listeners: { target: EventListenerTarget; eventName: EventName; action(event: Event): void; options?: AddEventListenerOptions }[] = [
{ target: window, eventName: "beforeunload", action: (e: BeforeUnloadEvent) => onBeforeUnload(e) }, { target: window, eventName: "beforeunload", action: (e: BeforeUnloadEvent) => onBeforeUnload(e) },
@@ -66,338 +59,46 @@ export function createInputManager(editor: Editor, dialog: DialogStore, portfoli
{ target: window.document, eventName: "pointerlockerror", action: onPointerLockChange }, { target: window.document, eventName: "pointerlockerror", action: onPointerLockChange },
]; ];
// Event bindings export function createInputManager(editor: Editor, dialog: DialogStore, portfolio: PortfolioStore, doc: DocumentStore) {
editorRef = editor;
dialogStore = dialog;
portfolioStore = portfolio;
documentStore = doc;
function bindListeners() { editor.subscriptions.subscribeFrontendMessage("TriggerClipboardRead", () => {
// Add event bindings for the lifetime of the application triggerClipboardRead();
listeners.forEach(({ target, eventName, action, options }) => target.addEventListener(eventName, action, options));
}
function unbindListeners() {
// Remove event bindings after the lifetime of the application (or on hot-module replacement during development)
listeners.forEach(({ target, eventName, action, options }) => target.removeEventListener(eventName, action, options));
}
// Keyboard events
async function shouldRedirectKeyboardEventToBackend(e: KeyboardEvent): Promise<boolean> {
// Don't redirect when a dialog is covering the workspace
if (get(dialog).visible) return false;
const key = await getLocalizedScanCode(e);
// TODO: Switch to a system where everything is sent to the backend, then the input preprocessor makes decisions and kicks some inputs back to the frontend
const accelKey = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
// Cut, copy, and paste is handled in the backend on desktop
if (isPlatformNative() && accelKey && ["KeyX", "KeyC", "KeyV"].includes(key)) return true;
// But on web, we want to not redirect paste
if (!isPlatformNative() && key === "KeyV" && accelKey) return false;
// Don't redirect user input from text entry into HTML elements
if (targetIsTextField(e.target || undefined) && key !== "Escape" && !(accelKey && ["Enter", "NumpadEnter"].includes(key))) return false;
// Don't redirect tab or enter if not in canvas (to allow navigating elements)
potentiallyRestoreCanvasFocus(e);
if (
!canvasFocused &&
!targetIsTextField(e.target || undefined) &&
["Tab", "Enter", "NumpadEnter", "Space", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(key) &&
!(e.ctrlKey || e.metaKey || e.altKey)
)
return false;
// Don't redirect if a MenuList is open
if (window.document.querySelector("[data-floating-menu-content]")) return false;
// Web-only keyboard shortcuts
if (!isPlatformNative()) {
// Don't redirect a fullscreen request, but process it immediately instead
if (((operatingSystem() !== "Mac" && key === "F11") || (operatingSystem() === "Mac" && e.ctrlKey && e.metaKey && key === "KeyF")) && e.type === "keydown" && !e.repeat) {
e.preventDefault();
toggleFullscreen();
return false;
}
// Don't redirect a reload request
if (key === "F5") return false;
if (key === "KeyR" && accelKey) return false;
// Don't redirect debugging tools
if (["F12", "F8"].includes(key)) return false;
if (["KeyC", "KeyI", "KeyJ"].includes(key) && accelKey && e.shiftKey) return false;
}
// Redirect to the backend
return true;
}
async function onKeyDown(e: KeyboardEvent) {
const key = await getLocalizedScanCode(e);
const NO_KEY_REPEAT_MODIFIER_KEYS = ["ControlLeft", "ControlRight", "ShiftLeft", "ShiftRight", "MetaLeft", "MetaRight", "AltLeft", "AltRight", "AltGraph", "CapsLock", "Fn", "FnLock"];
if (e.repeat && NO_KEY_REPEAT_MODIFIER_KEYS.includes(key)) return;
if (await shouldRedirectKeyboardEventToBackend(e)) {
e.preventDefault();
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onKeyDown(key, modifiers, e.repeat);
return;
}
if (get(dialog).visible && key === "Escape") {
editor.handle.onDialogDismiss();
}
}
async function onKeyUp(e: KeyboardEvent) {
const key = await getLocalizedScanCode(e);
if (await shouldRedirectKeyboardEventToBackend(e)) {
e.preventDefault();
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onKeyUp(key, modifiers, e.repeat);
}
}
// Pointer events
// While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events and these are handled in the backend
function onPointerMove(e: PointerEvent) {
potentiallyRestoreCanvasFocus(e);
if (!e.buttons) viewportPointerInteractionOngoing = false;
// Don't redirect pointer movement to the backend if there's no ongoing interaction and it's over a floating menu, or the graph overlay, on top of the canvas
// TODO: A better approach is to pass along a boolean to the backend's input preprocessor so it can know if it's being occluded by the GUI.
// TODO: This would allow it to properly decide to act on removing hover focus from something that was hovered in the canvas before moving over the GUI.
// TODO: Further explanation: https://github.com/GraphiteEditor/Graphite/pull/623#discussion_r866436197
const inFloatingMenu = e.target instanceof Element && e.target.closest("[data-floating-menu-content]");
const inGraphOverlay = get(document).graphViewOverlayOpen;
if (!viewportPointerInteractionOngoing && (inFloatingMenu || inGraphOverlay)) return;
const modifiers = makeKeyboardModifiersBitfield(e);
if (detectShake(e)) editor.handle.onMouseShake(e.clientX, e.clientY, e.buttons, modifiers);
editor.handle.onMouseMove(e.clientX, e.clientY, e.buttons, modifiers);
}
function onPointerDown(e: PointerEvent) {
potentiallyRestoreCanvasFocus(e);
const { target } = e;
const inFloatingMenu = target instanceof Element && target.closest("[data-floating-menu-content]");
const isTargetingCanvas = !inFloatingMenu && target instanceof Element && target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
const inDialog = target instanceof Element && target.closest("[data-dialog] [data-floating-menu-content]");
const inContextMenu = target instanceof Element && target.closest("[data-context-menu]");
const inTextInput = target === textToolInteractiveInputElement;
if (get(dialog).visible && !inDialog) {
editor.handle.onDialogDismiss();
e.preventDefault();
e.stopPropagation();
}
if (!inTextInput && !inContextMenu) {
if (textToolInteractiveInputElement) {
const isLeftOrRightClick = e.button === BUTTON_RIGHT || e.button === BUTTON_LEFT;
editor.handle.onChangeText(textInputCleanup(textToolInteractiveInputElement.innerText), isLeftOrRightClick);
} else {
viewportPointerInteractionOngoing = isTargetingCanvas instanceof Element;
}
}
if (viewportPointerInteractionOngoing && isTargetingCanvas instanceof Element) {
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onMouseDown(e.clientX, e.clientY, e.buttons, modifiers);
}
}
function onPointerUp(e: PointerEvent) {
potentiallyRestoreCanvasFocus(e);
// Don't let the browser navigate back or forward when using the buttons on some mice
// TODO: This works in Chrome but not in Firefox
// TODO: Possible workaround: use the browser's history API to block navigation:
// TODO: <https://stackoverflow.com/questions/57102502/preventing-mouse-fourth-and-fifth-buttons-from-navigating-back-forward-in-browse>
if (e.button === BUTTON_BACK || e.button === BUTTON_FORWARD) e.preventDefault();
if (!e.buttons) viewportPointerInteractionOngoing = false;
if (textToolInteractiveInputElement) return;
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onMouseUp(e.clientX, e.clientY, e.buttons, modifiers);
}
// Mouse events
function onPotentialDoubleClick(e: MouseEvent) {
if (textToolInteractiveInputElement || inPointerLock) return;
// Allow only events within the viewport or node graph boundaries
const { target } = e;
const isTargetingCanvas = target instanceof Element && target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
if (!(isTargetingCanvas instanceof Element)) return;
// Allow only repeated increments of double-clicks (not 1, 3, 5, etc.)
if (e.detail % 2 == 1) return;
// `e.buttons` is always 0 in the `mouseup` event, so we have to convert from `e.button` instead
let buttons = 1;
if (e.button === BUTTON_LEFT) buttons = 1; // Left
if (e.button === BUTTON_RIGHT) buttons = 2; // Right
if (e.button === BUTTON_MIDDLE) buttons = 4; // Middle
if (e.button === BUTTON_BACK) buttons = 8; // Back
if (e.button === BUTTON_FORWARD) buttons = 16; // Forward
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onDoubleClick(e.clientX, e.clientY, buttons, modifiers);
}
function onMouseDown(e: MouseEvent) {
// Block middle mouse button auto-scroll mode (the circular gizmo that appears and allows quick scrolling by moving the cursor above or below it)
if (e.button === BUTTON_MIDDLE) e.preventDefault();
}
function onContextMenu(e: MouseEvent) {
if (!targetIsTextField(e.target || undefined) && e.target !== textToolInteractiveInputElement) {
e.preventDefault();
}
}
function onPointerLockChange() {
inPointerLock = Boolean(window.document.pointerLockElement);
}
// Wheel events
function onWheelScroll(e: WheelEvent) {
const { target } = e;
const isTargetingCanvas = target instanceof Element && target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
// Prevent zooming the entire page when using Ctrl + scroll wheel outside of the viewport
if (e.ctrlKey && !isTargetingCanvas) {
e.preventDefault();
}
// Redirect vertical scroll wheel movement into a horizontal scroll on a horizontally scrollable element
// There seems to be no possible way to properly employ the browser's smooth scrolling interpolation
const horizontalScrollableElement = target instanceof Element && target.closest("[data-scrollable-x]");
if (horizontalScrollableElement && e.deltaY !== 0) {
horizontalScrollableElement.scrollTo(horizontalScrollableElement.scrollLeft + e.deltaY, 0);
return;
}
if (isTargetingCanvas) {
e.preventDefault();
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onWheelScroll(e.clientX, e.clientY, e.buttons, e.deltaX, e.deltaY, e.deltaZ, modifiers);
}
}
// Receives a custom event dispatched when the user begins interactively editing with the text tool.
// We keep a copy of the text input element to check against when it's active for text entry.
function onModifyInputField(e: CustomEvent) {
textToolInteractiveInputElement = e.detail;
}
// Window events
async function onBeforeUnload(e: BeforeUnloadEvent) {
const activeDocument = get(portfolio).documents[get(portfolio).activeDocumentIndex];
if (activeDocument && !activeDocument.details.isAutoSaved) editor.handle.triggerAutoSave(activeDocument.id);
// Skip the message if the editor crashed, since work is already lost
if (await editor.handle.hasCrashed()) return;
// Skip the message during development, since it's annoying when testing
if (await editor.handle.inDevelopmentMode()) return;
const allDocumentsSaved = get(portfolio).documents.reduce((acc, doc) => acc && doc.details.isSaved, true);
if (!allDocumentsSaved) {
e.returnValue = "Unsaved work will be lost if the web browser tab is closed. Close anyway?";
e.preventDefault();
}
}
function onPaste(e: ClipboardEvent) {
const dataTransfer = e.clipboardData;
if (!dataTransfer || targetIsTextField(e.target || undefined)) return;
e.preventDefault();
Array.from(dataTransfer.items).forEach(async (item) => {
if (item.type === "text/plain") item.getAsString((text) => editor.handle.pasteText(text));
await pasteFile(item, editor);
}); });
editor.subscriptions.subscribeFrontendMessage("WindowPointerLockMove", (data) => {
// Desktop app only: dispatch custom pointer lock movement events
const event = new CustomEvent("pointerlockmove", { detail: { x: data.position[0], y: data.position[1] } });
window.dispatchEvent(event);
});
// INITIALIZATION
// Focus the app container
const app = window.document.querySelector("[data-app-container]");
if (app instanceof HTMLElement) app.focus();
// Bind the event listeners
bindListeners();
} }
function detectShake(e: PointerEvent | MouseEvent): boolean { // Return the destructor
const SENSITIVITY_DIRECTION_CHANGES = 3; export function destroyInputManager() {
const SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO = 0.1; const editor = editorRef;
const DETECTION_WINDOW_MS = 500; if (!editor) return;
const DEBOUNCE_MS = 1000;
// Add the current mouse position and time to our list of samples unbindListeners();
const now = Date.now(); editor.subscriptions.unsubscribeFrontendMessage("TriggerClipboardRead");
shakeSamples.push({ x: e.clientX, y: e.clientY, time: now }); editor.subscriptions.unsubscribeFrontendMessage("WindowPointerLockMove");
// Remove samples that are older than our time window
while (shakeSamples.length > 0 && now - shakeSamples[0].time > DETECTION_WINDOW_MS) {
shakeSamples.shift();
} }
// We can't be shaking if it's too early in terms of samples or debounce time async function triggerClipboardRead() {
if (shakeSamples.length <= 3 || now - lastShakeTime <= DEBOUNCE_MS) return false; const editor = editorRef;
if (!editor) return;
// Calculate the total distance traveled
let totalDistanceSquared = 0;
for (let i = 1; i < shakeSamples.length; i += 1) {
const p1 = shakeSamples[i - 1];
const p2 = shakeSamples[i];
totalDistanceSquared += (p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2;
}
// Count the number of times the mouse changes direction significantly, and the average position of the mouse
let directionChanges = 0;
const averagePoint = { x: 0, y: 0 };
let averagePointCount = 0;
for (let i = 0; i < shakeSamples.length - 2; i += 1) {
const p1 = shakeSamples[i];
const p2 = shakeSamples[i + 1];
const p3 = shakeSamples[i + 2];
const vector1 = { x: p2.x - p1.x, y: p2.y - p1.y };
const vector2 = { x: p3.x - p2.x, y: p3.y - p2.y };
// Check if the dot product is negative, which indicates the angle between vectors is > 90 degrees
if (vector1.x * vector2.x + vector1.y * vector2.y < 0) directionChanges += 1;
averagePoint.x += p2.x;
averagePoint.y += p2.y;
averagePointCount += 1;
}
if (averagePointCount > 0) {
averagePoint.x /= averagePointCount;
averagePoint.y /= averagePointCount;
}
// Calculate the displacement (the distance between the first and last mouse positions)
const lastPoint = shakeSamples[shakeSamples.length - 1];
const displacementSquared = (lastPoint.x - averagePoint.x) ** 2 + (lastPoint.y - averagePoint.y) ** 2;
// A shake is detected if the mouse has traveled a lot but not moved far, and has changed direction enough times
if (SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO * totalDistanceSquared >= displacementSquared && directionChanges >= SENSITIVITY_DIRECTION_CHANGES) {
lastShakeTime = now;
shakeSamples.length = 0;
return true;
}
return false;
}
// Frontend message subscriptions
editor.subscriptions.subscribeFrontendMessage("TriggerClipboardRead", async () => {
// In the try block, attempt to read from the Clipboard API, which may not have permission and may not be supported in all browsers // In the try block, attempt to read from the Clipboard API, which may not have permission and may not be supported in all browsers
// In the catch block, explain to the user why the paste failed and how to fix or work around the problem // In the catch block, explain to the user why the paste failed and how to fix or work around the problem
try { try {
@@ -486,20 +187,374 @@ export function createInputManager(editor: Editor, dialog: DialogStore, portfoli
editor.handle.errorDialog("Cannot access clipboard", message); editor.handle.errorDialog("Cannot access clipboard", message);
} }
}); }
// Pointer lock movement events on desktop // Event bindings
editor.subscriptions.subscribeFrontendMessage("WindowPointerLockMove", (data) => {
const event = new CustomEvent("pointerlockmove", { detail: { x: data.position[0], y: data.position[1] } });
window.dispatchEvent(event);
});
// Helper functions function bindListeners() {
// Add event bindings for the lifetime of the application
listeners.forEach(({ target, eventName, action, options }) => target.addEventListener(eventName, action, options));
}
function unbindListeners() {
// Remove event bindings after the lifetime of the application (or on hot-module replacement during development)
listeners.forEach(({ target, eventName, action, options }) => target.removeEventListener(eventName, action, options));
}
// Keyboard events
async function shouldRedirectKeyboardEventToBackend(e: KeyboardEvent): Promise<boolean> {
if (!dialogStore) return false;
// Don't redirect when a dialog is covering the workspace
if (get(dialogStore).visible) return false;
const key = await getLocalizedScanCode(e);
// TODO: Switch to a system where everything is sent to the backend, then the input preprocessor makes decisions and kicks some inputs back to the frontend
const accelKey = operatingSystem() === "Mac" ? e.metaKey : e.ctrlKey;
// Cut, copy, and paste is handled in the backend on desktop
if (isPlatformNative() && accelKey && ["KeyX", "KeyC", "KeyV"].includes(key)) return true;
// But on web, we want to not redirect paste
if (!isPlatformNative() && key === "KeyV" && accelKey) return false;
// Don't redirect user input from text entry into HTML elements
if (targetIsTextField(e.target || undefined) && key !== "Escape" && !(accelKey && ["Enter", "NumpadEnter"].includes(key))) return false;
// Don't redirect tab or enter if not in canvas (to allow navigating elements)
potentiallyRestoreCanvasFocus(e);
if (
!canvasFocused &&
!targetIsTextField(e.target || undefined) &&
["Tab", "Enter", "NumpadEnter", "Space", "ArrowDown", "ArrowLeft", "ArrowRight", "ArrowUp"].includes(key) &&
!(e.ctrlKey || e.metaKey || e.altKey)
)
return false;
// Don't redirect if a MenuList is open
if (window.document.querySelector("[data-floating-menu-content]")) return false;
// Web-only keyboard shortcuts
if (!isPlatformNative()) {
// Don't redirect a fullscreen request, but process it immediately instead
if (((operatingSystem() !== "Mac" && key === "F11") || (operatingSystem() === "Mac" && e.ctrlKey && e.metaKey && key === "KeyF")) && e.type === "keydown" && !e.repeat) {
e.preventDefault();
toggleFullscreen();
return false;
}
// Don't redirect a reload request
if (key === "F5") return false;
if (key === "KeyR" && accelKey) return false;
// Don't redirect debugging tools
if (["F12", "F8"].includes(key)) return false;
if (["KeyC", "KeyI", "KeyJ"].includes(key) && accelKey && e.shiftKey) return false;
}
// Redirect to the backend
return true;
}
async function onKeyDown(e: KeyboardEvent) {
const editor = editorRef;
if (!editor || !dialogStore) return;
const key = await getLocalizedScanCode(e);
const NO_KEY_REPEAT_MODIFIER_KEYS = ["ControlLeft", "ControlRight", "ShiftLeft", "ShiftRight", "MetaLeft", "MetaRight", "AltLeft", "AltRight", "AltGraph", "CapsLock", "Fn", "FnLock"];
if (e.repeat && NO_KEY_REPEAT_MODIFIER_KEYS.includes(key)) return;
if (await shouldRedirectKeyboardEventToBackend(e)) {
e.preventDefault();
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onKeyDown(key, modifiers, e.repeat);
return;
}
if (get(dialogStore).visible && key === "Escape") {
editor.handle.onDialogDismiss();
}
}
async function onKeyUp(e: KeyboardEvent) {
const editor = editorRef;
if (!editor) return;
const key = await getLocalizedScanCode(e);
if (await shouldRedirectKeyboardEventToBackend(e)) {
e.preventDefault();
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onKeyUp(key, modifiers, e.repeat);
}
}
// Pointer events
// While any pointer button is already down, additional button down events are not reported, but they are sent as `pointermove` events and these are handled in the backend
function onPointerMove(e: PointerEvent) {
const editor = editorRef;
if (!editor || !documentStore) return;
potentiallyRestoreCanvasFocus(e);
if (!e.buttons) viewportPointerInteractionOngoing = false;
// Don't redirect pointer movement to the backend if there's no ongoing interaction and it's over a floating menu, or the graph overlay, on top of the canvas
// TODO: A better approach is to pass along a boolean to the backend's input preprocessor so it can know if it's being occluded by the GUI.
// TODO: This would allow it to properly decide to act on removing hover focus from something that was hovered in the canvas before moving over the GUI.
// TODO: Further explanation: https://github.com/GraphiteEditor/Graphite/pull/623#discussion_r866436197
const inFloatingMenu = e.target instanceof Element && e.target.closest("[data-floating-menu-content]");
const inGraphOverlay = get(documentStore).graphViewOverlayOpen;
if (!viewportPointerInteractionOngoing && (inFloatingMenu || inGraphOverlay)) return;
const modifiers = makeKeyboardModifiersBitfield(e);
if (detectShake(e)) editor.handle.onMouseShake(e.clientX, e.clientY, e.buttons, modifiers);
editor.handle.onMouseMove(e.clientX, e.clientY, e.buttons, modifiers);
}
function onPointerDown(e: PointerEvent) {
const editor = editorRef;
if (!editor || !dialogStore) return;
potentiallyRestoreCanvasFocus(e);
const inFloatingMenu = e.target instanceof Element && e.target.closest("[data-floating-menu-content]");
const isTargetingCanvas = !inFloatingMenu && e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
const inDialog = e.target instanceof Element && e.target.closest("[data-dialog] [data-floating-menu-content]");
const inContextMenu = e.target instanceof Element && e.target.closest("[data-context-menu]");
const inTextInput = e.target === textToolInteractiveInputElement;
if (get(dialogStore).visible && !inDialog) {
editor.handle.onDialogDismiss();
e.preventDefault();
e.stopPropagation();
}
if (!inTextInput && !inContextMenu) {
if (textToolInteractiveInputElement) {
const isLeftOrRightClick = e.button === BUTTON_RIGHT || e.button === BUTTON_LEFT;
editor.handle.onChangeText(textInputCleanup(textToolInteractiveInputElement.innerText), isLeftOrRightClick);
} else {
viewportPointerInteractionOngoing = isTargetingCanvas instanceof Element;
}
}
if (viewportPointerInteractionOngoing && isTargetingCanvas instanceof Element) {
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onMouseDown(e.clientX, e.clientY, e.buttons, modifiers);
}
}
function onPointerUp(e: PointerEvent) {
const editor = editorRef;
if (!editor) return;
potentiallyRestoreCanvasFocus(e);
// Don't let the browser navigate back or forward when using the buttons on some mice
// TODO: This works in Chrome but not in Firefox
// TODO: Possible workaround: use the browser's history API to block navigation:
// TODO: <https://stackoverflow.com/questions/57102502/preventing-mouse-fourth-and-fifth-buttons-from-navigating-back-forward-in-browse>
if (e.button === BUTTON_BACK || e.button === BUTTON_FORWARD) e.preventDefault();
if (!e.buttons) viewportPointerInteractionOngoing = false;
if (textToolInteractiveInputElement) return;
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onMouseUp(e.clientX, e.clientY, e.buttons, modifiers);
}
// Mouse events
function onPotentialDoubleClick(e: MouseEvent) {
const editor = editorRef;
if (!editor) return;
if (textToolInteractiveInputElement || inPointerLock) return;
// Allow only events within the viewport or node graph boundaries
const isTargetingCanvas = e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
if (!(isTargetingCanvas instanceof Element)) return;
// Allow only repeated increments of double-clicks (not 1, 3, 5, etc.)
if (e.detail % 2 == 1) return;
// `e.buttons` is always 0 in the `mouseup` event, so we have to convert from `e.button` instead
let buttons = 1;
if (e.button === BUTTON_LEFT) buttons = 1; // Left
if (e.button === BUTTON_RIGHT) buttons = 2; // Right
if (e.button === BUTTON_MIDDLE) buttons = 4; // Middle
if (e.button === BUTTON_BACK) buttons = 8; // Back
if (e.button === BUTTON_FORWARD) buttons = 16; // Forward
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onDoubleClick(e.clientX, e.clientY, buttons, modifiers);
}
function onMouseDown(e: MouseEvent) {
// Block middle mouse button auto-scroll mode (the circular gizmo that appears and allows quick scrolling by moving the cursor above or below it)
if (e.button === BUTTON_MIDDLE) e.preventDefault();
}
function onContextMenu(e: MouseEvent) {
if (!targetIsTextField(e.target || undefined) && e.target !== textToolInteractiveInputElement) {
e.preventDefault();
}
}
function onPointerLockChange() {
inPointerLock = Boolean(window.document.pointerLockElement);
}
// Wheel events
function onWheelScroll(e: WheelEvent) {
const editor = editorRef;
if (!editor) return;
const isTargetingCanvas = e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-node-graph]");
// Prevent zooming the entire page when using Ctrl + scroll wheel outside of the viewport
if (e.ctrlKey && !isTargetingCanvas) {
e.preventDefault();
}
// Redirect vertical scroll wheel movement into a horizontal scroll on a horizontally scrollable element
// There seems to be no possible way to properly employ the browser's smooth scrolling interpolation
const horizontalScrollableElement = e.target instanceof Element && e.target.closest("[data-scrollable-x]");
if (horizontalScrollableElement && e.deltaY !== 0) {
horizontalScrollableElement.scrollTo(horizontalScrollableElement.scrollLeft + e.deltaY, 0);
return;
}
if (isTargetingCanvas) {
e.preventDefault();
const modifiers = makeKeyboardModifiersBitfield(e);
editor.handle.onWheelScroll(e.clientX, e.clientY, e.buttons, e.deltaX, e.deltaY, e.deltaZ, modifiers);
}
}
// Receives a custom event dispatched when the user begins interactively editing with the text tool.
// We keep a copy of the text input element to check against when it's active for text entry.
function onModifyInputField(e: CustomEvent) {
textToolInteractiveInputElement = e.detail;
}
// Window events
async function onBeforeUnload(e: BeforeUnloadEvent) {
const editor = editorRef;
if (!editor || !portfolioStore) return;
const activeDocument = get(portfolioStore).documents[get(portfolioStore).activeDocumentIndex];
if (activeDocument && !activeDocument.details.isAutoSaved) editor.handle.triggerAutoSave(activeDocument.id);
// Skip the message if the editor crashed, since work is already lost
if (await editor.handle.hasCrashed()) return;
// Skip the message during development, since it's annoying when testing
if (await editor.handle.inDevelopmentMode()) return;
const allDocumentsSaved = get(portfolioStore).documents.reduce((acc, doc) => acc && doc.details.isSaved, true);
if (!allDocumentsSaved) {
e.returnValue = "Unsaved work will be lost if the web browser tab is closed. Close anyway?";
e.preventDefault();
}
}
function onPaste(e: ClipboardEvent) {
const editor = editorRef;
if (!editor) return;
const dataTransfer = e.clipboardData;
if (!dataTransfer || targetIsTextField(e.target || undefined)) return;
e.preventDefault();
Array.from(dataTransfer.items).forEach(async (item) => {
if (item.type === "text/plain") item.getAsString((text) => editor.handle.pasteText(text));
await pasteFile(item, editor);
});
}
function detectShake(e: PointerEvent | MouseEvent): boolean {
const SENSITIVITY_DIRECTION_CHANGES = 3;
const SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO = 0.1;
const DETECTION_WINDOW_MS = 500;
const DEBOUNCE_MS = 1000;
// Add the current mouse position and time to our list of samples
const now = Date.now();
shakeSamples.push({ x: e.clientX, y: e.clientY, time: now });
// Remove samples that are older than our time window
while (shakeSamples.length > 0 && now - shakeSamples[0].time > DETECTION_WINDOW_MS) {
shakeSamples.shift();
}
// We can't be shaking if it's too early in terms of samples or debounce time
if (shakeSamples.length <= 3 || now - lastShakeTime <= DEBOUNCE_MS) return false;
// Calculate the total distance traveled
let totalDistanceSquared = 0;
for (let i = 1; i < shakeSamples.length; i += 1) {
const p1 = shakeSamples[i - 1];
const p2 = shakeSamples[i];
totalDistanceSquared += (p2.x - p1.x) ** 2 + (p2.y - p1.y) ** 2;
}
// Count the number of times the mouse changes direction significantly, and the average position of the mouse
let directionChanges = 0;
const averagePoint = { x: 0, y: 0 };
let averagePointCount = 0;
for (let i = 0; i < shakeSamples.length - 2; i += 1) {
const p1 = shakeSamples[i];
const p2 = shakeSamples[i + 1];
const p3 = shakeSamples[i + 2];
const vector1 = { x: p2.x - p1.x, y: p2.y - p1.y };
const vector2 = { x: p3.x - p2.x, y: p3.y - p2.y };
// Check if the dot product is negative, which indicates the angle between vectors is > 90 degrees
if (vector1.x * vector2.x + vector1.y * vector2.y < 0) directionChanges += 1;
averagePoint.x += p2.x;
averagePoint.y += p2.y;
averagePointCount += 1;
}
if (averagePointCount > 0) {
averagePoint.x /= averagePointCount;
averagePoint.y /= averagePointCount;
}
// Calculate the displacement (the distance between the first and last mouse positions)
const lastPoint = shakeSamples[shakeSamples.length - 1];
const displacementSquared = (lastPoint.x - averagePoint.x) ** 2 + (lastPoint.y - averagePoint.y) ** 2;
// A shake is detected if the mouse has traveled a lot but not moved far, and has changed direction enough times
if (SENSITIVITY_DISTANCE_TO_DISPLACEMENT_RATIO * totalDistanceSquared >= displacementSquared && directionChanges >= SENSITIVITY_DIRECTION_CHANGES) {
lastShakeTime = now;
shakeSamples.length = 0;
return true;
}
return false;
}
function targetIsTextField(target: EventTarget | HTMLElement | undefined): boolean {
return target instanceof HTMLElement && (target.nodeName === "INPUT" || target.nodeName === "TEXTAREA" || target.isContentEditable);
}
function potentiallyRestoreCanvasFocus(e: Event) { function potentiallyRestoreCanvasFocus(e: Event) {
const { target } = e; const appElement = window.document.querySelector("[data-app-container]");
const app = appElement instanceof HTMLElement ? appElement : null;
const newInCanvasArea = const newInCanvasArea =
(target instanceof Element && target.closest("[data-viewport], [data-viewport-container], [data-graph]")) instanceof Element && (e.target instanceof Element && e.target.closest("[data-viewport], [data-viewport-container], [data-graph]")) instanceof Element &&
!targetIsTextField(window.document.activeElement || undefined); !targetIsTextField(window.document.activeElement || undefined);
if (!canvasFocused && newInCanvasArea) { if (!canvasFocused && newInCanvasArea) {
canvasFocused = true; canvasFocused = true;
@@ -507,29 +562,8 @@ export function createInputManager(editor: Editor, dialog: DialogStore, portfoli
} }
} }
// Initialization
// Bind the event listeners
bindListeners();
// Return the destructor
function destroy() {
unbindListeners();
editor.subscriptions.unsubscribeFrontendMessage("TriggerClipboardRead");
editor.subscriptions.unsubscribeFrontendMessage("WindowPointerLockMove");
}
currentCleanup = destroy;
return { destroy };
}
export type InputManager = ReturnType<typeof createInputManager>;
function targetIsTextField(target: EventTarget | HTMLElement | undefined): boolean {
return target instanceof HTMLElement && (target.nodeName === "INPUT" || target.nodeName === "TEXTAREA" || target.isContentEditable);
}
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
currentCleanup?.(); destroyInputManager();
if (currentArgs) newModule?.createInputManager(...currentArgs); if (editorRef && dialogStore && portfolioStore && documentStore) newModule?.createInputManager(editorRef, dialogStore, portfolioStore, documentStore);
}); });
+9 -12
View File
@@ -1,26 +1,23 @@
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
let currentCleanup: (() => void) | undefined; let editorRef: Editor | undefined = undefined;
let currentArgs: [Editor] | undefined;
export function createLocalizationManager(editor: Editor) { export function createLocalizationManager(editor: Editor) {
currentArgs = [editor]; editorRef = editor;
// Subscribe to process backend event
editor.subscriptions.subscribeFrontendMessage("TriggerAboutGraphiteLocalizedCommitDate", (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerAboutGraphiteLocalizedCommitDate", (data) => {
const localized = localizeTimestamp(data.commitDate); const localized = localizeTimestamp(data.commitDate);
editor.handle.requestAboutGraphiteDialogWithLocalizedCommitDate(localized.timestamp, localized.year); editor.handle.requestAboutGraphiteDialogWithLocalizedCommitDate(localized.timestamp, localized.year);
}); });
}
export function destroyLocalizationManager() {
const editor = editorRef;
if (!editor) return;
function destroy() {
editor.subscriptions.unsubscribeFrontendMessage("TriggerAboutGraphiteLocalizedCommitDate"); editor.subscriptions.unsubscribeFrontendMessage("TriggerAboutGraphiteLocalizedCommitDate");
} }
currentCleanup = destroy;
return { destroy };
}
export type LocalizationManager = ReturnType<typeof createLocalizationManager>;
function localizeTimestamp(utc: string): { timestamp: string; year: string } { function localizeTimestamp(utc: string): { timestamp: string; year: string } {
// Timestamp // Timestamp
const date = new Date(utc); const date = new Date(utc);
@@ -38,6 +35,6 @@ function localizeTimestamp(utc: string): { timestamp: string; year: string } {
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
currentCleanup?.(); destroyLocalizationManager();
if (currentArgs) newModule?.createLocalizationManager(...currentArgs); if (editorRef) newModule?.createLocalizationManager(editorRef);
}); });
+11 -12
View File
@@ -1,18 +1,18 @@
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
import { createCrashDialog } from "@graphite/stores/dialog"; import { createCrashDialog } from "@graphite/stores/dialog";
let currentCleanup: (() => void) | undefined; let editorRef: Editor | undefined = undefined;
let currentArgs: [Editor] | undefined;
export function createPanicManager(editor: Editor) { export function createPanicManager(editor: Editor) {
currentArgs = [editor]; editorRef = editor;
// Code panic dialog and console error
editor.subscriptions.subscribeFrontendMessage("DisplayDialogPanic", (data) => { editor.subscriptions.subscribeFrontendMessage("DisplayDialogPanic", (data) => {
// `Error.stackTraceLimit` is only available in V8/Chromium // `Error.stackTraceLimit` is only available in V8/Chromium
const previousStackTraceLimit = Error.stackTraceLimit; const previousStackTraceLimit = Error.stackTraceLimit;
Error.stackTraceLimit = Infinity; Error.stackTraceLimit = Infinity;
const stackTrace = new Error().stack || ""; const stackTrace = new Error().stack || "";
Error.stackTraceLimit = previousStackTraceLimit; Error.stackTraceLimit = previousStackTraceLimit;
const panicDetails = `${data.panicInfo}${stackTrace ? `\n\n${stackTrace}` : ""}`; const panicDetails = `${data.panicInfo}${stackTrace ? `\n\n${stackTrace}` : ""}`;
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
@@ -20,18 +20,17 @@ export function createPanicManager(editor: Editor) {
createCrashDialog(panicDetails); createCrashDialog(panicDetails);
}); });
}
export function destroyPanicManager() {
const editor = editorRef;
if (!editor) return;
function destroy() {
editor.subscriptions.unsubscribeFrontendMessage("DisplayDialogPanic"); editor.subscriptions.unsubscribeFrontendMessage("DisplayDialogPanic");
} }
currentCleanup = destroy;
return { destroy };
}
export type PanicManager = ReturnType<typeof createPanicManager>;
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
currentCleanup?.(); destroyPanicManager();
if (currentArgs) newModule?.createPanicManager(...currentArgs); if (editorRef) newModule?.createPanicManager(editorRef);
}); });
+72 -58
View File
@@ -1,46 +1,51 @@
import { createStore, del, get, set, update } from "idb-keyval"; import * as idb from "idb-keyval";
import { get as getFromStore } from "svelte/store"; import { get } from "svelte/store";
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
import type { PortfolioStore } from "@graphite/stores/portfolio"; import type { PortfolioStore } from "@graphite/stores/portfolio";
import type { MessageBody } from "@graphite/subscription-router"; import type { MessageBody } from "@graphite/subscription-router";
const graphiteStore = createStore("graphite", "store"); let editorRef: Editor | undefined = undefined;
let portfolioStore: PortfolioStore | undefined = undefined;
let currentCleanup: (() => void) | undefined;
let currentArgs: [Editor, PortfolioStore] | undefined;
export function createPersistenceManager(editor: Editor, portfolio: PortfolioStore) { export function createPersistenceManager(editor: Editor, portfolio: PortfolioStore) {
currentArgs = [editor, portfolio]; editorRef = editor;
// DOCUMENTS portfolioStore = portfolio;
// FRONTEND MESSAGE SUBSCRIPTIONS
// Subscribe to process backend events
editor.subscriptions.subscribeFrontendMessage("TriggerSavePreferences", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerSavePreferences", async (data) => {
await saveEditorPreferences(data.preferences); await saveEditorPreferences(data.preferences);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerLoadPreferences", async () => { editor.subscriptions.subscribeFrontendMessage("TriggerLoadPreferences", async () => {
await loadEditorPreferences(editor); await loadEditorPreferences(editor);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerPersistenceWriteDocument", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerPersistenceWriteDocument", async (data) => {
await storeDocument(data, portfolio); await storeDocument(data, portfolio);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerPersistenceRemoveDocument", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerPersistenceRemoveDocument", async (data) => {
await removeDocument(String(data.documentId), portfolio); await removeDocument(String(data.documentId), portfolio);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerLoadFirstAutoSaveDocument", async () => { editor.subscriptions.subscribeFrontendMessage("TriggerLoadFirstAutoSaveDocument", async () => {
await loadFirstDocument(editor); await loadFirstDocument(editor);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerLoadRestAutoSaveDocuments", async () => { editor.subscriptions.subscribeFrontendMessage("TriggerLoadRestAutoSaveDocuments", async () => {
await loadRestDocuments(editor); await loadRestDocuments(editor);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerOpenLaunchDocuments", async () => { editor.subscriptions.subscribeFrontendMessage("TriggerOpenLaunchDocuments", async () => {
// TODO: Could be used to load documents from URL params or similar on launch // TODO: Could be used to load documents from URL params or similar on launch
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerSaveActiveDocument", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerSaveActiveDocument", async (data) => {
const indexedDbStorage = idb.createStore("graphite", "store");
const previouslySavedDocuments = await idb.get<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>("documents", indexedDbStorage);
const documentId = String(data.documentId); const documentId = String(data.documentId);
const previouslySavedDocuments = await get<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>("documents", graphiteStore);
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// Migrate TriggerPersistenceWriteDocument.documentId from string to bigint if needed // Migrate TriggerPersistenceWriteDocument.documentId from string to bigint if needed
@@ -55,8 +60,12 @@ export function createPersistenceManager(editor: Editor, portfolio: PortfolioSto
await storeCurrentDocumentId(documentId); await storeCurrentDocumentId(documentId);
} }
}); });
}
export function destroyPersistenceManager() {
const editor = editorRef;
if (!editor) return;
function destroy() {
editor.subscriptions.unsubscribeFrontendMessage("TriggerSavePreferences"); editor.subscriptions.unsubscribeFrontendMessage("TriggerSavePreferences");
editor.subscriptions.unsubscribeFrontendMessage("TriggerLoadPreferences"); editor.subscriptions.unsubscribeFrontendMessage("TriggerLoadPreferences");
editor.subscriptions.unsubscribeFrontendMessage("TriggerPersistenceWriteDocument"); editor.subscriptions.unsubscribeFrontendMessage("TriggerPersistenceWriteDocument");
@@ -67,77 +76,70 @@ export function createPersistenceManager(editor: Editor, portfolio: PortfolioSto
editor.subscriptions.unsubscribeFrontendMessage("TriggerSaveActiveDocument"); editor.subscriptions.unsubscribeFrontendMessage("TriggerSaveActiveDocument");
} }
currentCleanup = destroy; export async function storeCurrentDocumentId(documentId: string) {
return { destroy }; const indexedDbStorage = idb.createStore("graphite", "store");
}
export type PersistenceManager = ReturnType<typeof createPersistenceManager>;
export async function wipeDocuments() { await idb.set("current_document_id", String(documentId), indexedDbStorage);
await del("documents_tab_order", graphiteStore);
await del("current_document_id", graphiteStore);
await del("documents", graphiteStore);
} }
async function storeDocumentOrder(portfolio: PortfolioStore) { export async function storeDocument(autoSaveDocument: MessageBody<"TriggerPersistenceWriteDocument">, portfolio: PortfolioStore) {
const documentOrder = getFromStore(portfolio).documents.map((doc) => String(doc.id)); const indexedDbStorage = idb.createStore("graphite", "store");
await set("documents_tab_order", documentOrder, graphiteStore);
}
async function storeCurrentDocumentId(documentId: string) { await idb.update<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>(
await set("current_document_id", String(documentId), graphiteStore);
}
async function storeDocument(autoSaveDocument: MessageBody<"TriggerPersistenceWriteDocument">, portfolio: PortfolioStore) {
await update<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>(
"documents", "documents",
(old) => { (old) => {
const documents = old || {}; const documents = old || {};
documents[String(autoSaveDocument.documentId)] = autoSaveDocument; documents[String(autoSaveDocument.documentId)] = autoSaveDocument;
return documents; return documents;
}, },
graphiteStore, indexedDbStorage,
); );
await storeDocumentOrder(portfolio); const documentOrder = get(portfolio).documents.map((doc) => String(doc.id));
await idb.set("documents_tab_order", documentOrder, indexedDbStorage);
await storeCurrentDocumentId(String(autoSaveDocument.documentId)); await storeCurrentDocumentId(String(autoSaveDocument.documentId));
} }
async function removeDocument(id: string, portfolio: PortfolioStore) { export async function removeDocument(id: string, portfolio: PortfolioStore) {
await update<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>( const indexedDbStorage = idb.createStore("graphite", "store");
await idb.update<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>(
"documents", "documents",
(old) => { (old) => {
const documents = old || {}; const documents = old || {};
delete documents[id]; delete documents[id];
return documents; return documents;
}, },
graphiteStore, indexedDbStorage,
); );
await update<string[]>( await idb.update<string[]>(
"documents_tab_order", "documents_tab_order",
(old) => { (old) => {
const order = old || []; const order = old || [];
return order.filter((docId) => docId !== id); return order.filter((docId) => docId !== id);
}, },
graphiteStore, indexedDbStorage,
); );
const documentCount = getFromStore(portfolio).documents.length; const documentCount = get(portfolio).documents.length;
if (documentCount > 0) { if (documentCount > 0) {
const documentIndex = getFromStore(portfolio).activeDocumentIndex; const documentIndex = get(portfolio).activeDocumentIndex;
const documentId = String(getFromStore(portfolio).documents[documentIndex].id); const documentId = String(get(portfolio).documents[documentIndex].id);
const tabOrder = (await get<string[]>("documents_tab_order", graphiteStore)) || []; const tabOrder = (await idb.get<string[]>("documents_tab_order", indexedDbStorage)) || [];
if (tabOrder.includes(documentId)) { if (tabOrder.includes(documentId)) {
await storeCurrentDocumentId(documentId); await storeCurrentDocumentId(documentId);
} }
} else { } else {
await del("current_document_id", graphiteStore); await idb.del("current_document_id", indexedDbStorage);
} }
} }
async function loadFirstDocument(editor: Editor) { export async function loadFirstDocument(editor: Editor) {
const previouslySavedDocuments = await get<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>("documents", graphiteStore); const indexedDbStorage = idb.createStore("graphite", "store");
const previouslySavedDocuments = await idb.get<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>("documents", indexedDbStorage);
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// Migrate TriggerPersistenceWriteDocument.documentId from string to bigint if the browser is storing the old format as strings // Migrate TriggerPersistenceWriteDocument.documentId from string to bigint if the browser is storing the old format as strings
@@ -147,8 +149,8 @@ async function loadFirstDocument(editor: Editor) {
}); });
} }
const documentOrder = await get<string[]>("documents_tab_order", graphiteStore); const documentOrder = await idb.get<string[]>("documents_tab_order", indexedDbStorage);
const currentDocumentIdString = await get<string>("current_document_id", graphiteStore); const currentDocumentIdString = await idb.get<string>("current_document_id", indexedDbStorage);
const currentDocumentId = currentDocumentIdString ? BigInt(currentDocumentIdString) : undefined; const currentDocumentId = currentDocumentIdString ? BigInt(currentDocumentIdString) : undefined;
if (!previouslySavedDocuments || !documentOrder) return; if (!previouslySavedDocuments || !documentOrder) return;
@@ -168,8 +170,10 @@ async function loadFirstDocument(editor: Editor) {
} }
} }
async function loadRestDocuments(editor: Editor) { export async function loadRestDocuments(editor: Editor) {
const previouslySavedDocuments = await get<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>("documents", graphiteStore); const indexedDbStorage = idb.createStore("graphite", "store");
const previouslySavedDocuments = await idb.get<Record<string, MessageBody<"TriggerPersistenceWriteDocument">>>("documents", indexedDbStorage);
// TODO: Eventually remove this document upgrade code // TODO: Eventually remove this document upgrade code
// Migrate TriggerPersistenceWriteDocument.documentId from string to bigint if needed // Migrate TriggerPersistenceWriteDocument.documentId from string to bigint if needed
@@ -179,8 +183,8 @@ async function loadRestDocuments(editor: Editor) {
}); });
} }
const documentOrder = await get<string[]>("documents_tab_order", graphiteStore); const documentOrder = await idb.get<string[]>("documents_tab_order", indexedDbStorage);
const currentDocumentIdString = await get<string>("current_document_id", graphiteStore); const currentDocumentIdString = await idb.get<string>("current_document_id", indexedDbStorage);
const currentDocumentId = currentDocumentIdString ? BigInt(currentDocumentIdString) : undefined; const currentDocumentId = currentDocumentIdString ? BigInt(currentDocumentIdString) : undefined;
if (!previouslySavedDocuments || !documentOrder) return; if (!previouslySavedDocuments || !documentOrder) return;
@@ -217,19 +221,29 @@ async function loadRestDocuments(editor: Editor) {
} }
} }
// PREFERENCES export async function saveEditorPreferences(preferences: unknown) {
const indexedDbStorage = idb.createStore("graphite", "store");
async function saveEditorPreferences(preferences: unknown) { await idb.set("preferences", preferences, indexedDbStorage);
await set("preferences", preferences, graphiteStore);
} }
async function loadEditorPreferences(editor: Editor) { export async function loadEditorPreferences(editor: Editor) {
const preferences = await get<Record<string, unknown>>("preferences", graphiteStore); const indexedDbStorage = idb.createStore("graphite", "store");
const preferences = await idb.get<Record<string, unknown>>("preferences", indexedDbStorage);
editor.handle.loadPreferences(preferences ? JSON.stringify(preferences) : undefined); editor.handle.loadPreferences(preferences ? JSON.stringify(preferences) : undefined);
} }
export async function wipeDocuments() {
const indexedDbStorage = idb.createStore("graphite", "store");
await idb.del("documents_tab_order", indexedDbStorage);
await idb.del("current_document_id", indexedDbStorage);
await idb.del("documents", indexedDbStorage);
}
// Self-accepting HMR: tear down the old instance and re-create with the new module's code // Self-accepting HMR: tear down the old instance and re-create with the new module's code
import.meta.hot?.accept((newModule) => { import.meta.hot?.accept((newModule) => {
currentCleanup?.(); destroyPersistenceManager();
if (currentArgs) newModule?.createPersistenceManager(...currentArgs); if (editorRef && portfolioStore) newModule?.createPersistenceManager(editorRef, portfolioStore);
}); });
+17 -19
View File
@@ -4,6 +4,8 @@ import type { Writable } from "svelte/store";
import type { AppWindowPlatform } from "@graphite/../wasm/pkg/graphite_wasm"; import type { AppWindowPlatform } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
export type AppWindowStore = ReturnType<typeof createAppWindowStore>;
type AppWindowStoreState = { type AppWindowStoreState = {
platform: AppWindowPlatform; platform: AppWindowPlatform;
maximized: boolean; maximized: boolean;
@@ -19,37 +21,44 @@ const initialState: AppWindowStoreState = {
uiScale: 1, uiScale: 1,
}; };
let editorRef: Editor | undefined = undefined;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree // Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<AppWindowStoreState> = import.meta.hot?.data?.store || writable<AppWindowStoreState>(initialState); const store: Writable<AppWindowStoreState> = import.meta.hot?.data?.store || writable<AppWindowStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store; if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store; const { subscribe, update } = store;
export function createAppWindowStore(editor: Editor) { export function createAppWindowStore(editor: Editor) {
// Set up message subscriptions on creation editorRef = editor;
editor.subscriptions.subscribeFrontendMessage("UpdatePlatform", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdatePlatform", (data) => {
update((state) => { update((state) => {
state.platform = data.platform; state.platform = data.platform;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateMaximized", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateMaximized", (data) => {
update((state) => { update((state) => {
state.maximized = data.maximized; state.maximized = data.maximized;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateFullscreen", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateFullscreen", (data) => {
update((state) => { update((state) => {
state.fullscreen = data.fullscreen; state.fullscreen = data.fullscreen;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateViewportHolePunch", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateViewportHolePunch", (data) => {
update((state) => { update((state) => {
state.viewportHolePunch = data.active; state.viewportHolePunch = data.active;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateUIScale", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateUIScale", (data) => {
update((state) => { update((state) => {
state.uiScale = data.scale; state.uiScale = data.scale;
@@ -57,27 +66,16 @@ export function createAppWindowStore(editor: Editor) {
}); });
}); });
function destroy() { return { subscribe };
}
export function destroyAppWindowStore() {
const editor = editorRef;
if (!editor) return;
editor.subscriptions.unsubscribeFrontendMessage("UpdatePlatform"); editor.subscriptions.unsubscribeFrontendMessage("UpdatePlatform");
editor.subscriptions.unsubscribeFrontendMessage("UpdateMaximized"); editor.subscriptions.unsubscribeFrontendMessage("UpdateMaximized");
editor.subscriptions.unsubscribeFrontendMessage("UpdateFullscreen"); editor.subscriptions.unsubscribeFrontendMessage("UpdateFullscreen");
editor.subscriptions.unsubscribeFrontendMessage("UpdateViewportHolePunch"); editor.subscriptions.unsubscribeFrontendMessage("UpdateViewportHolePunch");
editor.subscriptions.unsubscribeFrontendMessage("UpdateUIScale"); editor.subscriptions.unsubscribeFrontendMessage("UpdateUIScale");
} }
currentCleanup = destroy;
currentArgs = [editor];
return {
subscribe,
destroy,
};
}
export type AppWindowStore = ReturnType<typeof createAppWindowStore>;
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
let currentCleanup: (() => void) | undefined;
let currentArgs: [Editor] | undefined;
import.meta.hot?.accept((newModule) => {
currentCleanup?.();
if (currentArgs) newModule?.createAppWindowStore(...currentArgs);
});
+14 -19
View File
@@ -7,6 +7,8 @@ import type { Editor } from "@graphite/editor";
import type { IconName } from "@graphite/icons"; import type { IconName } from "@graphite/icons";
import { patchLayout } from "@graphite/utility-functions/widgets"; import { patchLayout } from "@graphite/utility-functions/widgets";
export type DialogStore = ReturnType<typeof createDialogStore>;
type DialogStoreState = { type DialogStoreState = {
visible: boolean; visible: boolean;
title: string; title: string;
@@ -27,13 +29,16 @@ const initialState: DialogStoreState = {
panicDetails: "", panicDetails: "",
}; };
let editorRef: Editor | undefined = undefined;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree // Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<DialogStoreState> = import.meta.hot?.data?.store || writable<DialogStoreState>(initialState); const store: Writable<DialogStoreState> = import.meta.hot?.data?.store || writable<DialogStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store; if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store; const { subscribe, update } = store;
export function createDialogStore(editor: Editor) { export function createDialogStore(editor: Editor) {
// Subscribe to process backend events editorRef = editor;
editor.subscriptions.subscribeFrontendMessage("DisplayDialog", (data) => { editor.subscriptions.subscribeFrontendMessage("DisplayDialog", (data) => {
update((state) => { update((state) => {
state.visible = true; state.visible = true;
@@ -71,6 +76,7 @@ export function createDialogStore(editor: Editor) {
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("DialogClose", () => { editor.subscriptions.subscribeFrontendMessage("DialogClose", () => {
update((state) => { update((state) => {
// Disallow dismissing the crash dialog since it should remain as the final notification // Disallow dismissing the crash dialog since it should remain as the final notification
@@ -94,7 +100,13 @@ export function createDialogStore(editor: Editor) {
editor.handle.requestLicensesThirdPartyDialogWithLicenseText(licenseText); editor.handle.requestLicensesThirdPartyDialogWithLicenseText(licenseText);
}); });
function destroy() { return { subscribe };
}
export function destroyDialogStore() {
const editor = editorRef;
if (!editor) return;
editor.subscriptions.unsubscribeFrontendMessage("DisplayDialog"); editor.subscriptions.unsubscribeFrontendMessage("DisplayDialog");
editor.subscriptions.unsubscribeFrontendMessage("DialogClose"); editor.subscriptions.unsubscribeFrontendMessage("DialogClose");
editor.subscriptions.unsubscribeFrontendMessage("TriggerDisplayThirdPartyLicensesDialog"); editor.subscriptions.unsubscribeFrontendMessage("TriggerDisplayThirdPartyLicensesDialog");
@@ -103,15 +115,6 @@ export function createDialogStore(editor: Editor) {
editor.subscriptions.unsubscribeLayoutUpdate("DialogColumn2"); editor.subscriptions.unsubscribeLayoutUpdate("DialogColumn2");
} }
currentCleanup = destroy;
currentArgs = [editor];
return {
subscribe,
destroy,
};
}
export type DialogStore = ReturnType<typeof createDialogStore>;
// Creates a crash dialog from JS once the editor has panicked. // Creates a crash dialog from JS once the editor has panicked.
// Normal dialogs are created in the Rust backend, but for the crash dialog, the editor has panicked so it cannot respond to widget callbacks. // Normal dialogs are created in the Rust backend, but for the crash dialog, the editor has panicked so it cannot respond to widget callbacks.
export function createCrashDialog(panicDetails: string) { export function createCrashDialog(panicDetails: string) {
@@ -129,11 +132,3 @@ export function createCrashDialog(panicDetails: string) {
return state; return state;
}); });
} }
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
let currentCleanup: (() => void) | undefined;
let currentArgs: [Editor] | undefined;
import.meta.hot?.accept((newModule) => {
currentCleanup?.();
if (currentArgs) newModule?.createDialogStore(...currentArgs);
});
+13 -18
View File
@@ -6,6 +6,8 @@ import type { Layout } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
import { patchLayout } from "@graphite/utility-functions/widgets"; import { patchLayout } from "@graphite/utility-functions/widgets";
export type DocumentStore = ReturnType<typeof createDocumentStore>;
type DocumentStoreState = { type DocumentStoreState = {
toolOptionsLayout: Layout; toolOptionsLayout: Layout;
documentBarLayout: Layout; documentBarLayout: Layout;
@@ -25,12 +27,16 @@ const initialState: DocumentStoreState = {
fadeArtwork: 100, fadeArtwork: 100,
}; };
let editorRef: Editor | undefined = undefined;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree // Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<DocumentStoreState> = import.meta.hot?.data?.store || writable<DocumentStoreState>(initialState); const store: Writable<DocumentStoreState> = import.meta.hot?.data?.store || writable<DocumentStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store; if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store; const { subscribe, update } = store;
export function createDocumentStore(editor: Editor) { export function createDocumentStore(editor: Editor) {
editorRef = editor;
// Update layouts // Update layouts
editor.subscriptions.subscribeFrontendMessage("UpdateGraphFadeArtwork", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateGraphFadeArtwork", (data) => {
update((state) => { update((state) => {
@@ -87,7 +93,13 @@ export function createDocumentStore(editor: Editor) {
}); });
}); });
function destroy() { return { subscribe };
}
export function destroyDocumentStore() {
const editor = editorRef;
if (!editor) return;
editor.subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork"); editor.subscriptions.unsubscribeFrontendMessage("UpdateGraphFadeArtwork");
editor.subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay"); editor.subscriptions.unsubscribeFrontendMessage("UpdateGraphViewOverlay");
editor.subscriptions.unsubscribeLayoutUpdate("ToolOptions"); editor.subscriptions.unsubscribeLayoutUpdate("ToolOptions");
@@ -96,20 +108,3 @@ export function createDocumentStore(editor: Editor) {
editor.subscriptions.unsubscribeLayoutUpdate("WorkingColors"); editor.subscriptions.unsubscribeLayoutUpdate("WorkingColors");
editor.subscriptions.unsubscribeLayoutUpdate("NodeGraphControlBar"); editor.subscriptions.unsubscribeLayoutUpdate("NodeGraphControlBar");
} }
currentCleanup = destroy;
currentArgs = [editor];
return {
subscribe,
destroy,
};
}
export type DocumentStore = ReturnType<typeof createDocumentStore>;
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
let currentCleanup: (() => void) | undefined;
let currentArgs: [Editor] | undefined;
import.meta.hot?.accept((newModule) => {
currentCleanup?.();
if (currentArgs) newModule?.createDocumentStore(...currentArgs);
});
+12 -17
View File
@@ -3,6 +3,8 @@ import type { Writable } from "svelte/store";
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
export type FullscreenStore = ReturnType<typeof createFullscreenStore>;
type FullscreenStoreState = { type FullscreenStoreState = {
windowFullscreen: boolean; windowFullscreen: boolean;
keyboardLocked: boolean; keyboardLocked: boolean;
@@ -12,28 +14,29 @@ const initialState: FullscreenStoreState = {
keyboardLocked: false, keyboardLocked: false,
}; };
let editorRef: Editor | undefined = undefined;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree // Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<FullscreenStoreState> = import.meta.hot?.data?.store || writable<FullscreenStoreState>(initialState); const store: Writable<FullscreenStoreState> = import.meta.hot?.data?.store || writable<FullscreenStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store; if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store; const { subscribe, update } = store;
export function createFullscreenStore(editor: Editor) { export function createFullscreenStore(editor: Editor) {
editorRef = editor;
editor.subscriptions.subscribeFrontendMessage("WindowFullscreen", () => { editor.subscriptions.subscribeFrontendMessage("WindowFullscreen", () => {
toggleFullscreen(); toggleFullscreen();
}); });
function destroy() { return { subscribe };
editor.subscriptions.unsubscribeFrontendMessage("WindowFullscreen");
} }
currentCleanup = destroy; export function destroyFullscreenStore() {
currentArgs = [editor]; const editor = editorRef;
return { if (!editor) return;
subscribe,
destroy, editor.subscriptions.unsubscribeFrontendMessage("WindowFullscreen");
};
} }
export type FullscreenStore = ReturnType<typeof createFullscreenStore>;
export function fullscreenModeChanged() { export function fullscreenModeChanged() {
update((state) => { update((state) => {
@@ -67,11 +70,3 @@ export async function toggleFullscreen() {
if (state.windowFullscreen) await exitFullscreen(); if (state.windowFullscreen) await exitFullscreen();
else await enterFullscreen(); else await enterFullscreen();
} }
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
let currentCleanup: (() => void) | undefined;
let currentArgs: [Editor] | undefined;
import.meta.hot?.accept((newModule) => {
currentCleanup?.();
if (currentArgs) newModule?.createFullscreenStore(...currentArgs);
});
+30 -18
View File
@@ -5,6 +5,8 @@ import type { NodeGraphErrorDiagnostic, BoxSelection, FrontendClickTargets, Cont
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
import type { MessageBody } from "@graphite/subscription-router"; import type { MessageBody } from "@graphite/subscription-router";
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
type NodeGraphStoreState = { type NodeGraphStoreState = {
box: BoxSelection | undefined; box: BoxSelection | undefined;
clickTargets: FrontendClickTargets | undefined; clickTargets: FrontendClickTargets | undefined;
@@ -51,12 +53,16 @@ const initialState: NodeGraphStoreState = {
reorderExportIndex: undefined, reorderExportIndex: undefined,
}; };
let editorRef: Editor | undefined = undefined;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree // Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<NodeGraphStoreState> = import.meta.hot?.data?.store || writable<NodeGraphStoreState>(initialState); const store: Writable<NodeGraphStoreState> = import.meta.hot?.data?.store || writable<NodeGraphStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store; if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store; const { subscribe, update } = store;
export function createNodeGraphStore(editor: Editor) { export function createNodeGraphStore(editor: Editor) {
editorRef = editor;
// Set up message subscriptions on creation // Set up message subscriptions on creation
editor.subscriptions.subscribeFrontendMessage("SendUIMetadata", (data) => { editor.subscriptions.subscribeFrontendMessage("SendUIMetadata", (data) => {
update((state) => { update((state) => {
@@ -65,48 +71,56 @@ export function createNodeGraphStore(editor: Editor) {
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateBox", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateBox", (data) => {
update((state) => { update((state) => {
state.box = data.box; state.box = data.box;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateClickTargets", (data) => {
update((state) => { update((state) => {
state.clickTargets = data.clickTargets; state.clickTargets = data.clickTargets;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateContextMenuInformation", (data) => {
update((state) => { update((state) => {
state.contextMenuInformation = data.contextMenuInformation; state.contextMenuInformation = data.contextMenuInformation;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateImportReorderIndex", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateImportReorderIndex", (data) => {
update((state) => { update((state) => {
state.reorderImportIndex = data.importIndex; state.reorderImportIndex = data.importIndex;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateExportReorderIndex", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateExportReorderIndex", (data) => {
update((state) => { update((state) => {
state.reorderExportIndex = data.exportIndex; state.reorderExportIndex = data.exportIndex;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateImportsExports", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateImportsExports", (data) => {
update((state) => { update((state) => {
state.updateImportsExports = data; state.updateImportsExports = data;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateInSelectedNetwork", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateInSelectedNetwork", (data) => {
update((state) => { update((state) => {
state.inSelectedNetwork = data.inSelectedNetwork; state.inSelectedNetwork = data.inSelectedNetwork;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateLayerWidths", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateLayerWidths", (data) => {
update((state) => { update((state) => {
state.layerWidths = data.layerWidths; state.layerWidths = data.layerWidths;
@@ -115,6 +129,7 @@ export function createNodeGraphStore(editor: Editor) {
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphNodes", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphNodes", (data) => {
update((state) => { update((state) => {
state.nodes.clear(); state.nodes.clear();
@@ -124,18 +139,21 @@ export function createNodeGraphStore(editor: Editor) {
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphErrorDiagnostic", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphErrorDiagnostic", (data) => {
update((state) => { update((state) => {
state.error = data.error; state.error = data.error;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateVisibleNodes", (data) => {
update((state) => { update((state) => {
state.visibleNodes = new Set<bigint>(data.nodes); state.visibleNodes = new Set<bigint>(data.nodes);
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphWires", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphWires", (data) => {
update((state) => { update((state) => {
data.wires.forEach((wireUpdate) => { data.wires.forEach((wireUpdate) => {
@@ -154,30 +172,35 @@ export function createNodeGraphStore(editor: Editor) {
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("ClearAllNodeGraphWires", () => { editor.subscriptions.subscribeFrontendMessage("ClearAllNodeGraphWires", () => {
update((state) => { update((state) => {
state.wires.clear(); state.wires.clear();
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphSelection", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphSelection", (data) => {
update((state) => { update((state) => {
state.selected = data.selected; state.selected = data.selected;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphTransform", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateNodeGraphTransform", (data) => {
update((state) => { update((state) => {
state.transform = { scale: data.scale, x: data.translation[0], y: data.translation[1] }; state.transform = { scale: data.scale, x: data.translation[0], y: data.translation[1] };
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateNodeThumbnail", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateNodeThumbnail", (data) => {
update((state) => { update((state) => {
state.thumbnails.set(data.id, data.value); state.thumbnails.set(data.id, data.value);
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateWirePathInProgress", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateWirePathInProgress", (data) => {
update((state) => { update((state) => {
state.wirePathInProgress = data.wirePath; state.wirePathInProgress = data.wirePath;
@@ -185,7 +208,13 @@ export function createNodeGraphStore(editor: Editor) {
}); });
}); });
function destroy() { return { subscribe };
}
export function destroyNodeGraphStore() {
const editor = editorRef;
if (!editor) return;
editor.subscriptions.unsubscribeFrontendMessage("SendUIMetadata"); editor.subscriptions.unsubscribeFrontendMessage("SendUIMetadata");
editor.subscriptions.unsubscribeFrontendMessage("UpdateBox"); editor.subscriptions.unsubscribeFrontendMessage("UpdateBox");
editor.subscriptions.unsubscribeFrontendMessage("UpdateClickTargets"); editor.subscriptions.unsubscribeFrontendMessage("UpdateClickTargets");
@@ -206,26 +235,9 @@ export function createNodeGraphStore(editor: Editor) {
editor.subscriptions.unsubscribeFrontendMessage("UpdateWirePathInProgress"); editor.subscriptions.unsubscribeFrontendMessage("UpdateWirePathInProgress");
} }
currentCleanup = destroy;
currentArgs = [editor];
return {
subscribe,
destroy,
};
}
export type NodeGraphStore = ReturnType<typeof createNodeGraphStore>;
export function closeContextMenu() { export function closeContextMenu() {
update((state) => { update((state) => {
state.contextMenuInformation = undefined; state.contextMenuInformation = undefined;
return state; return state;
}); });
} }
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
let currentCleanup: (() => void) | undefined;
let currentArgs: [Editor] | undefined;
import.meta.hot?.accept((newModule) => {
currentCleanup?.();
if (currentArgs) newModule?.createNodeGraphStore(...currentArgs);
});
+23 -19
View File
@@ -6,6 +6,8 @@ import type { Editor } from "@graphite/editor";
import { downloadFile, downloadFileBlob, upload } from "@graphite/utility-functions/files"; import { downloadFile, downloadFileBlob, upload } from "@graphite/utility-functions/files";
import { rasterizeSVG } from "@graphite/utility-functions/rasterization"; import { rasterizeSVG } from "@graphite/utility-functions/rasterization";
export type PortfolioStore = ReturnType<typeof createPortfolioStore>;
type PortfolioStoreState = { type PortfolioStoreState = {
unsaved: boolean; unsaved: boolean;
documents: OpenDocument[]; documents: OpenDocument[];
@@ -23,19 +25,23 @@ const initialState: PortfolioStoreState = {
layersPanelOpen: true, layersPanelOpen: true,
}; };
let editorRef: Editor | undefined = undefined;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree // Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<PortfolioStoreState> = import.meta.hot?.data?.store || writable<PortfolioStoreState>(initialState); const store: Writable<PortfolioStoreState> = import.meta.hot?.data?.store || writable<PortfolioStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store; if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store; const { subscribe, update } = store;
export function createPortfolioStore(editor: Editor) { export function createPortfolioStore(editor: Editor) {
// Set up message subscriptions on creation editorRef = editor;
editor.subscriptions.subscribeFrontendMessage("UpdateOpenDocumentsList", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateOpenDocumentsList", (data) => {
update((state) => { update((state) => {
state.documents = data.openDocuments; state.documents = data.openDocuments;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateActiveDocument", (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateActiveDocument", (data) => {
update((state) => { update((state) => {
// Assume we receive a correct document id // Assume we receive a correct document id
@@ -44,6 +50,7 @@ export function createPortfolioStore(editor: Editor) {
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerFetchAndOpenDocument", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerFetchAndOpenDocument", async (data) => {
try { try {
const url = new URL(`demo-artwork/${data.filename}`, document.location.href); const url = new URL(`demo-artwork/${data.filename}`, document.location.href);
@@ -56,21 +63,26 @@ export function createPortfolioStore(editor: Editor) {
}, 0); }, 0);
} }
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerOpen", async () => { editor.subscriptions.subscribeFrontendMessage("TriggerOpen", async () => {
const data = await upload(`image/*,.${editor.handle.fileExtension()}`, "data"); const data = await upload(`image/*,.${editor.handle.fileExtension()}`, "data");
editor.handle.openFile(data.filename, data.content); editor.handle.openFile(data.filename, data.content);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerImport", async () => { editor.subscriptions.subscribeFrontendMessage("TriggerImport", async () => {
// TODO: Use the same `accept` string as in the `TriggerOpen` handler once importing Graphite documents as nodes is supported // TODO: Use the same `accept` string as in the `TriggerOpen` handler once importing Graphite documents as nodes is supported
const data = await upload("image/*", "data"); const data = await upload("image/*", "data");
editor.handle.importFile(data.filename, data.content); editor.handle.importFile(data.filename, data.content);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerSaveDocument", (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerSaveDocument", (data) => {
downloadFile(data.name, data.content); downloadFile(data.name, data.content);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerSaveFile", (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerSaveFile", (data) => {
downloadFile(data.name, data.content); downloadFile(data.name, data.content);
}); });
editor.subscriptions.subscribeFrontendMessage("TriggerExportImage", async (data) => { editor.subscriptions.subscribeFrontendMessage("TriggerExportImage", async (data) => {
const { svg, name, mime, size } = data; const { svg, name, mime, size } = data;
@@ -87,18 +99,21 @@ export function createPortfolioStore(editor: Editor) {
// Fail silently if there's an error rasterizing the SVG, such as a zero-sized image // Fail silently if there's an error rasterizing the SVG, such as a zero-sized image
} }
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateDataPanelState", async (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateDataPanelState", async (data) => {
update((state) => { update((state) => {
state.dataPanelOpen = data.open; state.dataPanelOpen = data.open;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdatePropertiesPanelState", async (data) => { editor.subscriptions.subscribeFrontendMessage("UpdatePropertiesPanelState", async (data) => {
update((state) => { update((state) => {
state.propertiesPanelOpen = data.open; state.propertiesPanelOpen = data.open;
return state; return state;
}); });
}); });
editor.subscriptions.subscribeFrontendMessage("UpdateLayersPanelState", async (data) => { editor.subscriptions.subscribeFrontendMessage("UpdateLayersPanelState", async (data) => {
update((state) => { update((state) => {
state.layersPanelOpen = data.open; state.layersPanelOpen = data.open;
@@ -106,7 +121,13 @@ export function createPortfolioStore(editor: Editor) {
}); });
}); });
function destroy() { return { subscribe };
}
export function destroyPortfolioStore() {
const editor = editorRef;
if (!editor) return;
editor.subscriptions.unsubscribeFrontendMessage("UpdateOpenDocumentsList"); editor.subscriptions.unsubscribeFrontendMessage("UpdateOpenDocumentsList");
editor.subscriptions.unsubscribeFrontendMessage("UpdateActiveDocument"); editor.subscriptions.unsubscribeFrontendMessage("UpdateActiveDocument");
editor.subscriptions.unsubscribeFrontendMessage("TriggerFetchAndOpenDocument"); editor.subscriptions.unsubscribeFrontendMessage("TriggerFetchAndOpenDocument");
@@ -119,20 +140,3 @@ export function createPortfolioStore(editor: Editor) {
editor.subscriptions.unsubscribeFrontendMessage("UpdatePropertiesPanelState"); editor.subscriptions.unsubscribeFrontendMessage("UpdatePropertiesPanelState");
editor.subscriptions.unsubscribeFrontendMessage("UpdateLayersPanelState"); editor.subscriptions.unsubscribeFrontendMessage("UpdateLayersPanelState");
} }
currentCleanup = destroy;
currentArgs = [editor];
return {
subscribe,
destroy,
};
}
export type PortfolioStore = ReturnType<typeof createPortfolioStore>;
// Self-accepting HMR: tear down the old instance and re-create with the new module's code
let currentCleanup: (() => void) | undefined;
let currentArgs: [Editor] | undefined;
import.meta.hot?.accept((newModule) => {
currentCleanup?.();
if (currentArgs) newModule?.createPortfolioStore(...currentArgs);
});
+76 -81
View File
@@ -5,8 +5,12 @@ import type { ActionShortcut } from "@graphite/../wasm/pkg/graphite_wasm";
import type { Editor } from "@graphite/editor"; import type { Editor } from "@graphite/editor";
import { operatingSystem } from "@graphite/utility-functions/platform"; import { operatingSystem } from "@graphite/utility-functions/platform";
export type TooltipStore = ReturnType<typeof createTooltipStore>;
const SHOW_TOOLTIP_DELAY_MS = 500; const SHOW_TOOLTIP_DELAY_MS = 500;
let tooltipTimeout: ReturnType<typeof setTimeout> | undefined = undefined;
type TooltipStoreState = { type TooltipStoreState = {
visible: boolean; visible: boolean;
element: Element | undefined; element: Element | undefined;
@@ -24,80 +28,15 @@ const initialState: TooltipStoreState = {
fullscreenShortcut: undefined, fullscreenShortcut: undefined,
}; };
let editorRef: Editor | undefined = undefined;
// Store state persisted across HMR to maintain reactive subscriptions in the component tree // Store state persisted across HMR to maintain reactive subscriptions in the component tree
const store: Writable<TooltipStoreState> = import.meta.hot?.data?.store || writable<TooltipStoreState>(initialState); const store: Writable<TooltipStoreState> = import.meta.hot?.data?.store || writable<TooltipStoreState>(initialState);
if (import.meta.hot) import.meta.hot.data.store = store; if (import.meta.hot) import.meta.hot.data.store = store;
const { subscribe, update } = store; const { subscribe, update } = store;
export function createTooltipStore(editor: Editor) { export function createTooltipStore(editor: Editor) {
let tooltipTimeout: ReturnType<typeof setTimeout> | undefined = undefined; editorRef = editor;
// Listen for mouse movements onto tooltip-bearing HTML elements to track the future target of a tooltip
const onMouseOver = (e: MouseEvent) => {
const element = (e.target instanceof Element && e.target.closest("[data-tooltip-label], [data-tooltip-description], [data-tooltip-shortcut]")) || undefined;
update((state) => {
state.visible = false;
state.element = element;
return state;
});
};
// Listen for mouse movements to schedule and position the tooltip, or hide it immediately upon further movement
const onMouseMove = (e: MouseEvent) => {
// Hide the tooltip now that the cursor has moved
update((state) => {
state.visible = false;
return state;
});
// Before we schedule a new future tooltip appearance, we clear the existing one
if (tooltipTimeout) clearTimeout(tooltipTimeout);
// Don't show tooltips while mouse buttons are pressed
if (e.buttons !== 0) return;
// Schedule the tooltip to appear at this cursor position after a delay
tooltipTimeout = setTimeout(() => {
update((state) => {
if (state.element) {
state.visible = true;
state.position = { x: e.clientX, y: e.clientY };
}
return state;
});
}, SHOW_TOOLTIP_DELAY_MS);
};
// Hide tooltip and cancel any pending timeout when the mouse leaves the application window
const onMouseLeave = () => {
if (tooltipTimeout) clearTimeout(tooltipTimeout);
closeTooltip();
};
// Stop showing a tooltip if the user clicks or presses a key, and require the user to first move out of the element before it can re-appear
function closeTooltip() {
update((state) => {
state.visible = false;
state.element = undefined;
return state;
});
}
function destroy() {
if (tooltipTimeout) clearTimeout(tooltipTimeout);
document.removeEventListener("mouseover", onMouseOver);
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseleave", onMouseLeave);
document.removeEventListener("mousedown", closeTooltip);
document.removeEventListener("keydown", closeTooltip);
document.removeEventListener("wheel", closeTooltip);
editor.subscriptions.unsubscribeFrontendMessage("SendShortcutShiftClick");
editor.subscriptions.unsubscribeFrontendMessage("SendShortcutAltClick");
editor.subscriptions.unsubscribeFrontendMessage("SendShortcutFullscreen");
}
document.addEventListener("mouseover", onMouseOver); document.addEventListener("mouseover", onMouseOver);
document.addEventListener("mousemove", onMouseMove); document.addEventListener("mousemove", onMouseMove);
@@ -125,19 +64,75 @@ export function createTooltipStore(editor: Editor) {
}); });
}); });
currentCleanup = destroy; return { subscribe };
currentArgs = [editor];
return {
subscribe,
destroy,
};
} }
export type TooltipStore = ReturnType<typeof createTooltipStore>;
// Self-accepting HMR: tear down the old instance and re-create with the new module's code export function destroyTooltipStore() {
let currentCleanup: (() => void) | undefined; const editor = editorRef;
let currentArgs: [Editor] | undefined; if (!editor) return;
import.meta.hot?.accept((newModule) => {
currentCleanup?.(); if (tooltipTimeout) clearTimeout(tooltipTimeout);
if (currentArgs) newModule?.createTooltipStore(...currentArgs);
document.removeEventListener("mouseover", onMouseOver);
document.removeEventListener("mousemove", onMouseMove);
document.removeEventListener("mouseleave", onMouseLeave);
document.removeEventListener("mousedown", closeTooltip);
document.removeEventListener("keydown", closeTooltip);
document.removeEventListener("wheel", closeTooltip);
editor.subscriptions.unsubscribeFrontendMessage("SendShortcutShiftClick");
editor.subscriptions.unsubscribeFrontendMessage("SendShortcutAltClick");
editor.subscriptions.unsubscribeFrontendMessage("SendShortcutFullscreen");
}
// Listen for mouse movements onto tooltip-bearing HTML elements to track the future target of a tooltip
function onMouseOver(e: MouseEvent) {
const element = (e.target instanceof Element && e.target.closest("[data-tooltip-label], [data-tooltip-description], [data-tooltip-shortcut]")) || undefined;
update((state) => {
state.visible = false;
state.element = element;
return state;
}); });
}
// Listen for mouse movements to schedule and position the tooltip, or hide it immediately upon further movement
function onMouseMove(e: MouseEvent) {
// Hide the tooltip now that the cursor has moved
update((state) => {
state.visible = false;
return state;
});
// Before we schedule a new future tooltip appearance, we clear the existing one
if (tooltipTimeout) clearTimeout(tooltipTimeout);
// Don't show tooltips while mouse buttons are pressed
if (e.buttons !== 0) return;
// Schedule the tooltip to appear at this cursor position after a delay
tooltipTimeout = setTimeout(() => {
update((state) => {
if (state.element) {
state.visible = true;
state.position = { x: e.clientX, y: e.clientY };
}
return state;
});
}, SHOW_TOOLTIP_DELAY_MS);
}
// Hide tooltip and cancel any pending timeout when the mouse leaves the application window
function onMouseLeave() {
if (tooltipTimeout) clearTimeout(tooltipTimeout);
closeTooltip();
}
// Stop showing a tooltip if the user clicks or presses a key, and require the user to first move out of the element before it can re-appear
function closeTooltip() {
update((state) => {
state.visible = false;
state.element = undefined;
return state;
});
}
+6
View File
@@ -187,6 +187,12 @@ impl EditorHandle {
// the backend from the web frontend. // the backend from the web frontend.
// ======================================================================== // ========================================================================
/// Re-sends all UI layouts to the frontend. Called during HMR re-mounts when the frontend has lost its layout state.
#[wasm_bindgen(js_name = resendAllLayouts)]
pub fn resend_all_layouts(&self) {
self.dispatch(LayoutMessage::ResendAllLayouts);
}
#[wasm_bindgen(js_name = initAfterFrontendReady)] #[wasm_bindgen(js_name = initAfterFrontendReady)]
pub fn init_after_frontend_ready(&self) { pub fn init_after_frontend_ready(&self) {
// Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice // Enforce idempotency, so if this is called again during an HMR re-mount, we don't initialize the editor backend twice