Refactor: e -> event or error, err -> error, p -> pointer (#831)

* Refactor: e -> event or error, err -> error, p -> pointer

* simplify
This commit is contained in:
Lipis 2020-02-28 23:03:53 +01:00 committed by GitHub
parent d2827aa40b
commit 097c5dfad7
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
14 changed files with 190 additions and 185 deletions

View File

@ -31,9 +31,7 @@ export const actionChangeExportBackground: Action = {
<input <input
type="checkbox" type="checkbox"
checked={appState.exportBackground} checked={appState.exportBackground}
onChange={e => { onChange={event => updateData(event.target.checked)}
updateData(e.target.checked);
}}
/>{" "} />{" "}
{t("labels.withBackground")} {t("labels.withBackground")}
</label> </label>
@ -43,7 +41,7 @@ export const actionChangeExportBackground: Action = {
export const actionSaveScene: Action = { export const actionSaveScene: Action = {
name: "saveScene", name: "saveScene",
perform: (elements, appState, value) => { perform: (elements, appState, value) => {
saveAsJSON(elements, appState).catch(err => console.error(err)); saveAsJSON(elements, appState).catch(error => console.error(error));
return {}; return {};
}, },
PanelComponent: ({ updateData }) => ( PanelComponent: ({ updateData }) => (
@ -79,7 +77,7 @@ export const actionLoadScene: Action = {
.then(({ elements, appState }) => { .then(({ elements, appState }) => {
updateData({ elements: elements, appState: appState }); updateData({ elements: elements, appState: appState });
}) })
.catch(err => console.error(err)); .catch(error => console.error(error));
}} }}
/> />
), ),

View File

@ -229,18 +229,18 @@ export const actionChangeOpacity: Action = {
min="0" min="0"
max="100" max="100"
step="10" step="10"
onChange={e => updateData(+e.target.value)} onChange={event => updateData(+event.target.value)}
onWheel={e => { onWheel={event => {
e.stopPropagation(); event.stopPropagation();
const target = e.target as HTMLInputElement; const target = event.target as HTMLInputElement;
const STEP = 10; const STEP = 10;
const MAX = 100; const MAX = 100;
const MIN = 0; const MIN = 0;
const value = +target.value; const value = +target.value;
if (e.deltaY < 0 && value < MAX) { if (event.deltaY < 0 && value < MAX) {
updateData(value + STEP); updateData(value + STEP);
} else if (e.deltaY > 0 && value > MIN) { } else if (event.deltaY > 0 && value > MIN) {
updateData(value - STEP); updateData(value - STEP);
} }
}} }}

View File

@ -91,7 +91,7 @@ export const actionSendBackward: Action = {
<button <button
type="button" type="button"
className="zIndexButton" className="zIndexButton"
onClick={e => updateData(null)} onClick={event => updateData(null)}
title={t("labels.sendBackward")} title={t("labels.sendBackward")}
> >
{ICONS.sendBackward} {ICONS.sendBackward}
@ -115,7 +115,7 @@ export const actionBringForward: Action = {
<button <button
type="button" type="button"
className="zIndexButton" className="zIndexButton"
onClick={e => updateData(null)} onClick={event => updateData(null)}
title={t("labels.bringForward")} title={t("labels.bringForward")}
> >
{ICONS.bringForward} {ICONS.bringForward}
@ -138,7 +138,7 @@ export const actionSendToBack: Action = {
<button <button
type="button" type="button"
className="zIndexButton" className="zIndexButton"
onClick={e => updateData(null)} onClick={event => updateData(null)}
title={t("labels.sendToBack")} title={t("labels.sendToBack")}
> >
{ICONS.sendToBack} {ICONS.sendToBack}
@ -161,7 +161,7 @@ export const actionBringToFront: Action = {
<button <button
type="button" type="button"
className="zIndexButton" className="zIndexButton"
onClick={e => updateData(null)} onClick={event => updateData(null)}
title={t("labels.bringToFront")} title={t("labels.bringToFront")}
> >
{ICONS.bringToFront} {ICONS.bringToFront}

View File

@ -28,7 +28,7 @@ export async function copyToAppClipboard(
// copied elements, and thus we should prefer the text content. // copied elements, and thus we should prefer the text content.
await copyTextToSystemClipboard(null); await copyTextToSystemClipboard(null);
PREFER_APP_CLIPBOARD = false; PREFER_APP_CLIPBOARD = false;
} catch (err) { } catch (error) {
// if clearing system clipboard didn't work, we should prefer in-app // if clearing system clipboard didn't work, we should prefer in-app
// clipboard even if there's text in system clipboard on paste, because // clipboard even if there's text in system clipboard on paste, because
// we can't be sure of the order of copy operations // we can't be sure of the order of copy operations
@ -49,30 +49,30 @@ export function getAppClipboard(): {
) { ) {
return { elements: clipboardElements }; return { elements: clipboardElements };
} }
} catch (err) { } catch (error) {
console.error(err); console.error(error);
} }
return {}; return {};
} }
export async function getClipboardContent( export async function getClipboardContent(
e: ClipboardEvent | null, event: ClipboardEvent | null,
): Promise<{ ): Promise<{
text?: string; text?: string;
elements?: readonly ExcalidrawElement[]; elements?: readonly ExcalidrawElement[];
}> { }> {
try { try {
const text = e const text = event
? e.clipboardData?.getData("text/plain").trim() ? event.clipboardData?.getData("text/plain").trim()
: probablySupportsClipboardReadText && : probablySupportsClipboardReadText &&
(await navigator.clipboard.readText()); (await navigator.clipboard.readText());
if (text && !PREFER_APP_CLIPBOARD) { if (text && !PREFER_APP_CLIPBOARD) {
return { text }; return { text };
} }
} catch (err) { } catch (error) {
console.error(err); console.error(error);
} }
return getAppClipboard(); return getAppClipboard();
@ -87,12 +87,12 @@ export async function copyCanvasToClipboardAsPng(canvas: HTMLCanvasElement) {
new window.ClipboardItem({ "image/png": blob }), new window.ClipboardItem({ "image/png": blob }),
]); ]);
resolve(); resolve();
} catch (err) { } catch (error) {
reject(err); reject(error);
} }
}); });
} catch (err) { } catch (error) {
reject(err); reject(error);
} }
}); });
} }
@ -105,7 +105,7 @@ export async function copyTextToSystemClipboard(text: string | null) {
// not focused // not focused
await navigator.clipboard.writeText(text || ""); await navigator.clipboard.writeText(text || "");
copied = true; copied = true;
} catch (err) {} } catch (error) {}
} }
// Note that execCommand doesn't allow copying empty strings, so if we're // Note that execCommand doesn't allow copying empty strings, so if we're
@ -143,7 +143,7 @@ function copyTextViaExecCommand(text: string) {
textarea.setSelectionRange(0, textarea.value.length); textarea.setSelectionRange(0, textarea.value.length);
success = document.execCommand("copy"); success = document.execCommand("copy");
} catch (err) {} } catch (error) {}
textarea.remove(); textarea.remove();

