Vue initialization and FloatingMenu codebase refactoring and cleanup (#649)

* Clean up Vue initialization-related code

* Rename folder: dispatcher -> interop

* Rename folder: state -> providers

* Comments and clarification

* Rename JS dispatcher to subscription router

* Assorted cleanup and renaming

* Rename: js-messages.ts -> messages.ts

* Comments

* Remove unused Vue component injects

* Clean up coming soon and add warning about freezing the app

* Further cleanup

* Dangerous changes

* Simplify App.vue code

* Move more disparate init code from components into managers

* Rename folder: providers -> state-providers

* Other

* Move Document panel options bar separator to backend

* Add destructors to managers to fix HMR

* Comments and code style

* Rename variable: font -> font_file_url

* Fix async font loading; refactor janky floating menu openness and min-width measurement; fix Vetur errors

* Fix misaligned canvas in viewport until panning on page (re)load

* Add Vue bidirectional props documentation

* More folder renaming for better terminology; add some documentation
This commit is contained in:
Keavon Chambers
2022-05-21 19:46:15 -07:00
parent 4c3c925c2c
commit fc2d983bd7
73 changed files with 1572 additions and 1462 deletions
+53
View File
@@ -0,0 +1,53 @@
import { reactive, readonly } from "vue";
import { TextButtonWidget } from "@/components/widgets/buttons/TextButton";
import { IconName } from "@/utility-functions/icons";
import { Editor } from "@/wasm-communication/editor";
import { defaultWidgetLayout, DisplayDialog, DisplayDialogDismiss, UpdateDialogDetails, WidgetLayout } from "@/wasm-communication/messages";
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createDialogState(editor: Editor) {
const state = reactive({
visible: false,
icon: "" as IconName,
widgets: defaultWidgetLayout(),
// Special case for the crash dialog because we cannot handle button widget callbacks from Rust once the editor instance has panicked
jsCallbackBasedButtons: undefined as undefined | TextButtonWidget[],
});
function dismissDialog(): void {
state.visible = false;
}
function dialogIsVisible(): boolean {
return state.visible;
}
// Creates a panic dialog from JS.
// Normal dialogs are created in the Rust backend, but for the crash dialog, the editor instance has panicked so it cannot respond to widget callbacks.
function createPanicDialog(icon: IconName, widgets: WidgetLayout, jsCallbackBasedButtons: TextButtonWidget[]): void {
state.visible = true;
state.icon = icon;
state.widgets = widgets;
state.jsCallbackBasedButtons = jsCallbackBasedButtons;
}
// Subscribe to process backend events
editor.subscriptions.subscribeJsMessage(DisplayDialog, (displayDialog) => {
state.visible = true;
state.icon = displayDialog.icon;
});
editor.subscriptions.subscribeJsMessage(UpdateDialogDetails, (updateDialogDetails) => {
state.widgets = updateDialogDetails;
state.jsCallbackBasedButtons = undefined;
});
editor.subscriptions.subscribeJsMessage(DisplayDialogDismiss, dismissDialog);
return {
state: readonly(state) as typeof state,
dismissDialog,
dialogIsVisible,
createPanicDialog,
};
}
export type DialogState = ReturnType<typeof createDialogState>;
+95
View File
@@ -0,0 +1,95 @@
import { reactive, readonly } from "vue";
import { Editor } from "@/wasm-communication/editor";
import { TriggerFontLoad, TriggerFontLoadDefault } from "@/wasm-communication/messages";
const DEFAULT_FONT = "Merriweather";
const DEFAULT_FONT_STYLE = "Normal (400)";
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createFontsState(editor: Editor) {
const state = reactive({
fontNames: [] as string[],
});
async function getFontStyles(fontFamily: string): Promise<string[]> {
const font = (await fontList).find((value) => value.family === fontFamily);
return font?.variants || [];
}
async function getFontFileUrl(fontFamily: string, fontStyle: string): Promise<string | undefined> {
const font = (await fontList).find((value) => value.family === fontFamily);
const fontFileUrl = font?.files.get(fontStyle);
return fontFileUrl?.replace("http://", "https://");
}
function formatFontStyleName(fontStyle: string): string {
const isItalic = fontStyle.endsWith("italic");
const weight = fontStyle === "regular" || fontStyle === "italic" ? 400 : parseInt(fontStyle, 10);
let weightName = "";
let bestWeight = Infinity;
weightNameMapping.forEach((nameChecking, weightChecking) => {
if (Math.abs(weightChecking - weight) < bestWeight) {
bestWeight = Math.abs(weightChecking - weight);
weightName = nameChecking;
}
});
return `${weightName}${isItalic ? " Italic" : ""} (${weight})`;
}
// Subscribe to process backend events
editor.subscriptions.subscribeJsMessage(TriggerFontLoadDefault, async (): Promise<void> => {
const fontFileUrl = await getFontFileUrl(DEFAULT_FONT, DEFAULT_FONT_STYLE);
if (!fontFileUrl) return;
const response = await fetch(fontFileUrl);
const responseBuffer = await response.arrayBuffer();
editor.instance.on_font_load(fontFileUrl, new Uint8Array(responseBuffer), true);
});
editor.subscriptions.subscribeJsMessage(TriggerFontLoad, async (triggerFontLoad) => {
const response = await (await fetch(triggerFontLoad.font_file_url)).arrayBuffer();
editor.instance.on_font_load(triggerFontLoad.font_file_url, new Uint8Array(response), false);
});
const fontList: Promise<{ family: string; variants: string[]; files: Map<string, string> }[]> = new Promise((resolve) => {
fetch(fontListAPI)
.then((response) => response.json())
.then((fontListResponse) => {
const fontListData = fontListResponse.items as { family: string; variants: string[]; files: { [name: string]: string } }[];
const result = fontListData.map((font) => {
const { family } = font;
const variants = font.variants.map(formatFontStyleName);
const files = new Map(font.variants.map((x) => [formatFontStyleName(x), font.files[x]]));
return { family, variants, files };
});
state.fontNames = result.map((value) => value.family);
resolve(result);
});
});
return {
state: readonly(state) as typeof state,
getFontStyles,
getFontFileUrl,
};
}
export type FontsState = ReturnType<typeof createFontsState>;
const fontListAPI = "https://api.graphite.rs/font-list";
// From https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#common_weight_name_mapping
const weightNameMapping = new Map([
[100, "Thin"],
[200, "Extra Light"],
[300, "Light"],
[400, "Normal"],
[500, "Medium"],
[600, "Semi Bold"],
[700, "Bold"],
[800, "Extra Bold"],
[900, "Black"],
[950, "Extra Black"],
]);
@@ -0,0 +1,47 @@
import { reactive, readonly } from "vue";
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createFullscreenState() {
const state = reactive({
windowFullscreen: false,
keyboardLocked: false,
});
function fullscreenModeChanged(): void {
state.windowFullscreen = Boolean(document.fullscreenElement);
if (!state.windowFullscreen) state.keyboardLocked = false;
}
async function enterFullscreen(): Promise<void> {
await document.documentElement.requestFullscreen();
if (keyboardLockApiSupported) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
await (navigator as any).keyboard.lock(["ControlLeft", "ControlRight"]);
state.keyboardLocked = true;
}
}
async function exitFullscreen(): Promise<void> {
await document.exitFullscreen();
}
async function toggleFullscreen(): Promise<void> {
if (state.windowFullscreen) await exitFullscreen();
else await enterFullscreen();
}
// Experimental Keyboard API: https://developer.mozilla.org/en-US/docs/Web/API/Navigator/keyboard
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const keyboardLockApiSupported: Readonly<boolean> = "keyboard" in navigator && (navigator as any).keyboard && "lock" in (navigator as any).keyboard;
return {
state: readonly(state) as typeof state,
fullscreenModeChanged,
enterFullscreen,
exitFullscreen,
toggleFullscreen,
keyboardLockApiSupported,
};
}
export type FullscreenState = ReturnType<typeof createFullscreenState>;
+71
View File
@@ -0,0 +1,71 @@
/* eslint-disable max-classes-per-file */
import { reactive, readonly } from "vue";
import { download, downloadBlob, upload } from "@/utility-functions/files";
import { Editor } from "@/wasm-communication/editor";
import { TriggerFileDownload, TriggerRasterDownload, FrontendDocumentDetails, TriggerFileUpload, UpdateActiveDocument, UpdateOpenDocumentsList } from "@/wasm-communication/messages";
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createPortfolioState(editor: Editor) {
const state = reactive({
unsaved: false,
documents: [] as FrontendDocumentDetails[],
activeDocumentIndex: 0,
});
// Set up message subscriptions on creation
editor.subscriptions.subscribeJsMessage(UpdateOpenDocumentsList, (updateOpenDocumentList) => {
state.documents = updateOpenDocumentList.open_documents;
});
editor.subscriptions.subscribeJsMessage(UpdateActiveDocument, (updateActiveDocument) => {
// Assume we receive a correct document id
const activeId = state.documents.findIndex((doc) => doc.id === updateActiveDocument.document_id);
state.activeDocumentIndex = activeId;
});
editor.subscriptions.subscribeJsMessage(TriggerFileUpload, async () => {
const extension = editor.raw.file_save_suffix();
const data = await upload(extension);
editor.instance.open_document_file(data.filename, data.content);
});
editor.subscriptions.subscribeJsMessage(TriggerFileDownload, (triggerFileDownload) => {
download(triggerFileDownload.name, triggerFileDownload.document);
});
editor.subscriptions.subscribeJsMessage(TriggerRasterDownload, (triggerRasterDownload) => {
// A canvas to render our svg to in order to get a raster image
// https://stackoverflow.com/questions/3975499/convert-svg-to-image-jpeg-png-etc-in-the-browser
const canvas = document.createElement("canvas");
canvas.width = triggerRasterDownload.size.x;
canvas.height = triggerRasterDownload.size.y;
const context = canvas.getContext("2d");
if (!context) return;
// Fill the canvas with white if jpeg (does not support transparency and defaults to black)
if (triggerRasterDownload.mime.endsWith("jpg")) {
context.fillStyle = "white";
context.fillRect(0, 0, triggerRasterDownload.size.x, triggerRasterDownload.size.y);
}
// Create a blob url for our svg
const img = new Image();
const svgBlob = new Blob([triggerRasterDownload.document], { type: "image/svg+xml;charset=utf-8" });
const url = URL.createObjectURL(svgBlob);
img.onload = (): void => {
// Draw our svg to the canvas
context?.drawImage(img, 0, 0, triggerRasterDownload.size.x, triggerRasterDownload.size.y);
// Convert the canvas to an image of the correct mime
const imgURI = canvas.toDataURL(triggerRasterDownload.mime);
// Download our canvas
downloadBlob(imgURI, triggerRasterDownload.name);
// Cleanup resources
URL.revokeObjectURL(url);
};
img.src = url;
});
return {
state: readonly(state) as typeof state,
};
}
export type PortfolioState = ReturnType<typeof createPortfolioState>;
+22
View File
@@ -0,0 +1,22 @@
/* eslint-disable max-classes-per-file */
import { reactive, readonly } from "vue";
import { Editor } from "@/wasm-communication/editor";
import { UpdateNodeGraphVisibility } from "@/wasm-communication/messages";
// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
export function createWorkspaceState(editor: Editor) {
const state = reactive({
nodeGraphVisible: false,
});
// Set up message subscriptions on creation
editor.subscriptions.subscribeJsMessage(UpdateNodeGraphVisibility, (updateNodeGraphVisibility) => {
state.nodeGraphVisible = updateNodeGraphVisibility.visible;
});
return {
state: readonly(state) as typeof state,
};
}
export type WorkspaceState = ReturnType<typeof createWorkspaceState>;