File size: 2,327 Bytes
b456468
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import commandFactory from '@/factory/command';
import { componentNames, commandNames, rejectMessages } from '@/consts';
import {
  setCachedUndoDataForDimension,
  makeSelectionUndoData,
  makeSelectionUndoDatum,
} from '@/helper/selectionModifyHelper';

const { TEXT } = componentNames;

const command = {
  name: commandNames.ADD_TEXT,

  /**
   * Add a text object
   * @param {Graphics} graphics - Graphics instance
   * @param {string} text - Initial input text
   * @param {Object} [options] Options for text styles
   *     @param {Object} [options.styles] Initial styles
   *         @param {string} [options.styles.fill] Color
   *         @param {string} [options.styles.fontFamily] Font type for text
   *         @param {number} [options.styles.fontSize] Size
   *         @param {string} [options.styles.fontStyle] Type of inclination (normal / italic)
   *         @param {string} [options.styles.fontWeight] Type of thicker or thinner looking (normal / bold)
   *         @param {string} [options.styles.textAlign] Type of text align (left / center / right)
   *         @param {string} [options.styles.textDecoration] Type of line (underline / line-through / overline)
   *     @param {{x: number, y: number}} [options.position] - Initial position
   * @returns {Promise}
   */
  execute(graphics, text, options) {
    const textComp = graphics.getComponent(TEXT);

    if (this.undoData.object) {
      const undoObject = this.undoData.object;

      return new Promise((resolve, reject) => {
        if (!graphics.contains(undoObject)) {
          graphics.add(undoObject);
          resolve(undoObject);
        } else {
          reject(rejectMessages.redo);
        }
      });
    }

    return textComp.add(text, options).then((objectProps) => {
      const { id } = objectProps;
      const textObject = graphics.getObject(id);

      this.undoData.object = textObject;

      setCachedUndoDataForDimension(
        makeSelectionUndoData(textObject, () => makeSelectionUndoDatum(id, textObject, false))
      );

      return objectProps;
    });
  },

  /**
   * @param {Graphics} graphics - Graphics instance
   * @returns {Promise}
   */
  undo(graphics) {
    graphics.remove(this.undoData.object);

    return Promise.resolve();
  },
};

commandFactory.register(command);

export default command;