Skip to content

Commit

Permalink
Prefer arrow functions and callbacks (excalidraw#1210)
Browse files Browse the repository at this point in the history
  • Loading branch information
lipis authored May 20, 2020
1 parent 33fe223 commit c427aa3
Show file tree
Hide file tree
Showing 64 changed files with 785 additions and 848 deletions.
16 changes: 8 additions & 8 deletions src/actions/actionZindex.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,15 @@ import {
import { ExcalidrawElement } from "../element/types";
import { AppState } from "../types";

function getElementIndices(
const getElementIndices = (
direction: "left" | "right",
elements: readonly ExcalidrawElement[],
appState: AppState,
) {
) => {
const selectedIndices: number[] = [];
let deletedIndicesCache: number[] = [];

function cb(element: ExcalidrawElement, index: number) {
const cb = (element: ExcalidrawElement, index: number) => {
if (element.isDeleted) {
// we want to build an array of deleted elements that are preceeding
// a selected element so that we move them together
Expand All @@ -39,7 +39,7 @@ function getElementIndices(
// of selected/deleted elements, of after encountering non-deleted elem
deletedIndicesCache = [];
}
}
};

// sending back → select contiguous deleted elements that are to the left of
// selected element(s)
Expand All @@ -59,19 +59,19 @@ function getElementIndices(
}
// sort in case we were gathering indexes from right to left
return selectedIndices.sort();
}
};

function moveElements(
const moveElements = (
func: typeof moveOneLeft,
elements: readonly ExcalidrawElement[],
appState: AppState,
) {
) => {
const _elements = elements.slice();
const direction =
func === moveOneLeft || func === moveAllLeft ? "left" : "right";
const indices = getElementIndices(direction, _elements, appState);
return func(_elements, indices);
}
};

export const actionSendBackward = register({
name: "sendBackward",
Expand Down
4 changes: 2 additions & 2 deletions src/actions/register.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { Action } from "./types";

export let actions: readonly Action[] = [];

export function register(action: Action): Action {
export const register = (action: Action): Action => {
actions = actions.concat(action);
return action;
}
};
18 changes: 9 additions & 9 deletions src/appState.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { t } from "./i18n";
export const DEFAULT_FONT = "20px Virgil";
export const DEFAULT_TEXT_ALIGN = "left";

export function getDefaultAppState(): AppState {
export const getDefaultAppState = (): AppState => {
return {
isLoading: false,
errorMessage: null,
Expand Down Expand Up @@ -49,9 +49,9 @@ export function getDefaultAppState(): AppState {
showShortcutsDialog: false,
zenModeEnabled: false,
};
}
};

export function clearAppStateForLocalStorage(appState: AppState) {
export const clearAppStateForLocalStorage = (appState: AppState) => {
const {
draggingElement,
resizingElement,
Expand All @@ -68,11 +68,11 @@ export function clearAppStateForLocalStorage(appState: AppState) {
...exportedState
} = appState;
return exportedState;
}
};

export function clearAppStatePropertiesForHistory(
export const clearAppStatePropertiesForHistory = (
appState: AppState,
): Partial<AppState> {
): Partial<AppState> => {
return {
selectedElementIds: appState.selectedElementIds,
exportBackground: appState.exportBackground,
Expand All @@ -88,10 +88,10 @@ export function clearAppStatePropertiesForHistory(
viewBackgroundColor: appState.viewBackgroundColor,
name: appState.name,
};
}
};

export function cleanAppStateForExport(appState: AppState) {
export const cleanAppStateForExport = (appState: AppState) => {
return {
viewBackgroundColor: appState.viewBackgroundColor,
};
}
};
37 changes: 18 additions & 19 deletions src/clipboard.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,10 @@ export const probablySupportsClipboardBlob =
"ClipboardItem" in window &&
"toBlob" in HTMLCanvasElement.prototype;

export async function copyToAppClipboard(
export const copyToAppClipboard = async (
elements: readonly NonDeletedExcalidrawElement[],
appState: AppState,
) {
) => {
CLIPBOARD = JSON.stringify(getSelectedElements(elements, appState));
try {
// when copying to in-app clipboard, clear system clipboard so that if
Expand All @@ -38,11 +38,11 @@ export async function copyToAppClipboard(
// we can't be sure of the order of copy operations
PREFER_APP_CLIPBOARD = true;
}
}
};

export function getAppClipboard(): {
export const getAppClipboard = (): {
elements?: readonly ExcalidrawElement[];
} {
} => {
if (!CLIPBOARD) {
return {};
}
Expand All @@ -62,14 +62,14 @@ export function getAppClipboard(): {
}

return {};
}
};

export async function getClipboardContent(
export const getClipboardContent = async (
event: ClipboardEvent | null,
): Promise<{
text?: string;
elements?: readonly ExcalidrawElement[];
}> {
}> => {
try {
const text = event
? event.clipboardData?.getData("text/plain").trim()
Expand All @@ -84,12 +84,12 @@ export async function getClipboardContent(
}

return getAppClipboard();
}
};

export async function copyCanvasToClipboardAsPng(canvas: HTMLCanvasElement) {
return new Promise((resolve, reject) => {
export const copyCanvasToClipboardAsPng = async (canvas: HTMLCanvasElement) =>
new Promise((resolve, reject) => {
try {
canvas.toBlob(async function (blob: any) {
canvas.toBlob(async (blob: any) => {
try {
await navigator.clipboard.write([
new window.ClipboardItem({ "image/png": blob }),
Expand All @@ -103,17 +103,16 @@ export async function copyCanvasToClipboardAsPng(canvas: HTMLCanvasElement) {
reject(error);
}
});
}

export async function copyCanvasToClipboardAsSvg(svgroot: SVGSVGElement) {
export const copyCanvasToClipboardAsSvg = async (svgroot: SVGSVGElement) => {
try {
await navigator.clipboard.writeText(svgroot.outerHTML);
} catch (error) {
console.error(error);
}
}
};

export async function copyTextToSystemClipboard(text: string | null) {
export const copyTextToSystemClipboard = async (text: string | null) => {
let copied = false;
if (probablySupportsClipboardWriteText) {
try {
Expand All @@ -131,10 +130,10 @@ export async function copyTextToSystemClipboard(text: string | null) {
if (!copied && !copyTextViaExecCommand(text || " ")) {
throw new Error("couldn't copy");
}
}
};

// adapted from https://github.com/zenorocha/clipboard.js/blob/ce79f170aa655c408b6aab33c9472e8e4fa52e19/src/clipboard-action.js#L48
function copyTextViaExecCommand(text: string) {
const copyTextViaExecCommand = (text: string) => {
const isRTL = document.documentElement.getAttribute("dir") === "rtl";

const textarea = document.createElement("textarea");
Expand Down Expand Up @@ -168,4 +167,4 @@ function copyTextViaExecCommand(text: string) {
textarea.remove();

return success;
}
};
100 changes: 48 additions & 52 deletions src/components/Actions.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import Stack from "./Stack";
import useIsMobile from "../is-mobile";
import { getNonDeletedElements } from "../element";

export function SelectedShapeActions({
export const SelectedShapeActions = ({
appState,
elements,
renderAction,
Expand All @@ -21,7 +21,7 @@ export function SelectedShapeActions({
elements: readonly ExcalidrawElement[];
renderAction: ActionManager["renderAction"];
elementType: ExcalidrawElement["type"];
}) {
}) => {
const targetElements = getTargetElement(
getNonDeletedElements(elements),
appState,
Expand Down Expand Up @@ -83,65 +83,61 @@ export function SelectedShapeActions({
)}
</div>
);
}
};

export function ShapesSwitcher({
export const ShapesSwitcher = ({
elementType,
setAppState,
}: {
elementType: ExcalidrawElement["type"];
setAppState: any;
}) {
return (
<>
{SHAPES.map(({ value, icon, key }, index) => {
const label = t(`toolBar.${value}`);
const shortcut = `${capitalizeString(key)} ${t("shortcutsDialog.or")} ${
index + 1
}`;
return (
<ToolButton
key={value}
type="radio"
icon={icon}
checked={elementType === value}
name="editor-current-shape"
title={`${capitalizeString(label)}${shortcut}`}
keyBindingLabel={`${index + 1}`}
aria-label={capitalizeString(label)}
aria-keyshortcuts={`${key} ${index + 1}`}
data-testid={value}
onChange={() => {
setAppState({
elementType: value,
multiElement: null,
selectedElementIds: {},
});
setCursorForShape(value);
setAppState({});
}}
></ToolButton>
);
})}
</>
);
}
}) => (
<>
{SHAPES.map(({ value, icon, key }, index) => {
const label = t(`toolBar.${value}`);
const shortcut = `${capitalizeString(key)} ${t("shortcutsDialog.or")} ${
index + 1
}`;
return (
<ToolButton
key={value}
type="radio"
icon={icon}
checked={elementType === value}
name="editor-current-shape"
title={`${capitalizeString(label)}${shortcut}`}
keyBindingLabel={`${index + 1}`}
aria-label={capitalizeString(label)}
aria-keyshortcuts={`${key} ${index + 1}`}
data-testid={value}
onChange={() => {
setAppState({
elementType: value,
multiElement: null,
selectedElementIds: {},
});
setCursorForShape(value);
setAppState({});
}}
></ToolButton>
);
})}
</>
);

export function ZoomActions({
export const ZoomActions = ({
renderAction,
zoom,
}: {
renderAction: ActionManager["renderAction"];
zoom: number;
}) {
return (
<Stack.Col gap={1}>
<Stack.Row gap={1} align="center">
{renderAction("zoomIn")}
{renderAction("zoomOut")}
{renderAction("resetZoom")}
<div style={{ marginInlineStart: 4 }}>{(zoom * 100).toFixed(0)}%</div>
</Stack.Row>
</Stack.Col>
);
}
}) => (
<Stack.Col gap={1}>
<Stack.Row gap={1} align="center">
{renderAction("zoomIn")}
{renderAction("zoomOut")}
{renderAction("resetZoom")}
<div style={{ marginInlineStart: 4 }}>{(zoom * 100).toFixed(0)}%</div>
</Stack.Row>
</Stack.Col>
);
13 changes: 6 additions & 7 deletions src/components/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -136,13 +136,14 @@ import throttle from "lodash.throttle";
/**
* @param func handler taking at most single parameter (event).
*/
function withBatchedUpdates<
const withBatchedUpdates = <
TFunction extends ((event: any) => void) | (() => void)
>(func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never) {
return ((event) => {
>(
func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never,
) =>
((event) => {
unstable_batchedUpdates(func as TFunction, event);
}) as TFunction;
}

const { history } = createHistory();

Expand Down Expand Up @@ -2748,9 +2749,7 @@ if (
},
},
history: {
get() {
return history;
},
get: () => history,
},
});
}
Expand Down
Loading

0 comments on commit c427aa3

Please sign in to comment.