summaryrefslogtreecommitdiffstats
path: root/src/Text.js
blob: 3d9f074bc89f927ba484763c91e2184a2cb4197e (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
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
import Parent from './Parent.js'
import SVGNumber from './SVGNumber.js'
import {nodeOrNew, adopt} from './tools.js'
import {attrs} from './defaults.js'

export default class Text extends Parent {
  // Initialize node
  constructor (node) {
    super(nodeOrNew('text', node))

    this.dom.leading = new SVGNumber(1.3)    // store leading value for rebuilding
    this._rebuild = true                      // enable automatic updating of dy values
    this._build = false                       // disable build mode for adding multiple lines

    // set default font
    this.attr('font-family', attrs['font-family'])
  }

  // Move over x-axis
  x (x) {
    // act as getter
    if (x == null) {
      return this.attr('x')
    }

    return this.attr('x', x)
  }

  // Move over y-axis
  y (y) {
    var oy = this.attr('y')
    var o = typeof oy === 'number' ? oy - this.bbox().y : 0

    // act as getter
    if (y == null) {
      return typeof oy === 'number' ? oy - o : oy
    }

    return this.attr('y', typeof y === 'number' ? y + o : y)
  }

  // Move center over x-axis
  cx (x) {
    return x == null ? this.bbox().cx : this.x(x - this.bbox().width / 2)
  }

  // Move center over y-axis
  cy (y) {
    return y == null ? this.bbox().cy : this.y(y - this.bbox().height / 2)
  }

  // Set the text content
  text (text) {
    // act as getter
    if (text === undefined) {
      var children = this.node.childNodes
      var firstLine = 0
      text = ''

      for (var i = 0, len = children.length; i < len; ++i) {
        // skip textPaths - they are no lines
        if (children[i].nodeName === 'textPath') {
          if (i === 0) firstLine = 1
          continue
        }

        // add newline if its not the first child and newLined is set to true
        if (i !== firstLine && children[i].nodeType !== 3 && adopt(children[i]).dom.newLined === true) {
          text += '\n'
        }

        // add content of this node
        text += children[i].textContent
      }

      return text
    }

    // remove existing content
    this.clear().build(true)

    if (typeof text === 'function') {
      // call block
      text.call(this, this)
    } else {
      // store text and make sure text is not blank
      text = text.split('\n')

      // build new lines
      for (var j = 0, jl = text.length; j < jl; j++) {
        this.tspan(text[j]).newLine()
      }
    }

    // disable build mode and rebuild lines
    return this.build(false).rebuild()
  }

  // Set / get leading
  leading (value) {
    // act as getter
    if (value == null) {
      return this.dom.leading
    }

    // act as setter
    this.dom.leading = new SVGNumber(value)

    return this.rebuild()
  }

  // Rebuild appearance type
  rebuild (rebuild) {
    // store new rebuild flag if given
    if (typeof rebuild === 'boolean') {
      this._rebuild = rebuild
    }

    // define position of all lines
    if (this._rebuild) {
      var self = this
      var blankLineOffset = 0
      var dy = this.dom.leading * new SVGNumber(this.attr('font-size'))

      this.each(function () {
        if (this.dom.newLined) {
          this.attr('x', self.attr('x'))

          if (this.text() === '\n') {
            blankLineOffset += dy
          } else {
            this.attr('dy', dy + blankLineOffset)
            blankLineOffset = 0
          }
        }
      })

      this.fire('rebuild')
    }

    return this
  }

  // Enable / disable build mode
  build (build) {
    this._build = !!build
    return this
  }

  // overwrite method from parent to set data properly
  setData (o) {
    this.dom = o
    this.dom.leading = new SVGNumber(o.leading || 1.3)
    return this
  }
}


addFactory(Parent, {
  // Create text element
  text (text) {
    return this.put(new Text()).text(text)
  },

  // Create plain text element
  plain (text) {
    return this.put(new Text()).plain(text)
  }
})


class Tspan extends Parent {
  // Initialize node
  constructor (node) {
    super(nodeOrNew('tspan', node))
  }

  // Set text content
  text (text) {
    if (text == null) return this.node.textContent + (this.dom.newLined ? '\n' : '')

    typeof text === 'function' ? text.call(this, this) : this.plain(text)

    return this
  }

  // Shortcut dx
  dx (dx) {
    return this.attr('dx', dx)
  }

  // Shortcut dy
  dy (dy) {
    return this.attr('dy', dy)
  }

  // Create new line
  newLine () {
    // fetch text parent
    var t = this.parent(Text)

    // mark new line
    this.dom.newLined = true

    // apply new position
    return this.dy(t.dom.leading * t.attr('font-size')).attr('x', t.x())
  }
}

extend([Text, Tspan], {
  // Create plain text node
  plain: function (text) {
    // clear if build mode is disabled
    if (this._build === false) {
      this.clear()
    }

    // create text node
    this.node.appendChild(document.createTextNode(text))

    return this
  },

  // Create a tspan
  tspan: function (text) {
    var tspan = new Tspan()

    // clear if build mode is disabled
    if (!this._build) {
      this.clear()
    }

    // add new tspan
    this.node.appendChild(tspan.node)

    return tspan.text(text)
  },

  // FIXME: Does this also work for textpath?
  // Get length of text element
  length: function () {
    return this.node.getComputedTextLength()
  }
})