summaryrefslogtreecommitdiffstats
path: root/packages/excalidraw/components/Stats/DragInput.tsx
blob: 82d6419c0b06c6d713a16ff746d761e2ed92fdc8 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
import { useEffect, useRef, useState } from "react";
import { EVENT } from "../../constants";
import { KEYS } from "../../keys";
import type { ElementsMap, ExcalidrawElement } from "../../element/types";
import { deepCopyElement } from "../../element/newElement";
import clsx from "clsx";
import { useApp } from "../App";
import { InlineIcon } from "../InlineIcon";
import type { StatsInputProperty } from "./utils";
import { SMALLEST_DELTA } from "./utils";
import { CaptureUpdateAction } from "../../store";
import type Scene from "../../scene/Scene";

import "./DragInput.scss";
import type { AppState } from "../../types";
import { cloneJSON } from "../../utils";

export type DragInputCallbackType<
  P extends StatsInputProperty,
  E = ExcalidrawElement,
> = (props: {
  accumulatedChange: number;
  instantChange: number;
  originalElements: readonly E[];
  originalElementsMap: ElementsMap;
  shouldKeepAspectRatio: boolean;
  shouldChangeByStepSize: boolean;
  scene: Scene;
  nextValue?: number;
  property: P;
  originalAppState: AppState;
  setInputValue: (value: number) => void;
}) => void;

interface StatsDragInputProps<
  T extends StatsInputProperty,
  E = ExcalidrawElement,
> {
  label: string | React.ReactNode;
  icon?: React.ReactNode;
  value: number | "Mixed";
  elements: readonly E[];
  editable?: boolean;
  shouldKeepAspectRatio?: boolean;
  dragInputCallback: DragInputCallbackType<T, E>;
  property: T;
  scene: Scene;
  appState: AppState;
  /** how many px you need to drag to get 1 unit change */
  sensitivity?: number;
}

const StatsDragInput = <
  T extends StatsInputProperty,
  E extends ExcalidrawElement = ExcalidrawElement,
