aboutsummaryrefslogtreecommitdiff
path: root/build/js/tools/text.js
blob: 919df48b43227e60294062e4e9ac6955383ffbe2 (plain)
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
// Text tool: creates and edits editable text layers. Editing happens in an
// invisible <textarea> overlaid on the canvas while the layer renders live.
import { Tool } from './tool.js';
import { Layer, DEFAULT_TEXT, layoutText, textFont } from '../core/layer.js';

export const FONT_FAMILIES = [
  'Arial', 'Helvetica', 'Verdana', 'Tahoma', 'Trebuchet MS', 'Segoe UI', 'Georgia', 'Times New Roman',
  'Palatino Linotype', 'Garamond', 'Courier New', 'Consolas', 'Impact', 'Comic Sans MS', 'Brush Script MT',
  'system-ui', 'serif', 'sans-serif', 'monospace', 'cursive', 'fantasy',
];

const STYLE_KEYS = ['fontFamily', 'fontSize', 'bold', 'italic', 'underline', 'align', 'color', 'lineHeight', 'strokeWidth', 'strokeColor', 'shadow'];

export class TextTool extends Tool {
  static id = 'text';
  static label = 'Text';
  static icon = 'text';
  static shortcut = 'T';
  static schema = [
    { key: 'fontFamily', label: 'Font', type: 'font', default: 'Arial', options: FONT_FAMILIES },
    { key: 'fontSize', label: 'Size', type: 'number', min: 1, max: 2000, default: 48, unit: 'px' },
    { key: 'bold', label: 'B', title: 'Bold', type: 'toggle', default: false, style: 'font-weight:bold' },
    { key: 'italic', label: 'I', title: 'Italic', type: 'toggle', default: false, style: 'font-style:italic' },
    { key: 'underline', label: 'U', title: 'Underline', type: 'toggle', default: false, style: 'text-decoration:underline' },
    {
      key: 'align', label: '', type: 'buttons', default: 'left', options: [
        { value: 'left', icon: 'alignLeft', title: 'Align left' },
        { value: 'center', icon: 'alignCenter', title: 'Center' },
        { value: 'right', icon: 'alignRight', title: 'Align right' },
      ],
    },
    { key: 'color', label: 'Color', type: 'color', default: '#000000' },
    { key: 'lineHeight', label: 'Leading', type: 'number', min: 0.5, max: 4, step: 0.05, default: 1.2 },
    { key: 'strokeWidth', label: 'Outline', type: 'number', min: 0, max: 100, default: 0, unit: 'px' },
    { key: 'strokeColor', label: '', type: 'color', default: '#ffffff' },
    { key: 'shadow', label: 'Shadow', type: 'checkbox', default: false },
  ];
  get cursor() { return 'text'; }
  get hint() {
    return this.session ? 'Typing… Esc or Ctrl+Enter to finish · click elsewhere to commit' : 'Click to add text · click existing text to edit';
  }

  activate() {
    this.syncFromLayer();
    this._offLayer = this.app.on('activeLayer', () => { if (!this.session) this.syncFromLayer(); });
  }
  deactivate() {
    this.commit();
    this._offLayer?.();
  }

  /** Load style options from the active text layer so the bar reflects it. */
  syncFromLayer() {
    const l = this.doc?.activeLayer;
    if (!l?.isText) return;
    for (const k of STYLE_KEYS) this.options[k] = l.text[k];
    this.app.ui?.toolOptions.refresh();
  }

  onOptionChange(key, value) {
    const doc = this.doc;
    const layer = this.session?.layer || (doc?.activeLayer?.isText ? doc.activeLayer : null);
    if (!layer || !STYLE_KEYS.includes(key)) return;
    if (this.session) {
      layer.text[key] = value;
      layer.renderText();
      doc.markDirty();
      this.positionEditor();
    } else {
      doc.change('Text style', () => {
        layer.text[key] = value;
        layer.renderText();
      }, { coalesceKey: `text-style-${layer.id}-${key}` });
    }
  }

  textLayerAt(p) {
    const layers = this.doc.layers;
    const active = this.doc.activeLayer;
    const order = [active, ...[...layers].reverse().filter((l) => l !== active)];
    for (const l of order) {
      if (!l?.isText || !l.visible || l.locked) continue;
      const b = layoutText(l.text);
      const pad = 4 / this.doc.view.zoom;
      if (p.x >= b.x - pad && p.y >= b.y - pad && p.x <= b.x + b.w + pad && p.y <= b.y + b.h + pad) return l;
    }
    return null;
  }