View File

@ -45,25 +45,25 @@ const Picker = function({
} }
}, []); }, []);
const handleKeyDown = (e: React.KeyboardEvent) => { const handleKeyDown = (event: React.KeyboardEvent) => {
if (e.key === KEYS.TAB) { if (event.key === KEYS.TAB) {
const { activeElement } = document; const { activeElement } = document;
if (e.shiftKey) { if (event.shiftKey) {
if (activeElement === firstItem.current) { if (activeElement === firstItem.current) {
colorInput.current?.focus(); colorInput.current?.focus();
e.preventDefault(); event.preventDefault();
} }
} else { } else {
if (activeElement === colorInput.current) { if (activeElement === colorInput.current) {
firstItem.current?.focus(); firstItem.current?.focus();
e.preventDefault(); event.preventDefault();
} }
} }
} else if ( } else if (
e.key === KEYS.ARROW_RIGHT || event.key === KEYS.ARROW_RIGHT ||
e.key === KEYS.ARROW_LEFT || event.key === KEYS.ARROW_LEFT ||
e.key === KEYS.ARROW_UP || event.key === KEYS.ARROW_UP ||
e.key === KEYS.ARROW_DOWN event.key === KEYS.ARROW_DOWN
) { ) {
const { activeElement } = document; const { activeElement } = document;
const index = Array.prototype.indexOf.call( const index = Array.prototype.indexOf.call(
@ -73,30 +73,30 @@ const Picker = function({
if (index !== -1) { if (index !== -1) {
const length = gallery!.current!.children.length; const length = gallery!.current!.children.length;
const nextIndex = const nextIndex =
e.key === KEYS.ARROW_RIGHT event.key === KEYS.ARROW_RIGHT
? (index + 1) % length ? (index + 1) % length
: e.key === KEYS.ARROW_LEFT : event.key === KEYS.ARROW_LEFT
? (length + index - 1) % length ? (length + index - 1) % length
: e.key === KEYS.ARROW_DOWN : event.key === KEYS.ARROW_DOWN
? (index + 5) % length ? (index + 5) % length
: e.key === KEYS.ARROW_UP : event.key === KEYS.ARROW_UP
? (length + index - 5) % length ? (length + index - 5) % length
: index; : index;
(gallery!.current!.children![nextIndex] as any).focus(); (gallery!.current!.children![nextIndex] as any).focus();
} }
e.preventDefault(); event.preventDefault();
} else if ( } else if (
keyBindings.includes(e.key.toLowerCase()) && keyBindings.includes(event.key.toLowerCase()) &&
!isWritableElement(e.target) !isWritableElement(event.target)
) { ) {
const index = keyBindings.indexOf(e.key.toLowerCase()); const index = keyBindings.indexOf(event.key.toLowerCase());
(gallery!.current!.children![index] as any).focus(); (gallery!.current!.children![index] as any).focus();
e.preventDefault(); event.preventDefault();
} else if (e.key === KEYS.ESCAPE || e.key === KEYS.ENTER) { } else if (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) {
e.preventDefault(); event.preventDefault();
onClose(); onClose();
} }
e.nativeEvent.stopImmediatePropagation(); event.nativeEvent.stopImmediatePropagation();
}; };
return ( return (
@ -193,15 +193,15 @@ const ColorInput = React.forwardRef(
spellCheck={false} spellCheck={false}
className="color-picker-input" className="color-picker-input"
aria-label={label} aria-label={label}
onChange={e => { onChange={event => {
const value = e.target.value.toLowerCase(); const value = event.target.value.toLowerCase();
if (value.match(colorRegex)) { if (value.match(colorRegex)) {
onChange(value === "transparent" ? "transparent" : `#${value}`); onChange(value === "transparent" ? "transparent" : `#${value}`);
} }
setInnerValue(value); setInnerValue(value);
}} }}
value={(innerValue || "").replace(/^#/, "")} value={(innerValue || "").replace(/^#/, "")}
onPaste={e => onChange(e.clipboardData.getData("text"))} onPaste={event => onChange(event.clipboardData.getData("text"))}
onBlur={() => setInnerValue(color)} onBlur={() => setInnerValue(color)}
ref={inputRef} ref={inputRef}
/> />

View File

@ -24,7 +24,10 @@ function ContextMenu({ options, onCloseRequest, top, left }: Props) {
left={left} left={left}
fitInViewport={true} fitInViewport={true}
> >
<ul className="context-menu" onContextMenu={e => e.preventDefault()}> <ul
className="context-menu"
onContextMenu={event => event.preventDefault()}
>
{options.map((option, idx) => ( {options.map((option, idx) => (
<li key={idx} onClick={onCloseRequest}> <li key={idx} onClick={onCloseRequest}>
<ContextMenuOption {...option} /> <ContextMenuOption {...option} />

View File

@ -89,22 +89,22 @@ function ExportModal({
pngButton.current?.focus(); pngButton.current?.focus();
}, []); }, []);
function handleKeyDown(e: React.KeyboardEvent) { function handleKeyDown(event: React.KeyboardEvent) {
if (e.key === KEYS.TAB) { if (event.key === KEYS.TAB) {
const { activeElement } = document; const { activeElement } = document;
if (e.shiftKey) { if (event.shiftKey) {
if (activeElement === pngButton.current) { if (activeElement === pngButton.current) {
closeButton.current?.focus(); closeButton.current?.focus();
e.preventDefault(); event.preventDefault();
} }
} else { } else {
if (activeElement === closeButton.current) { if (activeElement === closeButton.current) {
pngButton.current?.focus(); pngButton.current?.focus();
e.preventDefault(); event.preventDefault();
} }
if (activeElement === onlySelectedInput.current) { if (activeElement === onlySelectedInput.current) {
closeButton.current?.focus(); closeButton.current?.focus();
e.preventDefault(); event.preventDefault();
} }
} }
} }
@ -186,7 +186,9 @@ function ExportModal({
<input <input
type="checkbox" type="checkbox"
checked={exportSelected} checked={exportSelected}
onChange={e => setExportSelected(e.currentTarget.checked)} onChange={event =>
setExportSelected(event.currentTarget.checked)
}
ref={onlySelectedInput} ref={onlySelectedInput}
/>{" "} />{" "}
{t("labels.onlySelected")} {t("labels.onlySelected")}

View File

@ -12,9 +12,9 @@ export function Modal(props: {
}) { }) {
const modalRoot = useBodyRoot(); const modalRoot = useBodyRoot();
const handleKeydown = (e: React.KeyboardEvent) => { const handleKeydown = (event: React.KeyboardEvent) => {
if (e.key === KEYS.ESCAPE) { if (event.key === KEYS.ESCAPE) {
e.nativeEvent.stopImmediatePropagation(); event.nativeEvent.stopImmediatePropagation();
props.onCloseRequest(); props.onCloseRequest();
} }
}; };

View File

@ -40,8 +40,8 @@ export function Popover({
<div <div
className="cover" className="cover"
onClick={onCloseRequest} onClick={onCloseRequest}
onContextMenu={e => { onContextMenu={event => {
e.preventDefault(); event.preventDefault();
if (onCloseRequest) { if (onCloseRequest) {
onCloseRequest(); onCloseRequest();
} }

View File

@ -10,25 +10,25 @@ type Props = {
}; };
export class ProjectName extends Component<Props> { export class ProjectName extends Component<Props> {
private handleFocus = (e: React.FocusEvent<HTMLElement>) => { private handleFocus = (event: React.FocusEvent<HTMLElement>) => {
selectNode(e.currentTarget); selectNode(event.currentTarget);
}; };
private handleBlur = (e: React.FocusEvent<HTMLElement>) => { private handleBlur = (event: React.FocusEvent<HTMLElement>) => {
const value = e.currentTarget.innerText.trim(); const value = event.currentTarget.innerText.trim();
if (value !== this.props.value) { if (value !== this.props.value) {
this.props.onChange(value); this.props.onChange(value);
} }
removeSelection(); removeSelection();
}; };
private handleKeyDown = (e: React.KeyboardEvent<HTMLElement>) => { private handleKeyDown = (event: React.KeyboardEvent<HTMLElement>) => {
if (e.key === "Enter") { if (event.key === "Enter") {
e.preventDefault(); event.preventDefault();
if (e.nativeEvent.isComposing || e.keyCode === 229) { if (event.nativeEvent.isComposing || event.keyCode === 229) {
return; return;
} }
e.currentTarget.blur(); event.currentTarget.blur();
} }
}; };
private makeEditable = (editable: HTMLSpanElement | null) => { private makeEditable = (editable: HTMLSpanElement | null) => {

View File

@ -84,8 +84,8 @@ export function textWysiwyg({
selection.addRange(range); selection.addRange(range);
ev.preventDefault(); ev.preventDefault();
} catch (err) { } catch (error) {
console.error(err); console.error(error);
} }
}; };

View File

@ -3,8 +3,8 @@ import { normalizeScroll } from "./scene/data";
export function getCenter(pointers: readonly Pointer[]) { export function getCenter(pointers: readonly Pointer[]) {
return { return {
x: normalizeScroll(sum(pointers, p => p.x) / pointers.length), x: normalizeScroll(sum(pointers, pointer => pointer.x) / pointers.length),
y: normalizeScroll(sum(pointers, p => p.y) / pointers.length), y: normalizeScroll(sum(pointers, pointer => pointer.y) / pointers.length),
}; };
} }

View File

@ -151,7 +151,7 @@ document.addEventListener(
{ passive: false }, { passive: false },
); );
let lastPointerUp: ((e: any) => void) | null = null; let lastPointerUp: ((event: any) => void) | null = null;
const gesture: Gesture = { const gesture: Gesture = {
pointers: [], pointers: [],
lastCenter: null, lastCenter: null,
@ -712,22 +712,22 @@ export class App extends React.Component<any, AppState> {
} }
}; };
private onCut = (e: ClipboardEvent) => { private onCut = (event: ClipboardEvent) => {
if (isWritableElement(e.target)) { if (isWritableElement(event.target)) {
return; return;
} }
copyToAppClipboard(elements); copyToAppClipboard(elements);
elements = deleteSelectedElements(elements); elements = deleteSelectedElements(elements);
history.resumeRecording(); history.resumeRecording();
this.setState({}); this.setState({});
e.preventDefault(); event.preventDefault();
}; };
private onCopy = (e: ClipboardEvent) => { private onCopy = (event: ClipboardEvent) => {
if (isWritableElement(e.target)) { if (isWritableElement(event.target)) {
return; return;
} }
copyToAppClipboard(elements); copyToAppClipboard(elements);
e.preventDefault(); event.preventDefault();
}; };
private onUnload = () => { private onUnload = () => {
@ -736,8 +736,8 @@ export class App extends React.Component<any, AppState> {
this.saveDebounced.flush(); this.saveDebounced.flush();
}; };
private disableEvent: EventHandlerNonNull = e => { private disableEvent: EventHandlerNonNull = event => {
e.preventDefault(); event.preventDefault();
}; };
private unmounted = false; private unmounted = false;
@ -803,9 +803,9 @@ export class App extends React.Component<any, AppState> {
this.setState({}); this.setState({});
}; };
private updateCurrentCursorPosition = (e: MouseEvent) => { private updateCurrentCursorPosition = (event: MouseEvent) => {
cursorX = e.x; cursorX = event.x;
cursorY = e.y; cursorY = event.y;
}; };
private onKeyDown = (event: KeyboardEvent) => { private onKeyDown = (event: KeyboardEvent) => {
@ -907,18 +907,18 @@ export class App extends React.Component<any, AppState> {
copyToAppClipboard(elements); copyToAppClipboard(elements);
}; };
private pasteFromClipboard = async (e: ClipboardEvent | null) => { private pasteFromClipboard = async (event: ClipboardEvent | null) => {
// #686 // #686
const target = document.activeElement; const target = document.activeElement;
const elementUnderCursor = document.elementFromPoint(cursorX, cursorY); const elementUnderCursor = document.elementFromPoint(cursorX, cursorY);
if ( if (
// if no ClipboardEvent supplied, assume we're pasting via contextMenu // if no ClipboardEvent supplied, assume we're pasting via contextMenu
// thus these checks don't make sense // thus these checks don't make sense
!e || !event ||
(elementUnderCursor instanceof HTMLCanvasElement && (elementUnderCursor instanceof HTMLCanvasElement &&
!isWritableElement(target)) !isWritableElement(target))
) { ) {
const data = await getClipboardContent(e); const data = await getClipboardContent(event);
if (data.elements) { if (data.elements) {
this.addElementsFromPaste(data.elements); this.addElementsFromPaste(data.elements);
} else if (data.text) { } else if (data.text) {
@ -950,7 +950,7 @@ export class App extends React.Component<any, AppState> {
history.resumeRecording(); history.resumeRecording();
} }
this.selectShapeTool("selection"); this.selectShapeTool("selection");
e?.preventDefault(); event?.preventDefault();
} }
}; };
@ -976,8 +976,10 @@ export class App extends React.Component<any, AppState> {
this.setState({}); this.setState({});
}; };
removePointer = (e: React.PointerEvent<HTMLElement>) => { removePointer = (event: React.PointerEvent<HTMLElement>) => {
gesture.pointers = gesture.pointers.filter(p => p.id !== e.pointerId); gesture.pointers = gesture.pointers.filter(
pointer => pointer.id !== event.pointerId,
);
}; };
public render() { public render() {
@ -1026,11 +1028,11 @@ export class App extends React.Component<any, AppState> {
this.canvas?.removeEventListener("wheel", this.handleWheel); this.canvas?.removeEventListener("wheel", this.handleWheel);
} }
}} }}
onContextMenu={e => { onContextMenu={event => {
e.preventDefault(); event.preventDefault();
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -1052,8 +1054,8 @@ export class App extends React.Component<any, AppState> {
this.canvasOnlyActions.includes(action), this.canvasOnlyActions.includes(action),
), ),
], ],
top: e.clientY, top: event.clientY,
left: e.clientX, left: event.clientX,
}); });
return; return;
} }
@ -1078,38 +1080,38 @@ export class App extends React.Component<any, AppState> {
action => !this.canvasOnlyActions.includes(action), action => !this.canvasOnlyActions.includes(action),
), ),
], ],
top: e.clientY, top: event.clientY,
left: e.clientX, left: event.clientX,
}); });
}} }}
onPointerDown={e => { onPointerDown={event => {
if (lastPointerUp !== null) { if (lastPointerUp !== null) {
// Unfortunately, sometimes we don't get a pointerup after a pointerdown, // Unfortunately, sometimes we don't get a pointerup after a pointerdown,
// this can happen when a contextual menu or alert is triggered. In order to avoid // this can happen when a contextual menu or alert is triggered. In order to avoid
// being in a weird state, we clean up on the next pointerdown // being in a weird state, we clean up on the next pointerdown
lastPointerUp(e); lastPointerUp(event);
} }
if (isPanning) { if (isPanning) {
return; return;
} }
this.setState({ lastPointerDownWith: e.pointerType }); this.setState({ lastPointerDownWith: event.pointerType });
// pan canvas on wheel button drag or space+drag // pan canvas on wheel button drag or space+drag
if ( if (
gesture.pointers.length === 0 && gesture.pointers.length === 0 &&
(e.button === POINTER_BUTTON.WHEEL || (event.button === POINTER_BUTTON.WHEEL ||
(e.button === POINTER_BUTTON.MAIN && isHoldingSpace)) (event.button === POINTER_BUTTON.MAIN && isHoldingSpace))
) { ) {
isPanning = true; isPanning = true;
document.documentElement.style.cursor = CURSOR_TYPE.GRABBING; document.documentElement.style.cursor = CURSOR_TYPE.GRABBING;
let { clientX: lastX, clientY: lastY } = e; let { clientX: lastX, clientY: lastY } = event;
const onPointerMove = (e: PointerEvent) => { const onPointerMove = (event: PointerEvent) => {
const deltaX = lastX - e.clientX; const deltaX = lastX - event.clientX;
const deltaY = lastY - e.clientY; const deltaY = lastY - event.clientY;
lastX = e.clientX; lastX = event.clientX;
lastY = e.clientY; lastY = event.clientY;
this.setState({ this.setState({
scrollX: normalizeScroll( scrollX: normalizeScroll(
@ -1140,16 +1142,16 @@ export class App extends React.Component<any, AppState> {
// only handle left mouse button or touch // only handle left mouse button or touch
if ( if (
e.button !== POINTER_BUTTON.MAIN && event.button !== POINTER_BUTTON.MAIN &&
e.button !== POINTER_BUTTON.TOUCH event.button !== POINTER_BUTTON.TOUCH
) { ) {
return; return;
} }
gesture.pointers.push({ gesture.pointers.push({
id: e.pointerId, id: event.pointerId,
x: e.clientX, x: event.clientX,
y: e.clientY, y: event.clientY,
}); });
if (gesture.pointers.length === 2) { if (gesture.pointers.length === 2) {
gesture.lastCenter = getCenter(gesture.pointers); gesture.lastCenter = getCenter(gesture.pointers);
@ -1158,7 +1160,7 @@ export class App extends React.Component<any, AppState> {
} }
// fixes pointermove causing selection of UI texts #32 // fixes pointermove causing selection of UI texts #32
e.preventDefault(); event.preventDefault();
// Preventing the event above disables default behavior // Preventing the event above disables default behavior
// of defocusing potentially focused element, which is what we // of defocusing potentially focused element, which is what we
// want when clicking inside the canvas. // want when clicking inside the canvas.
@ -1177,15 +1179,15 @@ export class App extends React.Component<any, AppState> {
isOverVerticalScrollBar, isOverVerticalScrollBar,
} = isOverScrollBars( } = isOverScrollBars(
elements, elements,
e.clientX / window.devicePixelRatio, event.clientX / window.devicePixelRatio,
e.clientY / window.devicePixelRatio, event.clientY / window.devicePixelRatio,
canvasWidth / window.devicePixelRatio, canvasWidth / window.devicePixelRatio,
canvasHeight / window.devicePixelRatio, canvasHeight / window.devicePixelRatio,
this.state, this.state,
); );
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -1224,7 +1226,7 @@ export class App extends React.Component<any, AppState> {
elements, elements,
{ x, y }, { x, y },
this.state.zoom, this.state.zoom,
e.pointerType, event.pointerType,
); );
const selectedElements = getSelectedElements(elements); const selectedElements = getSelectedElements(elements);
@ -1248,7 +1250,7 @@ export class App extends React.Component<any, AppState> {
this.state.zoom, this.state.zoom,
); );
// clear selection if shift is not clicked // clear selection if shift is not clicked
if (!hitElement?.isSelected && !e.shiftKey) { if (!hitElement?.isSelected && !event.shiftKey) {
elements = clearSelection(elements); elements = clearSelection(elements);
} }
@ -1265,7 +1267,7 @@ export class App extends React.Component<any, AppState> {
} }
// We duplicate the selected element if alt is pressed on pointer down // We duplicate the selected element if alt is pressed on pointer down
if (e.altKey) { if (event.altKey) {
elements = [ elements = [
...elements.map(element => ({ ...elements.map(element => ({
...element, ...element,
@ -1294,9 +1296,9 @@ export class App extends React.Component<any, AppState> {
if (elementIsAddedToSelection) { if (elementIsAddedToSelection) {
element = hitElement!; element = hitElement!;
} }
let textX = e.clientX; let textX = event.clientX;
let textY = e.clientY; let textY = event.clientY;
if (!e.altKey) { if (!event.altKey) {
const snappedToCenterPosition = this.getTextWysiwygSnappedToCenterPosition( const snappedToCenterPosition = this.getTextWysiwygSnappedToCenterPosition(
x, x,
y, y,
@ -1394,8 +1396,8 @@ export class App extends React.Component<any, AppState> {
let lastY = y; let lastY = y;
if (isOverHorizontalScrollBar || isOverVerticalScrollBar) { if (isOverHorizontalScrollBar || isOverVerticalScrollBar) {
lastX = e.clientX; lastX = event.clientX;
lastY = e.clientY; lastY = event.clientY;
} }
let resizeArrowFn: let resizeArrowFn:
@ -1466,14 +1468,14 @@ export class App extends React.Component<any, AppState> {
} }
}; };
const onPointerMove = (e: PointerEvent) => { const onPointerMove = (event: PointerEvent) => {
const target = e.target; const target = event.target;
if (!(target instanceof HTMLElement)) { if (!(target instanceof HTMLElement)) {
return; return;
} }
if (isOverHorizontalScrollBar) { if (isOverHorizontalScrollBar) {
const x = e.clientX; const x = event.clientX;
const dx = x - lastX; const dx = x - lastX;
this.setState({ this.setState({
scrollX: normalizeScroll( scrollX: normalizeScroll(
@ -1485,7 +1487,7 @@ export class App extends React.Component<any, AppState> {
} }
if (isOverVerticalScrollBar) { if (isOverVerticalScrollBar) {
const y = e.clientY; const y = event.clientY;
const dy = y - lastY; const dy = y - lastY;
this.setState({ this.setState({
scrollY: normalizeScroll( scrollY: normalizeScroll(
@ -1506,7 +1508,7 @@ export class App extends React.Component<any, AppState> {
this.state.elementType === "line") this.state.elementType === "line")
) { ) {
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -1521,7 +1523,7 @@ export class App extends React.Component<any, AppState> {
const selectedElements = getSelectedElements(elements); const selectedElements = getSelectedElements(elements);
if (selectedElements.length === 1) { if (selectedElements.length === 1) {
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -1549,13 +1551,13 @@ export class App extends React.Component<any, AppState> {
deltaY, deltaY,
x, x,
y, y,
e.shiftKey, event.shiftKey,
); );
} else { } else {
element.width -= deltaX; element.width -= deltaX;
element.x += deltaX; element.x += deltaX;
if (e.shiftKey) { if (event.shiftKey) {
element.y += element.height - element.width; element.y += element.height - element.width;
element.height = element.width; element.height = element.width;
} else { } else {
@ -1581,11 +1583,11 @@ export class App extends React.Component<any, AppState> {
deltaY, deltaY,
x, x,
y, y,
e.shiftKey, event.shiftKey,
); );
} else { } else {
element.width += deltaX; element.width += deltaX;
if (e.shiftKey) { if (event.shiftKey) {
element.y += element.height - element.width; element.y += element.height - element.width;
element.height = element.width; element.height = element.width;
} else { } else {
@ -1611,12 +1613,12 @@ export class App extends React.Component<any, AppState> {
deltaY, deltaY,
x, x,
y, y,
e.shiftKey, event.shiftKey,
); );
} else { } else {
element.width -= deltaX; element.width -= deltaX;
element.x += deltaX; element.x += deltaX;
if (e.shiftKey) { if (event.shiftKey) {
element.height = element.width; element.height = element.width;
} else { } else {
element.height += deltaY; element.height += deltaY;
@ -1640,10 +1642,10 @@ export class App extends React.Component<any, AppState> {
deltaY, deltaY,
x, x,
y, y,
e.shiftKey, event.shiftKey,
); );
} else { } else {
if (e.shiftKey) { if (event.shiftKey) {
element.width += deltaX; element.width += deltaX;
element.height = element.width; element.height = element.width;
} else { } else {
@ -1748,7 +1750,7 @@ export class App extends React.Component<any, AppState> {
const selectedElements = getSelectedElements(elements); const selectedElements = getSelectedElements(elements);
if (selectedElements.length > 0) { if (selectedElements.length > 0) {
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -1772,7 +1774,7 @@ export class App extends React.Component<any, AppState> {
} }
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -1790,7 +1792,7 @@ export class App extends React.Component<any, AppState> {
let dx = x - draggingElement.x; let dx = x - draggingElement.x;
let dy = y - draggingElement.y; let dy = y - draggingElement.y;
if (e.shiftKey && points.length === 2) { if (event.shiftKey && points.length === 2) {
({ width: dx, height: dy } = getPerfectElementSize( ({ width: dx, height: dy } = getPerfectElementSize(
this.state.elementType, this.state.elementType,
dx, dx,
@ -1806,7 +1808,7 @@ export class App extends React.Component<any, AppState> {
pnt[1] = dy; pnt[1] = dy;
} }
} else { } else {
if (e.shiftKey) { if (event.shiftKey) {
({ width, height } = getPerfectElementSize( ({ width, height } = getPerfectElementSize(
this.state.elementType, this.state.elementType,
width, width,
@ -1828,7 +1830,7 @@ export class App extends React.Component<any, AppState> {
draggingElement.shape = null; draggingElement.shape = null;
if (this.state.elementType === "selection") { if (this.state.elementType === "selection") {
if (!e.shiftKey && isSomeElementSelected(elements)) { if (!event.shiftKey && isSomeElementSelected(elements)) {
elements = clearSelection(elements); elements = clearSelection(elements);
} }
const elementsWithinSelection = getElementsWithinSelection( const elementsWithinSelection = getElementsWithinSelection(
@ -1842,7 +1844,7 @@ export class App extends React.Component<any, AppState> {
this.setState({}); this.setState({});
}; };
const onPointerUp = (e: PointerEvent) => { const onPointerUp = (event: PointerEvent) => {
const { const {
draggingElement, draggingElement,
resizingElement, resizingElement,
@ -1869,7 +1871,7 @@ export class App extends React.Component<any, AppState> {
} }
if (!draggingOccurred && draggingElement && !multiElement) { if (!draggingOccurred && draggingElement && !multiElement) {
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -1940,7 +1942,7 @@ export class App extends React.Component<any, AppState> {
!draggingOccurred && !draggingOccurred &&
!elementIsAddedToSelection !elementIsAddedToSelection
) { ) {
if (e.shiftKey) { if (event.shiftKey) {
hitElement.isSelected = false; hitElement.isSelected = false;
} else { } else {
elements = clearSelection(elements); elements = clearSelection(elements);
@ -1984,11 +1986,11 @@ export class App extends React.Component<any, AppState> {
window.addEventListener("pointermove", onPointerMove); window.addEventListener("pointermove", onPointerMove);
window.addEventListener("pointerup", onPointerUp); window.addEventListener("pointerup", onPointerUp);
}} }}
onDoubleClick={e => { onDoubleClick={event => {
resetCursor(); resetCursor();
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -2021,8 +2023,8 @@ export class App extends React.Component<any, AppState> {
this.setState({ editingElement: element }); this.setState({ editingElement: element });
let textX = e.clientX; let textX = event.clientX;
let textY = e.clientY; let textY = event.clientY;
if (elementAtPosition && isTextElement(elementAtPosition)) { if (elementAtPosition && isTextElement(elementAtPosition)) {
elements = elements.filter( elements = elements.filter(
@ -2050,7 +2052,7 @@ export class App extends React.Component<any, AppState> {
// x and y will change after calling newTextElement function // x and y will change after calling newTextElement function
element.x = centerElementX; element.x = centerElementX;
element.y = centerElementY; element.y = centerElementY;
} else if (!e.altKey) { } else if (!event.altKey) {
const snappedToCenterPosition = this.getTextWysiwygSnappedToCenterPosition( const snappedToCenterPosition = this.getTextWysiwygSnappedToCenterPosition(
x, x,
y, y,
@ -2099,15 +2101,15 @@ export class App extends React.Component<any, AppState> {
}, },
}); });
}} }}
onPointerMove={e => { onPointerMove={event => {
gesture.pointers = gesture.pointers.map(p => gesture.pointers = gesture.pointers.map(pointer =>
p.id === e.pointerId pointer.id === event.pointerId
? { ? {
id: e.pointerId, id: event.pointerId,
x: e.clientX, x: event.clientX,
y: e.clientY, y: event.clientY,
} }
: p, : pointer,
); );
if (gesture.pointers.length === 2) { if (gesture.pointers.length === 2) {
@ -2135,10 +2137,10 @@ export class App extends React.Component<any, AppState> {
if (isHoldingSpace || isPanning) { if (isHoldingSpace || isPanning) {
return; return;
} }
const hasDeselectedButton = Boolean(e.buttons); const hasDeselectedButton = Boolean(event.buttons);
const { x, y } = viewportCoordsToSceneCoords( const { x, y } = viewportCoordsToSceneCoords(
e, event,
this.state, this.state,
this.canvas, this.canvas,
); );
@ -2168,7 +2170,7 @@ export class App extends React.Component<any, AppState> {
elements, elements,
{ x, y }, { x, y },
this.state.zoom, this.state.zoom,
e.pointerType, event.pointerType,
); );
if (resizeElement && resizeElement.resizeHandle) { if (resizeElement && resizeElement.resizeHandle) {
document.documentElement.style.cursor = getCursorForResizingElement( document.documentElement.style.cursor = getCursorForResizingElement(
@ -2187,14 +2189,14 @@ export class App extends React.Component<any, AppState> {
}} }}
onPointerUp={this.removePointer} onPointerUp={this.removePointer}
onPointerLeave={this.removePointer} onPointerLeave={this.removePointer}
onDrop={e => { onDrop={event => {
const file = e.dataTransfer.files[0]; const file = event.dataTransfer.files[0];
if (file?.type === "application/json") { if (file?.type === "application/json") {
loadFromBlob(file) loadFromBlob(file)
.then(({ elements, appState }) => .then(({ elements, appState }) =>
this.syncActionResult({ elements, appState }), this.syncActionResult({ elements, appState }),
) )
.catch(err => console.error(err)); .catch(error => console.error(error));
} }
}} }}
> >
@ -2205,11 +2207,11 @@ export class App extends React.Component<any, AppState> {
); );
} }
private handleWheel = (e: WheelEvent) => { private handleWheel = (event: WheelEvent) => {
e.preventDefault(); event.preventDefault();
const { deltaX, deltaY } = e; const { deltaX, deltaY } = event;
if (e[KEYS.META]) { if (event[KEYS.META]) {
const sign = Math.sign(deltaY); const sign = Math.sign(deltaY);
const MAX_STEP = 10; const MAX_STEP = 10;
let delta = Math.abs(deltaY); let delta = Math.abs(deltaY);
@ -2342,7 +2344,7 @@ class TopErrorBoundary extends React.Component<any, TopErrorBoundaryState> {
for (const [key, value] of Object.entries({ ...localStorage })) { for (const [key, value] of Object.entries({ ...localStorage })) {
try { try {
_localStorage[key] = JSON.parse(value); _localStorage[key] = JSON.parse(value);
} catch (err) { } catch (error) {
_localStorage[key] = value; _localStorage[key] = value;
} }
} }
@ -2366,8 +2368,8 @@ class TopErrorBoundary extends React.Component<any, TopErrorBoundaryState> {
try { try {
const StackTrace = await import("stacktrace-js"); const StackTrace = await import("stacktrace-js");
stack += (await StackTrace.fromError(error)).join("\n"); stack += (await StackTrace.fromError(error)).join("\n");
} catch (err) { } catch (error) {
console.error(err); console.error(error);
stack += error.stack || ""; stack += error.stack || "";
} }
} }

View File

@ -114,7 +114,7 @@ export async function loadFromBlob(blob: any) {
} }
elements = data.elements || []; elements = data.elements || [];
appState = { ...defaultAppState, ...data.appState }; appState = { ...defaultAppState, ...data.appState };
} catch (e) { } catch (error) {
// Do nothing because elements array is already empty // Do nothing because elements array is already empty
} }
return { elements, appState }; return { elements, appState };
@ -195,8 +195,8 @@ export async function exportToBackend(
} else { } else {
window.alert(t("alerts.couldNotCreateShareableLink")); window.alert(t("alerts.couldNotCreateShareableLink"));
} }
} catch (e) { } catch (error) {
console.error(e); console.error(error);
window.alert(t("alerts.couldNotCreateShareableLink")); window.alert(t("alerts.couldNotCreateShareableLink"));
} }
} }
@ -320,7 +320,7 @@ export async function exportCanvas(
} else if (type === "clipboard") { } else if (type === "clipboard") {
try { try {
copyCanvasToClipboardAsPng(tempCanvas); copyCanvasToClipboardAsPng(tempCanvas);
} catch (err) { } catch (error) {
window.alert(t("alerts.couldNotCopyToClipboard")); window.alert(t("alerts.couldNotCopyToClipboard"));
} }
} else if (type === "backend") { } else if (type === "backend") {
@ -418,7 +418,7 @@ export function restoreFromLocalStorage() {
elements = JSON.parse(savedElements).map( elements = JSON.parse(savedElements).map(
({ shape, ...element }: ExcalidrawElement) => element, ({ shape, ...element }: ExcalidrawElement) => element,
); );
} catch (e) { } catch (error) {
// Do nothing because elements array is already empty // Do nothing because elements array is already empty
} }
} }
@ -427,7 +427,7 @@ export function restoreFromLocalStorage() {
if (savedState) { if (savedState) {
try { try {
appState = JSON.parse(savedState) as AppState; appState = JSON.parse(savedState) as AppState;
} catch (e) { } catch (error) {
// Do nothing because appState is already null // Do nothing because appState is already null
} }
} }