>({
  label,
  icon,
  dragInputCallback,
  value,
  elements,
  editable = true,
  shouldKeepAspectRatio,
  property,
  scene,
  appState,
  sensitivity = 1,
}: StatsDragInputProps<T, E>) => {
  const app = useApp();
  const inputRef = useRef<HTMLInputElement>(null);
  const labelRef = useRef<HTMLDivElement>(null);

  const [inputValue, setInputValue] = useState(value.toString());

  const stateRef = useRef<{
    originalAppState: AppState;
    originalElements: readonly E[];
    lastUpdatedValue: string;
    updatePending: boolean;
  }>(null!);
  if (!stateRef.current) {
    stateRef.current = {
      originalAppState: cloneJSON(appState),
      originalElements: elements,
      lastUpdatedValue: inputValue,
      updatePending: false,
    };
  }

  useEffect(() => {
    const inputValue = value.toString();
    setInputValue(inputValue);
    stateRef.current.lastUpdatedValue = inputValue;
  }, [value]);

  const handleInputValue = (
    updatedValue: string,
    elements: readonly E[],
    appState: AppState,
  ) => {
    if (!stateRef.current.updatePending) {
      return false;
    }
    stateRef.current.updatePending = false;

    const parsed = Number(updatedValue);
    if (isNaN(parsed)) {
      setInputValue(value.toString());
      return;
    }

    const rounded = Number(parsed.toFixed(2));
    const original = Number(value);

    // only update when
    // 1. original was "Mixed" and we have a new value
    // 2. original was not "Mixed" and the difference between a new value and previous value is greater
    //    than the smallest delta allowed, which is 0.01
    // reason: idempotent to avoid unnecessary
    if (isNaN(original) || Math.abs(rounded - original) >= SMALLEST_DELTA) {
      stateRef.current.lastUpdatedValue = updatedValue;
      dragInputCallback({
        accumulatedChange: 0,
        instantChange: 0,
        originalElements: elements,
        originalElementsMap: app.scene.getNonDeletedElementsMap(),
        shouldKeepAspectRatio: shouldKeepAspectRatio!!,
        shouldChangeByStepSize: false,
        scene,
        nextValue: rounded,
        property,
        originalAppState: appState,
        setInputValue: (value) => setInputValue(String(value)),
      });
      app.syncActionResult({
        captureUpdate: CaptureUpdateAction.IMMEDIATELY,
      });
    }
  };

  const callbacksRef = useRef<
    Partial<{
      handleInputValue: typeof handleInputValue;
      onPointerUp: (event: PointerEvent) => void;
      onPointerMove: (event: PointerEvent) => void;
    }>
  >({});
  callbacksRef.current.handleInputValue = handleInputValue;

  // make sure that clicking on canvas (which umounts the component)
  // updates current input value (blur isn't triggered)
  useEffect(() => {
    const input = inputRef.current;
    const callbacks = callbacksRef.current;
    return () => {
      const nextValue = input?.value;
      if (nextValue) {
        callbacks.handleInputValue?.(
          nextValue,
          stateRef.current.originalElements,
          stateRef.current.originalAppState,
        );
      }

      // generally not needed, but in case `pointerup` doesn't fire and
      // we don't remove the listeners that way, we should at least remove
      // on unmount
      window.removeEventListener(
        EVENT.POINTER_MOVE,
        callbacks.onPointerMove!,
        false,
      );
      window.removeEventListener(
        EVENT.POINTER_UP,
        callbacks.onPointerUp!,
        false,
      );
    };
  }, [
    // we need to track change of `editable` state as mount/unmount
    // because react doesn't trigger `blur` when a an input is blurred due
    // to being disabled (https://github.com/facebook/react/issues/9142).
    // As such, if we keep rendering disabled inputs, then change in selection
    // to an element that has a given property as non-editable would not trigger
    // blur/unmount and wouldn't update the value.
    editable,
  ]);

  if (!editable) {
    return null;
  }

  return (
    <div
      className={clsx("drag-input-container", !editable && "disabled")}
      data-testid={label}
    >
      <div
        className="drag-input-label"
        ref={labelRef}
        onPointerDown={(event) => {
          if (inputRef.current && editable) {
            document.body.classList.add("excalidraw-cursor-resize");

            let startValue = Number(inputRef.current.value);
            if (isNaN(startValue)) {
              startValue = 0;
            }

            let lastPointer: {
              x: number;
              y: number;
            } | null = null;

            let originalElementsMap: Map<string, ExcalidrawElement> | null =
              app.scene
                .getNonDeletedElements()
                .reduce((acc: ElementsMap, element) => {
                  acc.set(element.id, deepCopyElement(element));
                  return acc;
                }, new Map());

            let originalElements: readonly E[] | null = elements.map(
              (element) => originalElementsMap!.get(element.id) as E,
            );

            const originalAppState: AppState = cloneJSON(appState);

            let accumulatedChange = 0;
            let stepChange = 0;

            const onPointerMove = (event: PointerEvent) => {
              if (
                lastPointer &&
                originalElementsMap !== null &&
                originalElements !== null
              ) {
                const instantChange = event.clientX - lastPointer.x;

                if (instantChange !== 0) {
                  stepChange += instantChange;

                  if (Math.abs(stepChange) >= sensitivity) {
                    stepChange =
                      Math.sign(stepChange) *
                      Math.floor(Math.abs(stepChange) / sensitivity);

                    accumulatedChange += stepChange;

                    dragInputCallback({
                      accumulatedChange,
                      instantChange: stepChange,
                      originalElements,
                      originalElementsMap,
                      shouldKeepAspectRatio: shouldKeepAspectRatio!!,
                      shouldChangeByStepSize: event.shiftKey,
                      property,
                      scene,
                      originalAppState,
                      setInputValue: (value) => setInputValue(String(value)),
                    });

                    stepChange = 0;
                  }
                }
              }

              lastPointer = {
                x: event.clientX,
                y: event.clientY,
              };
            };

            const onPointerUp = () => {
              window.removeEventListener(
                EVENT.POINTER_MOVE,
                onPointerMove,
                false,
              );

              app.syncActionResult({
                captureUpdate: CaptureUpdateAction.IMMEDIATELY,
              });

              lastPointer = null;
              accumulatedChange = 0;
              stepChange = 0;
              originalElements = null;
              originalElementsMap = null;

              document.body.classList.remove("excalidraw-cursor-resize");

              window.removeEventListener(EVENT.POINTER_UP, onPointerUp, false);
            };

            callbacksRef.current.onPointerMove = onPointerMove;
            callbacksRef.current.onPointerUp = onPointerUp;

            window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, false);
            window.addEventListener(EVENT.POINTER_UP, onPointerUp, false);
          }
        }}
        onPointerEnter={() => {
          if (labelRef.current) {
            labelRef.current.style.cursor = "ew-resize";
          }
        }}
      >
        {icon ? <InlineIcon icon={icon} /> : label}
      </div>
      <input
        className="drag-input"
        autoComplete="off"
        spellCheck="false"
        onKeyDown={(event) => {
          if (editable) {
            const eventTarget = event.target;
            if (
              eventTarget instanceof HTMLInputElement &&
              event.key === KEYS.ENTER
            ) {
              handleInputValue(eventTarget.value, elements, appState);
              app.focusContainer();
            }
          }
        }}
        ref={inputRef}
        value={inputValue}
        onChange={(event) => {
          stateRef.current.updatePending = true;
          setInputValue(event.target.value);
        }}
        onFocus={(event) => {
          event.target.select();
          stateRef.current.originalElements = elements;
          stateRef.current.originalAppState = cloneJSON(appState);
        }}
        onBlur={(event) => {
          if (!inputValue) {
            setInputValue(value.toString());
          } else if (editable) {
            handleInputValue(
              event.target.value,
              stateRef.current.originalElements,
              stateRef.current.originalAppState,
            );
          }
        }}
        disabled={!editable}
      />
    </div>
  );
};

export default StatsDragInput;