/
StyledText.coffee
362 lines (308 loc) · 9.42 KB
/
StyledText.coffee
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
356
357
358
359
360
361
362
_measureElement = null
getMeasureElement = (constraints={}) ->
shouldCreateElement = not _measureElement
if shouldCreateElement
_measureElement = document.createElement("div")
_measureElement.id = "_measureElement"
_measureElement.style.position = "fixed"
_measureElement.style.visibility = "hidden"
_measureElement.style.top = "-10000px"
_measureElement.style.left = "-10000px"
while _measureElement.hasChildNodes()
_measureElement.removeChild(_measureElement.lastChild)
_measureElement.style.width = "10000px"
if constraints.max
_measureElement.style.maxWidth = "#{constraints.width}px" if constraints.width
_measureElement.style.maxHeight = "#{constraints.height}px" if constraints.height
else
_measureElement.style.width = "#{constraints.width}px" if constraints.width
_measureElement.style.height = "#{constraints.height}px" if constraints.height
# This is a trick to call this function before the document ready event
if not window.document.body
document.write(_measureElement.outerHTML)
_textSizeNode = document.getElementById("_measureElement")
else
window.document.body.appendChild(_measureElement)
return _measureElement
class InlineStyle
startIndex: 0
endIndex: 0
css: null
text: ""
element: null
constructor: (configuration, text) ->
if _.isString configuration
@text = configuration
@startIndex = 0
@endIndex = @text.length
@css = text
else
@startIndex = configuration.startIndex
@endIndex = configuration.endIndex
@css = configuration.css
@text = text.substring(@startIndex, @endIndex)
getOptions: ->
startIndex: @startIndex
endIndex: @endIndex
css: _.clone(@css)
createElement: ->
span = document.createElement "span"
for prop, value of @css
span.style[prop] = value
if @text is ""
span.innerHTML = "<br/>"
else
span.textContent = @text
return span
setText: (text) ->
@text = text
@endIndex = @startIndex + text.length
resetStyle: (style) ->
delete @css[style]
if style is "color"
delete @css["WebkitTextFillColor"]
setStyle: (style, value) ->
@css[style] = value
@element?.style[style] = value
getStyle: (style) ->
if style is "color"
return @css["color"] ? @css["WebkitTextFillColor"]
return @css[style]
measure: ->
rect = @element.getBoundingClientRect()
size =
width: rect.right - rect.left
height: rect.bottom - rect.top
return size
replaceText: (search, replace) ->
regex = null
if _.isString search
regex = new RegExp(search, 'g')
else if search instanceof RegExp
regex = search
if regex?
@text = @text.replace(regex, replace)
@endIndex = @startIndex + @text.length
validate: ->
return @startIndex isnt @endIndex and @endIndex is (@startIndex + @text.length)
class StyledTextBlock
text: ""
inlineStyles: []
element: null
constructor: (configuration) ->
text = configuration.text
@text = text
if configuration.inlineStyles?
@inlineStyles = configuration.inlineStyles.map((i) -> new InlineStyle(i, text))
else if configuration.css?
inlineStyle = new InlineStyle @text, configuration.css
@inlineStyles = [inlineStyle]
else
throw new Error("Should specify inlineStyles or css")
getOptions: ->
text: @text
inlineStyles: @inlineStyles.map((i) -> i.getOptions())
createElement: ->
div = document.createElement "div"
div.style.fontSize = "1px"
for style in @inlineStyles
span = style.createElement()
style.element = span
div.appendChild span
return div
measure: ->
totalWidth = 0
for style in @inlineStyles
totalWidth += style.measure().width
rect = @element.getBoundingClientRect()
size =
width: totalWidth
height: rect.bottom - rect.top
return size
clone: ->
new StyledTextBlock
text: ""
css: _.first(@inlineStyles).css
setText: (text) ->
@text = text
firstStyle = _.first(@inlineStyles)
firstStyle.setText(text)
@inlineStyles = [firstStyle]
setTextOverflow: (textOverflow, maxLines=1) ->
if textOverflow in ["ellipsis", "clip"]
@setStyle("overflow", "hidden")
multiLineOverflow = textOverflow is "ellipsis"
if multiLineOverflow
@setStyle("WebkitLineClamp", maxLines)
@setStyle("WebkitBoxOrient", "vertical")
@setStyle("display", "-webkit-box")
else
@resetStyle("WebkitLineClamp")
@resetStyle("WebkitBoxOrient")
@setStyle("display", "block")
@setStyle("whiteSpace", "nowrap")
@setStyle("textOverflow", textOverflow)
else
@resetStyle("whiteSpace")
@resetStyle("textOverflow")
@resetStyle("display")
@resetStyle("overflow")
@resetStyle("WebkitLineClamp")
@resetStyle("WebkitBoxOrient")
resetStyle: (style) ->
@inlineStyles.map (inlineStyle) -> inlineStyle.resetStyle(style)
setStyle: (style, value) ->
@inlineStyles.map (inlineStyle) -> inlineStyle.setStyle(style, value)
getStyle: (style) ->
_.first(@inlineStyles).getStyle(style)
getFonts: ->
fonts = []
for style in @inlineStyles
font = style.getStyle("fontFamily")
if font?
fonts.push(font)
return fonts
replaceText: (search, replace) ->
currentIndex = 0
for style in @inlineStyles
style.startIndex = currentIndex
style.replaceText(search, replace)
currentIndex = style.endIndex
newText = @inlineStyles.map((i) -> i.text).join('')
@text = newText
return newText isnt @text
validate: ->
combinedText = ''
currentIndex = 0
for style in @inlineStyles
return false if not (currentIndex is style.startIndex)
return false if not style.validate()
currentIndex = style.endIndex
combinedText += style.text
return @text is combinedText
class exports.StyledText
blocks: null
textAlign: null
element: null
autoWidth: false
autoHeight: false
textOverflow: null
@defaultStyles =
fontStyle: "normal"
fontVariantCaps: "normal"
fontWeight: "normal"
fontSize: "16px"
lineHeight: "normal"
fontFamily: "-apple-system, BlinkMacSystemFont"
outline: "none"
whiteSpace: "pre-wrap"
wordWrap: "break-word"
constructor: (configuration) ->
@textAlign = configuration?.alignment ? "left"
if configuration?.blocks?
@blocks = configuration.blocks.map((b) -> new StyledTextBlock(b))
else
@blocks = []
getOptions: ->
blocks: @blocks.map((b) -> b.getOptions())
alignment: @textAlign
@isStyledText: (styledText) ->
return styledText?.blocks? and styledText?.alignment? and _.isArray(styledText.blocks) and _.isString(styledText.alignment)
setElement: (element) ->
return if not element?
@element = element
for style, value of StyledText.defaultStyles
if not @element.style[style]
@element.style[style] = value
if @textAlign? and not @element.style["textAlign"]
@element.style["textAlign"] = @textAlign
render: ->
return if not @element?
while @element.hasChildNodes()
@element.removeChild(@element.lastChild)
for block in @blocks
blockDiv = block.createElement()
block.element = blockDiv
@element.appendChild blockDiv
addBlock: (text, css = null) ->
if css?
block = new StyledTextBlock
text: text
css: css
else if @blocks.length > 0
block = _.last(@blocks).clone()
block.setText(text)
else
block = new StyledTextBlock
text: text
css: {}
@blocks.push(block)
getText: ->
@blocks.map((b) -> b.text).join("\n")
setText: (text) ->
values = text.split("\n")
@blocks = @blocks.slice(0, values.length)
for value, index in values
if @blocks[index]?
block = @blocks[index]
block.setText(value)
else
@addBlock value
setTextOverflow: (textOverflow) ->
@textOverflow = textOverflow
setStyle: (style, value) ->
@blocks.map (block) -> block.setStyle(style, value)
resetStyle: (style) ->
@blocks.map (block) -> block.resetStyle(style)
getStyle: (style, block=null) ->
return (block ? _.first(@blocks))?.getStyle(style) ? @element?.style[style]
getFonts: ->
fonts = []
elementFont = @element?.style["fontFamily"]
if elementFont?
fonts.push(elementFont)
for block in @blocks
fonts = fonts.concat block.getFonts()
return _.uniq(fonts)
measure: (currentSize) ->
constraints = {}
constraints.width = currentSize.width * currentSize.multiplier
constraints.height = currentSize.height * currentSize.multiplier
m = getMeasureElement(constraints)
measuredWidth = 0
measuredHeight = 0
parent = @element.parentNode
m.appendChild @element
for block in @blocks
size = block.measure()
measuredWidth = Math.max(measuredWidth, size.width)
constrainedHeight = if constraints.height? then constraints.height / currentSize.multiplier else null
if not @autoWidth and
@textOverflow? and @textOverflow in ["clip", "ellipsis"] and
constrainedHeight? and (measuredHeight + size.height) > constrainedHeight
fontSize = parseFloat(@getStyle("fontSize", block))
lineHeight = parseFloat(@getStyle("lineHeight", block))
availableHeight = constrainedHeight - measuredHeight
if availableHeight > 0
visibleLines = Math.max(1, Math.floor(availableHeight / (fontSize*lineHeight)))
block.setTextOverflow(@textOverflow, visibleLines)
else
block.setStyle("visibility", "hidden")
size.height = availableHeight
else
block.setTextOverflow(null)
measuredHeight += size.height
m.removeChild @element
parent?.appendChild @element
result = {}
if @autoWidth
result.width = Math.ceil(measuredWidth)
if @autoHeight
result.height = Math.ceil(measuredHeight)
return result
replace: (search, replace) ->
@blocks.map( (b) -> b.replaceText(search, replace))
validate: ->
for block in @blocks
return false if not block.validate()
return true