  onPointerDown(e, p) {
    if (this.session) {
      this.commit();
      return;
    }
    const hit = this.textLayerAt(p);
    if (hit) { this.editLayer(hit); return; }
    this.createAt(p);
  }

  createAt(p) {
    const doc = this.doc;
    const before = doc.captureState();
    const o = this.options;
    const layer = new Layer(doc.width, doc.height, { name: 'Text', type: 'text' });
    layer.text = { ...DEFAULT_TEXT };
    for (const k of STYLE_KEYS) layer.text[k] = o[k];
    layer.text.content = '';
    const lh = o.fontSize * o.lineHeight;
    layer.text.x = Math.round(p.x);
    layer.text.y = Math.round(p.y - lh / 2);
    const idx = doc.activeIndex + 1;
    doc.layers.splice(idx, 0, layer);
    doc.activeLayerId = layer.id;
    doc.editMask = false;
    layer.renderText();
    doc.markDirty(true);
    this.editLayer(layer, { isNew: true, before });
  }

  editLayer(layer, { isNew = false, before = null } = {}) {
    this.commit();
    const doc = this.doc;
    if (doc.activeLayerId !== layer.id) doc.setActiveLayer(layer.id);
    this.session = {
      layer, isNew, before: before || doc.captureState(), originalText: JSON.stringify(layer.text),
    };
    this.syncFromLayer();
    const ta = document.createElement('textarea');
    ta.className = 'text-editor';
    ta.spellcheck = false;
    ta.wrap = 'off';
    ta.value = layer.text.content;
    ta.addEventListener('input', () => {
      layer.text.content = ta.value;
      layer.renderText();
      doc.markDirty();
      this.positionEditor();
    });
    ta.addEventListener('keydown', (ev) => {
      ev.stopPropagation();
      if (ev.key === 'Escape' || (ev.key === 'Enter' && (ev.ctrlKey || ev.metaKey))) {
        ev.preventDefault();
        this.commit();
      }
    });
    ta.addEventListener('pointerdown', (ev) => ev.stopPropagation());
    this.app.renderer.container.appendChild(ta);
    this.session.ta = ta;
    this.positionEditor();
    ta.focus();
    if (!isNew) ta.select();
    this.app.renderer.request();
    this.app.emit('toolHint');
  }

  positionEditor() {
    const s = this.session;
    if (!s?.ta) return;
    const t = s.layer.text;
    const view = this.app.renderer;
    const zoom = this.doc.view.zoom;
    const box = layoutText(t);
    const tl = view.docToScreen({ x: box.x, y: box.y });
    const st = s.ta.style;
    st.left = `${tl.x}px`;
    st.top = `${tl.y}px`;
    st.width = `${Math.max(box.w * zoom + t.fontSize * zoom * 0.6, 40)}px`;
    st.height = `${box.h * zoom + 4}px`;
    st.font = textFont(t, zoom);
    st.lineHeight = `${t.fontSize * t.lineHeight * zoom}px`;
    st.textAlign = t.align;
  }

  commit() {
    const s = this.session;
    if (!s) return;
    this.session = null;
    s.ta.remove();
    const doc = this.doc;
    const layer = s.layer;
    if (!doc.layers.includes(layer)) return; // document changed under us
    if (!layer.text.content.trim()) {
      doc.layers = doc.layers.filter((l) => l !== layer);
      if (doc.activeLayerId === layer.id) doc.activeLayerId = doc.layers[Math.max(0, doc.layers.length - 1)]?.id;
      if (s.isNew) doc.restoreState(s.before);
      else doc.commitChange('Delete text', s.before);
    } else if (s.isNew) {
      layer.name = layer.text.content.split('\n')[0].slice(0, 24) || 'Text';
      doc.commitChange('Add text', s.before);
    } else if (JSON.stringify(layer.text) !== s.originalText) {
      doc.commitChange('Edit text', s.before);
    }
    doc.markDirty(true);
    this.app.renderer.container.focus?.();
    this.app.emit('toolHint');
  }

  cancel() {
    const s = this.session;
    if (!s) return;
    this.session = null;
    s.ta.remove();
    this.doc.restoreState(s.before);
  }

  drawOverlay(ctx, view, doc) {
    if (this.session) this.positionEditor();
    const layer = this.session?.layer || (doc.activeLayer?.isText ? doc.activeLayer : null);
    if (!layer) return;
    const b = layoutText(layer.text);
    view.outlineRect({ x: b.x - 2, y: b.y - 2, w: b.w + 4, h: b.h + 4 }, doc);
  }
}