Skip to content

Commit 4c1b2d4

Browse files
committed
- A new method has been added to the Label class that allows processing text with a regular expression and adding DOM elements where matches occur. This new function can be used as a text_node_func in labels. An example of this new method is a function that parses the text looking for object IDs and displays links to show these objects in a popover.
See #75603
1 parent 58df7e3 commit 4c1b2d4

File tree

1 file changed

+39
-0
lines changed

1 file changed

+39
-0
lines changed

src/elements/Label/Label.coffee

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -326,6 +326,45 @@ class CUI.Label extends CUI.DOMElement
326326
append_text()
327327
return nodes
328328

329+
# Let us specify a regex to parse the text and generate
330+
# dom elements. suitable to use as text_node_func.
331+
@parseWithRegex = (text, regexp, getElement) ->
332+
nodes = []
333+
lastIndex = 0
334+
335+
unless regexp.global
336+
throw new Error "RegExp must have the /g flag"
337+
338+
# Reset in case it was used before
339+
regexp.lastIndex = 0
340+
341+
while match = regexp.exec text
342+
matchText = match[0]
343+
matchIndex = match.index
344+
345+
# Append any text before this match as a text node
346+
if matchIndex > lastIndex
347+
preText = text.substring(lastIndex, matchIndex)
348+
nodes.push CUI.dom.text(preText)
349+
350+
# Generate a node for the matched text the user needs to provide a getElement function
351+
node = getElement(matchText, matchIndex, text)
352+
if node?
353+
nodes.push node
354+
else
355+
# If getElement returns null/undefined, fall back to plain text
356+
nodes.push CUI.dom.text(matchText)
357+
358+
# Move past this match
359+
lastIndex = regexp.lastIndex
360+
361+
# Append any remaining text after last match
362+
if lastIndex < text.length
363+
tail = text.substring(lastIndex)
364+
nodes.push CUI.dom.text(tail)
365+
366+
return nodes
367+
329368

330369

331370
CUI.defaults.class.Label = CUI.Label

0 commit comments

Comments
 (0)