UNPKG

2.79 kBtext/coffeescriptView Raw
1# Import
2{TaskGroup} = require('taskgroup')
3
4
5# =====================================
6# HTML
7
8balUtilHTML =
9
10 # Extract Argument
11 getAttribute: (attributes,attribute) ->
12 regex = new RegExp("""(#{attribute})\\s*=\\s*('[^']+'|\\"[^\\"]+\\"|[^'\\"\\s]\\S*)""",'ig')
13 value = null
14 while match = regex.exec(attributes)
15 value = match[2].trim().replace(/(^['"]\s*|\s*['"]$)/g, '')
16 return value
17
18 # Detect Indentation
19 detectIndentation: (source) ->
20 result = /\n([ \t]*)\S/m.exec(source)
21 indentation = result?[1] or ''
22 return indentation
23
24 # Remove Indentation
25 removeIndentation: (source) ->
26 indentation = balUtilHTML.detectIndentation(source)
27 regexString = indentation.replace(/\t/g,'\\t')
28 regex = new RegExp("""^#{regexString}""",'gm')
29 result = source.replace(regex,'').trim()
30 return result
31
32 # Replace Element
33 # replaceElementCallback(outerHTML, element, attributes, innerHTML)
34 # returns the replace result
35 replaceElement: (args...) ->
36 # Extract
37 if args.length is 1
38 {html, element, removeIndentation, replace} = args[0]
39 else
40 [html, element, replace] = args
41
42 # Replace
43 regex = new RegExp("""<(#{element}(?:\\:[-:_a-z0-9]+)?)(\\s+[^>]+)?>([\\s\\S]+?)<\\/\\1>""",'ig')
44 result = html.replace regex, (outerHTML, element, attributes, innerHTML) ->
45 # Remove the indentation from the innerHTML
46 innerHTML = balUtilHTML.removeIndentation(innerHTML) if removeIndentation isnt false
47 # Fetch the result
48 return replace(outerHTML, element, attributes, innerHTML)
49
50 # Return
51 return result
52
53 # Replace Element Async
54 # replaceElementCallback(outerHTML, element, attributes, innerHTML, replaceElementCompleteCallback), replaceElementCompleteCallback(err,replaceElementResult)
55 # next(err,result)
56 replaceElementAsync: (args...) ->
57 # Extract
58 if args.length is 1
59 {html, element, removeIndentation, replace, next} = args[0]
60 else
61 [html, element, replace, next] = args
62
63 # Prepare
64 tasks = new TaskGroup(concurrency:0).done (err) ->
65 return next(err) if err
66 return next(null,result)
67
68 # Replace
69 result = balUtilHTML.replaceElement(
70 html: html
71 element: element
72 removeIndentation: removeIndentation
73 replace: (outerHTML, element, attributes, innerHTML) ->
74 # Generate a temporary random number to replace the text with in the meantime
75 random = Math.random()
76
77 # Push the actual replace task
78 tasks.addTask (complete) ->
79 replace outerHTML, element, attributes, innerHTML, (err,replaceElementResult) ->
80 return complete(err) if err
81 result = result.replace(random,replaceElementResult)
82 return complete()
83
84 # Return the random to the replace
85 return random
86 )
87
88 # Run the tasks
89 tasks.run()
90
91 # Chain
92 @
93
94
95# =====================================
96# Export
97
98module.exports = balUtilHTML
\No newline at end of file