UiFileManager plugin
This commit is contained in:
parent
85790f8866
commit
f0b0f57643
24 changed files with 2541 additions and 0 deletions
138
plugins/UiFileManager/media/js/lib/Animation.coffee
Normal file
138
plugins/UiFileManager/media/js/lib/Animation.coffee
Normal file
|
@ -0,0 +1,138 @@
|
|||
class Animation
|
||||
slideDown: (elem, props) ->
|
||||
if elem.offsetTop > 2000
|
||||
return
|
||||
|
||||
h = elem.offsetHeight
|
||||
cstyle = window.getComputedStyle(elem)
|
||||
margin_top = cstyle.marginTop
|
||||
margin_bottom = cstyle.marginBottom
|
||||
padding_top = cstyle.paddingTop
|
||||
padding_bottom = cstyle.paddingBottom
|
||||
transition = cstyle.transition
|
||||
|
||||
elem.style.boxSizing = "border-box"
|
||||
elem.style.overflow = "hidden"
|
||||
elem.style.transform = "scale(0.6)"
|
||||
elem.style.opacity = "0"
|
||||
elem.style.height = "0px"
|
||||
elem.style.marginTop = "0px"
|
||||
elem.style.marginBottom = "0px"
|
||||
elem.style.paddingTop = "0px"
|
||||
elem.style.paddingBottom = "0px"
|
||||
elem.style.transition = "none"
|
||||
|
||||
setTimeout (->
|
||||
elem.className += " animate-inout"
|
||||
elem.style.height = h+"px"
|
||||
elem.style.transform = "scale(1)"
|
||||
elem.style.opacity = "1"
|
||||
elem.style.marginTop = margin_top
|
||||
elem.style.marginBottom = margin_bottom
|
||||
elem.style.paddingTop = padding_top
|
||||
elem.style.paddingBottom = padding_bottom
|
||||
), 1
|
||||
|
||||
elem.addEventListener "transitionend", ->
|
||||
elem.classList.remove("animate-inout")
|
||||
elem.style.transition = elem.style.transform = elem.style.opacity = elem.style.height = null
|
||||
elem.style.boxSizing = elem.style.marginTop = elem.style.marginBottom = null
|
||||
elem.style.paddingTop = elem.style.paddingBottom = elem.style.overflow = null
|
||||
elem.removeEventListener "transitionend", arguments.callee, false
|
||||
|
||||
|
||||
slideUp: (elem, remove_func, props) ->
|
||||
if elem.offsetTop > 1000
|
||||
return remove_func()
|
||||
|
||||
elem.className += " animate-back"
|
||||
elem.style.boxSizing = "border-box"
|
||||
elem.style.height = elem.offsetHeight+"px"
|
||||
elem.style.overflow = "hidden"
|
||||
elem.style.transform = "scale(1)"
|
||||
elem.style.opacity = "1"
|
||||
elem.style.pointerEvents = "none"
|
||||
setTimeout (->
|
||||
elem.style.height = "0px"
|
||||
elem.style.marginTop = "0px"
|
||||
elem.style.marginBottom = "0px"
|
||||
elem.style.paddingTop = "0px"
|
||||
elem.style.paddingBottom = "0px"
|
||||
elem.style.transform = "scale(0.8)"
|
||||
elem.style.borderTopWidth = "0px"
|
||||
elem.style.borderBottomWidth = "0px"
|
||||
elem.style.opacity = "0"
|
||||
), 1
|
||||
elem.addEventListener "transitionend", (e) ->
|
||||
if e.propertyName == "opacity" or e.elapsedTime >= 0.6
|
||||
elem.removeEventListener "transitionend", arguments.callee, false
|
||||
remove_func()
|
||||
|
||||
|
||||
slideUpInout: (elem, remove_func, props) ->
|
||||
elem.className += " animate-inout"
|
||||
elem.style.boxSizing = "border-box"
|
||||
elem.style.height = elem.offsetHeight+"px"
|
||||
elem.style.overflow = "hidden"
|
||||
elem.style.transform = "scale(1)"
|
||||
elem.style.opacity = "1"
|
||||
elem.style.pointerEvents = "none"
|
||||
setTimeout (->
|
||||
elem.style.height = "0px"
|
||||
elem.style.marginTop = "0px"
|
||||
elem.style.marginBottom = "0px"
|
||||
elem.style.paddingTop = "0px"
|
||||
elem.style.paddingBottom = "0px"
|
||||
elem.style.transform = "scale(0.8)"
|
||||
elem.style.borderTopWidth = "0px"
|
||||
elem.style.borderBottomWidth = "0px"
|
||||
elem.style.opacity = "0"
|
||||
), 1
|
||||
elem.addEventListener "transitionend", (e) ->
|
||||
if e.propertyName == "opacity" or e.elapsedTime >= 0.6
|
||||
elem.removeEventListener "transitionend", arguments.callee, false
|
||||
remove_func()
|
||||
|
||||
|
||||
showRight: (elem, props) ->
|
||||
elem.className += " animate"
|
||||
elem.style.opacity = 0
|
||||
elem.style.transform = "TranslateX(-20px) Scale(1.01)"
|
||||
setTimeout (->
|
||||
elem.style.opacity = 1
|
||||
elem.style.transform = "TranslateX(0px) Scale(1)"
|
||||
), 1
|
||||
elem.addEventListener "transitionend", ->
|
||||
elem.classList.remove("animate")
|
||||
elem.style.transform = elem.style.opacity = null
|
||||
|
||||
|
||||
show: (elem, props) ->
|
||||
delay = arguments[arguments.length-2]?.delay*1000 or 1
|
||||
elem.style.opacity = 0
|
||||
setTimeout (->
|
||||
elem.className += " animate"
|
||||
), 1
|
||||
setTimeout (->
|
||||
elem.style.opacity = 1
|
||||
), delay
|
||||
elem.addEventListener "transitionend", ->
|
||||
elem.classList.remove("animate")
|
||||
elem.style.opacity = null
|
||||
elem.removeEventListener "transitionend", arguments.callee, false
|
||||
|
||||
hide: (elem, remove_func, props) ->
|
||||
delay = arguments[arguments.length-2]?.delay*1000 or 1
|
||||
elem.className += " animate"
|
||||
setTimeout (->
|
||||
elem.style.opacity = 0
|
||||
), delay
|
||||
elem.addEventListener "transitionend", (e) ->
|
||||
if e.propertyName == "opacity"
|
||||
remove_func()
|
||||
|
||||
addVisibleClass: (elem, props) ->
|
||||
setTimeout ->
|
||||
elem.classList.add("visible")
|
||||
|
||||
window.Animation = new Animation()
|
23
plugins/UiFileManager/media/js/lib/Class.coffee
Normal file
23
plugins/UiFileManager/media/js/lib/Class.coffee
Normal file
|
@ -0,0 +1,23 @@
|
|||
class Class
|
||||
trace: true
|
||||
|
||||
log: (args...) ->
|
||||
return unless @trace
|
||||
return if typeof console is 'undefined'
|
||||
args.unshift("[#{@.constructor.name}]")
|
||||
console.log(args...)
|
||||
@
|
||||
|
||||
logStart: (name, args...) ->
|
||||
return unless @trace
|
||||
@logtimers or= {}
|
||||
@logtimers[name] = +(new Date)
|
||||
@log "#{name}", args..., "(started)" if args.length > 0
|
||||
@
|
||||
|
||||
logEnd: (name, args...) ->
|
||||
ms = +(new Date)-@logtimers[name]
|
||||
@log "#{name}", args..., "(Done in #{ms}ms)"
|
||||
@
|
||||
|
||||
window.Class = Class
|
3
plugins/UiFileManager/media/js/lib/Dollar.coffee
Normal file
3
plugins/UiFileManager/media/js/lib/Dollar.coffee
Normal file
|
@ -0,0 +1,3 @@
|
|||
window.$ = (selector) ->
|
||||
if selector.startsWith("#")
|
||||
return document.getElementById(selector.replace("#", ""))
|
26
plugins/UiFileManager/media/js/lib/ItemList.coffee
Normal file
26
plugins/UiFileManager/media/js/lib/ItemList.coffee
Normal file
|
@ -0,0 +1,26 @@
|
|||
class ItemList
|
||||
constructor: (@item_class, @key) ->
|
||||
@items = []
|
||||
@items_bykey = {}
|
||||
|
||||
sync: (rows, item_class, key) ->
|
||||
@items.splice(0, @items.length) # Empty items
|
||||
for row in rows
|
||||
current_obj = @items_bykey[row[@key]]
|
||||
if current_obj
|
||||
current_obj.row = row
|
||||
@items.push current_obj
|
||||
else
|
||||
item = new @item_class(row, @)
|
||||
@items_bykey[row[@key]] = item
|
||||
@items.push item
|
||||
|
||||
deleteItem: (item) ->
|
||||
index = @items.indexOf(item)
|
||||
if index > -1
|
||||
@items.splice(index, 1)
|
||||
else
|
||||
console.log "Can't delete item", item
|
||||
delete @items_bykey[item.row[@key]]
|
||||
|
||||
window.ItemList = ItemList
|
110
plugins/UiFileManager/media/js/lib/Menu.coffee
Normal file
110
plugins/UiFileManager/media/js/lib/Menu.coffee
Normal file
|
@ -0,0 +1,110 @@
|
|||
class Menu
|
||||
constructor: ->
|
||||
@visible = false
|
||||
@items = []
|
||||
@node = null
|
||||
@height = 0
|
||||
@direction = "bottom"
|
||||
|
||||
show: =>
|
||||
window.visible_menu?.hide()
|
||||
@visible = true
|
||||
window.visible_menu = @
|
||||
@direction = @getDirection()
|
||||
|
||||
hide: =>
|
||||
@visible = false
|
||||
|
||||
toggle: =>
|
||||
if @visible
|
||||
@hide()
|
||||
else
|
||||
@show()
|
||||
Page.projector.scheduleRender()
|
||||
|
||||
|
||||
addItem: (title, cb, selected=false) ->
|
||||
@items.push([title, cb, selected])
|
||||
|
||||
|
||||
storeNode: (node) =>
|
||||
@node = node
|
||||
# Animate visible
|
||||
if @visible
|
||||
node.className = node.className.replace("visible", "")
|
||||
setTimeout (=>
|
||||
node.className += " visible"
|
||||
node.attributes.style.value = @getStyle()
|
||||
), 20
|
||||
node.style.maxHeight = "none"
|
||||
@height = node.offsetHeight
|
||||
node.style.maxHeight = "0px"
|
||||
@direction = @getDirection()
|
||||
|
||||
getDirection: =>
|
||||
if @node and @node.parentNode.getBoundingClientRect().top + @height + 60 > document.body.clientHeight and @node.parentNode.getBoundingClientRect().top - @height > 0
|
||||
return "top"
|
||||
else
|
||||
return "bottom"
|
||||
|
||||
handleClick: (e) =>
|
||||
keep_menu = false
|
||||
for item in @items
|
||||
[title, cb, selected] = item
|
||||
if title == e.currentTarget.textContent or e.currentTarget["data-title"] == title
|
||||
keep_menu = cb?(item)
|
||||
break
|
||||
if keep_menu != true and cb != null
|
||||
@hide()
|
||||
return false
|
||||
|
||||
renderItem: (item) =>
|
||||
[title, cb, selected] = item
|
||||
if typeof(selected) == "function"
|
||||
selected = selected()
|
||||
|
||||
if title == "---"
|
||||
return h("div.menu-item-separator", {key: Time.timestamp()})
|
||||
else
|
||||
if cb == null
|
||||
href = undefined
|
||||
onclick = @handleClick
|
||||
else if typeof(cb) == "string" # Url
|
||||
href = cb
|
||||
onclick = true
|
||||
else # Callback
|
||||
href = "#"+title
|
||||
onclick = @handleClick
|
||||
classes = {
|
||||
"selected": selected,
|
||||
"noaction": (cb == null)
|
||||
}
|
||||
return h("a.menu-item", {href: href, onclick: onclick, "data-title": title, key: title, classes: classes}, title)
|
||||
|
||||
getStyle: =>
|
||||
if @visible
|
||||
max_height = @height
|
||||
else
|
||||
max_height = 0
|
||||
style = "max-height: #{max_height}px"
|
||||
if @direction == "top"
|
||||
style += ";margin-top: #{0 - @height - 50}px"
|
||||
else
|
||||
style += ";margin-top: 0px"
|
||||
return style
|
||||
|
||||
render: (class_name="") =>
|
||||
if @visible or @node
|
||||
h("div.menu#{class_name}", {classes: {"visible": @visible}, style: @getStyle(), afterCreate: @storeNode}, @items.map(@renderItem))
|
||||
|
||||
window.Menu = Menu
|
||||
|
||||
# Hide menu on outside click
|
||||
document.body.addEventListener "mouseup", (e) ->
|
||||
if not window.visible_menu or not window.visible_menu.node
|
||||
return false
|
||||
menu_node = window.visible_menu.node
|
||||
menu_parents = [menu_node, menu_node.parentNode]
|
||||
if e.target.parentNode not in menu_parents and e.target.parentNode.parentNode not in menu_parents
|
||||
window.visible_menu.hide()
|
||||
Page.projector.scheduleRender()
|
74
plugins/UiFileManager/media/js/lib/Promise.coffee
Normal file
74
plugins/UiFileManager/media/js/lib/Promise.coffee
Normal file
|
@ -0,0 +1,74 @@
|
|||
# From: http://dev.bizo.com/2011/12/promises-in-javascriptcoffeescript.html
|
||||
|
||||
class Promise
|
||||
@when: (tasks...) ->
|
||||
num_uncompleted = tasks.length
|
||||
args = new Array(num_uncompleted)
|
||||
promise = new Promise()
|
||||
|
||||
for task, task_id in tasks
|
||||
((task_id) ->
|
||||
task.then(() ->
|
||||
args[task_id] = Array.prototype.slice.call(arguments)
|
||||
num_uncompleted--
|
||||
promise.complete.apply(promise, args) if num_uncompleted == 0
|
||||
)
|
||||
)(task_id)
|
||||
|
||||
return promise
|
||||
|
||||
constructor: ->
|
||||
@resolved = false
|
||||
@end_promise = null
|
||||
@result = null
|
||||
@callbacks = []
|
||||
|
||||
resolve: ->
|
||||
if @resolved
|
||||
return false
|
||||
@resolved = true
|
||||
@data = arguments
|
||||
if not arguments.length
|
||||
@data = [true]
|
||||
@result = @data[0]
|
||||
for callback in @callbacks
|
||||
back = callback.apply callback, @data
|
||||
if @end_promise
|
||||
@end_promise.resolve(back)
|
||||
|
||||
fail: ->
|
||||
@resolve(false)
|
||||
|
||||
then: (callback) ->
|
||||
if @resolved == true
|
||||
callback.apply callback, @data
|
||||
return
|
||||
|
||||
@callbacks.push callback
|
||||
|
||||
@end_promise = new Promise()
|
||||
|
||||
window.Promise = Promise
|
||||
|
||||
###
|
||||
s = Date.now()
|
||||
log = (text) ->
|
||||
console.log Date.now()-s, Array.prototype.slice.call(arguments).join(", ")
|
||||
|
||||
log "Started"
|
||||
|
||||
cmd = (query) ->
|
||||
p = new Promise()
|
||||
setTimeout ( ->
|
||||
p.resolve query+" Result"
|
||||
), 100
|
||||
return p
|
||||
|
||||
back = cmd("SELECT * FROM message").then (res) ->
|
||||
log res
|
||||
return "Return from query"
|
||||
.then (res) ->
|
||||
log "Back then", res
|
||||
|
||||
log "Query started", back
|
||||
###
|
9
plugins/UiFileManager/media/js/lib/Prototypes.coffee
Normal file
9
plugins/UiFileManager/media/js/lib/Prototypes.coffee
Normal file
|
@ -0,0 +1,9 @@
|
|||
String::startsWith = (s) -> @[...s.length] is s
|
||||
String::endsWith = (s) -> s is '' or @[-s.length..] is s
|
||||
String::repeat = (count) -> new Array( count + 1 ).join(@)
|
||||
|
||||
window.isEmpty = (obj) ->
|
||||
for key of obj
|
||||
return false
|
||||
return true
|
||||
|
62
plugins/UiFileManager/media/js/lib/RateLimitCb.coffee
Normal file
62
plugins/UiFileManager/media/js/lib/RateLimitCb.coffee
Normal file
|
@ -0,0 +1,62 @@
|
|||
last_time = {}
|
||||
calling = {}
|
||||
calling_iterval = {}
|
||||
call_after_interval = {}
|
||||
|
||||
# Rate limit function call and don't allow to run in parallel (until callback is called)
|
||||
window.RateLimitCb = (interval, fn, args=[]) ->
|
||||
cb = -> # Callback when function finished
|
||||
left = interval - (Date.now() - last_time[fn]) # Time life until next call
|
||||
# console.log "CB, left", left, "Calling:", calling[fn]
|
||||
if left <= 0 # No time left from rate limit interval
|
||||
delete last_time[fn]
|
||||
if calling[fn] # Function called within interval
|
||||
RateLimitCb(interval, fn, calling[fn])
|
||||
delete calling[fn]
|
||||
else # Time left from rate limit interval
|
||||
setTimeout (->
|
||||
delete last_time[fn]
|
||||
if calling[fn] # Function called within interval
|
||||
RateLimitCb(interval, fn, calling[fn])
|
||||
delete calling[fn]
|
||||
), left
|
||||
if last_time[fn] # Function called within interval
|
||||
calling[fn] = args # Schedule call and update arguments
|
||||
else # Not called within interval, call instantly
|
||||
last_time[fn] = Date.now()
|
||||
fn.apply(this, [cb, args...])
|
||||
|
||||
|
||||
window.RateLimit = (interval, fn) ->
|
||||
if calling_iterval[fn] > interval
|
||||
clearInterval calling[fn]
|
||||
delete calling[fn]
|
||||
|
||||
if not calling[fn]
|
||||
call_after_interval[fn] = false
|
||||
fn() # First call is not delayed
|
||||
calling_iterval[fn] = interval
|
||||
calling[fn] = setTimeout (->
|
||||
if call_after_interval[fn]
|
||||
fn()
|
||||
delete calling[fn]
|
||||
delete call_after_interval[fn]
|
||||
), interval
|
||||
else # Called within iterval, delay the call
|
||||
call_after_interval[fn] = true
|
||||
|
||||
|
||||
###
|
||||
window.s = Date.now()
|
||||
window.load = (done, num) ->
|
||||
console.log "Loading #{num}...", Date.now()-window.s
|
||||
setTimeout (-> done()), 1000
|
||||
|
||||
RateLimit 500, window.load, [0] # Called instantly
|
||||
RateLimit 500, window.load, [1]
|
||||
setTimeout (-> RateLimit 500, window.load, [300]), 300
|
||||
setTimeout (-> RateLimit 500, window.load, [600]), 600 # Called after 1000ms
|
||||
setTimeout (-> RateLimit 500, window.load, [1000]), 1000
|
||||
setTimeout (-> RateLimit 500, window.load, [1200]), 1200 # Called after 2000ms
|
||||
setTimeout (-> RateLimit 500, window.load, [3000]), 3000 # Called after 3000ms
|
||||
###
|
147
plugins/UiFileManager/media/js/lib/Text.coffee
Normal file
147
plugins/UiFileManager/media/js/lib/Text.coffee
Normal file
|
@ -0,0 +1,147 @@
|
|||
class Text
|
||||
toColor: (text, saturation=30, lightness=50) ->
|
||||
hash = 0
|
||||
for i in [0..text.length-1]
|
||||
hash += text.charCodeAt(i)*i
|
||||
hash = hash % 1777
|
||||
return "hsl(" + (hash % 360) + ",#{saturation}%,#{lightness}%)";
|
||||
|
||||
|
||||
renderMarked: (text, options={}) ->
|
||||
options["gfm"] = true
|
||||
options["breaks"] = true
|
||||
options["sanitize"] = true
|
||||
options["renderer"] = marked_renderer
|
||||
text = marked(text, options)
|
||||
return @fixHtmlLinks text
|
||||
|
||||
emailLinks: (text) ->
|
||||
return text.replace(/([a-zA-Z0-9]+)@zeroid.bit/g, "<a href='?to=$1' onclick='return Page.message_create.show(\"$1\")'>$1@zeroid.bit</a>")
|
||||
|
||||
# Convert zeronet html links to relaitve
|
||||
fixHtmlLinks: (text) ->
|
||||
if window.is_proxy
|
||||
return text.replace(/href="http:\/\/(127.0.0.1|localhost):43110/g, 'href="http://zero')
|
||||
else
|
||||
return text.replace(/href="http:\/\/(127.0.0.1|localhost):43110/g, 'href="')
|
||||
|
||||
# Convert a single link to relative
|
||||
fixLink: (link) ->
|
||||
if window.is_proxy
|
||||
back = link.replace(/http:\/\/(127.0.0.1|localhost):43110/, 'http://zero')
|
||||
return back.replace(/http:\/\/zero\/([^\/]+\.bit)/, "http://$1") # Domain links
|
||||
else
|
||||
return link.replace(/http:\/\/(127.0.0.1|localhost):43110/, '')
|
||||
|
||||
toUrl: (text) ->
|
||||
return text.replace(/[^A-Za-z0-9]/g, "+").replace(/[+]+/g, "+").replace(/[+]+$/, "")
|
||||
|
||||
getSiteUrl: (address) ->
|
||||
if window.is_proxy
|
||||
if "." in address # Domain
|
||||
return "http://"+address+"/"
|
||||
else
|
||||
return "http://zero/"+address+"/"
|
||||
else
|
||||
return "/"+address+"/"
|
||||
|
||||
|
||||
fixReply: (text) ->
|
||||
return text.replace(/(>.*\n)([^\n>])/gm, "$1\n$2")
|
||||
|
||||
toBitcoinAddress: (text) ->
|
||||
return text.replace(/[^A-Za-z0-9]/g, "")
|
||||
|
||||
|
||||
jsonEncode: (obj) ->
|
||||
return unescape(encodeURIComponent(JSON.stringify(obj)))
|
||||
|
||||
jsonDecode: (obj) ->
|
||||
return JSON.parse(decodeURIComponent(escape(obj)))
|
||||
|
||||
fileEncode: (obj) ->
|
||||
if typeof(obj) == "string"
|
||||
return btoa(unescape(encodeURIComponent(obj)))
|
||||
else
|
||||
return btoa(unescape(encodeURIComponent(JSON.stringify(obj, undefined, '\t'))))
|
||||
|
||||
utf8Encode: (s) ->
|
||||
return unescape(encodeURIComponent(s))
|
||||
|
||||
utf8Decode: (s) ->
|
||||
return decodeURIComponent(escape(s))
|
||||
|
||||
|
||||
distance: (s1, s2) ->
|
||||
s1 = s1.toLocaleLowerCase()
|
||||
s2 = s2.toLocaleLowerCase()
|
||||
next_find_i = 0
|
||||
next_find = s2[0]
|
||||
match = true
|
||||
extra_parts = {}
|
||||
for char in s1
|
||||
if char != next_find
|
||||
if extra_parts[next_find_i]
|
||||
extra_parts[next_find_i] += char
|
||||
else
|
||||
extra_parts[next_find_i] = char
|
||||
else
|
||||
next_find_i++
|
||||
next_find = s2[next_find_i]
|
||||
|
||||
if extra_parts[next_find_i]
|
||||
extra_parts[next_find_i] = "" # Extra chars on the end doesnt matter
|
||||
extra_parts = (val for key, val of extra_parts)
|
||||
if next_find_i >= s2.length
|
||||
return extra_parts.length + extra_parts.join("").length
|
||||
else
|
||||
return false
|
||||
|
||||
|
||||
parseQuery: (query) ->
|
||||
params = {}
|
||||
parts = query.split('&')
|
||||
for part in parts
|
||||
[key, val] = part.split("=")
|
||||
if val
|
||||
params[decodeURIComponent(key)] = decodeURIComponent(val)
|
||||
else
|
||||
params["url"] = decodeURIComponent(key)
|
||||
return params
|
||||
|
||||
encodeQuery: (params) ->
|
||||
back = []
|
||||
if params.url
|
||||
back.push(params.url)
|
||||
for key, val of params
|
||||
if not val or key == "url"
|
||||
continue
|
||||
back.push("#{encodeURIComponent(key)}=#{encodeURIComponent(val)}")
|
||||
return back.join("&")
|
||||
|
||||
highlight: (text, search) ->
|
||||
if not text
|
||||
return [""]
|
||||
parts = text.split(RegExp(search, "i"))
|
||||
back = []
|
||||
for part, i in parts
|
||||
back.push(part)
|
||||
if i < parts.length-1
|
||||
back.push(h("span.highlight", {key: i}, search))
|
||||
return back
|
||||
|
||||
formatSize: (size) ->
|
||||
if isNaN(parseInt(size))
|
||||
return ""
|
||||
size_mb = size/1024/1024
|
||||
if size_mb >= 1000
|
||||
return (size_mb/1024).toFixed(1)+" GB"
|
||||
else if size_mb >= 100
|
||||
return size_mb.toFixed(0)+" MB"
|
||||
else if size/1024 >= 1000
|
||||
return size_mb.toFixed(2)+" MB"
|
||||
else
|
||||
return (parseInt(size)/1024).toFixed(2)+" KB"
|
||||
|
||||
window.is_proxy = (document.location.host == "zero" or window.location.pathname == "/")
|
||||
window.Text = new Text()
|
59
plugins/UiFileManager/media/js/lib/Time.coffee
Normal file
59
plugins/UiFileManager/media/js/lib/Time.coffee
Normal file
|
@ -0,0 +1,59 @@
|
|||
class Time
|
||||
since: (timestamp) ->
|
||||
now = +(new Date)/1000
|
||||
if timestamp > 1000000000000 # In ms
|
||||
timestamp = timestamp/1000
|
||||
secs = now - timestamp
|
||||
if secs < 60
|
||||
back = "Just now"
|
||||
else if secs < 60*60
|
||||
minutes = Math.round(secs/60)
|
||||
back = "" + minutes + " minutes ago"
|
||||
else if secs < 60*60*24
|
||||
back = "#{Math.round(secs/60/60)} hours ago"
|
||||
else if secs < 60*60*24*3
|
||||
back = "#{Math.round(secs/60/60/24)} days ago"
|
||||
else
|
||||
back = "on "+@date(timestamp)
|
||||
back = back.replace(/^1 ([a-z]+)s/, "1 $1") # 1 days ago fix
|
||||
return back
|
||||
|
||||
dateIso: (timestamp=null) ->
|
||||
if not timestamp
|
||||
timestamp = window.Time.timestamp()
|
||||
|
||||
if timestamp > 1000000000000 # In ms
|
||||
timestamp = timestamp/1000
|
||||
tzoffset = (new Date()).getTimezoneOffset() * 60
|
||||
return (new Date((timestamp - tzoffset) * 1000)).toISOString().split("T")[0]
|
||||
|
||||
date: (timestamp=null, format="short") ->
|
||||
if not timestamp
|
||||
timestamp = window.Time.timestamp()
|
||||
|
||||
if timestamp > 1000000000000 # In ms
|
||||
timestamp = timestamp/1000
|
||||
parts = (new Date(timestamp * 1000)).toString().split(" ")
|
||||
if format == "short"
|
||||
display = parts.slice(1, 4)
|
||||
else if format == "day"
|
||||
display = parts.slice(1, 3)
|
||||
else if format == "month"
|
||||
display = [parts[1], parts[3]]
|
||||
else if format == "long"
|
||||
display = parts.slice(1, 5)
|
||||
return display.join(" ").replace(/( [0-9]{4})/, ",$1")
|
||||
|
||||
weekDay: (timestamp) ->
|
||||
if timestamp > 1000000000000 # In ms
|
||||
timestamp = timestamp/1000
|
||||
return ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"][ (new Date(timestamp * 1000)).getDay() ]
|
||||
|
||||
timestamp: (date="") ->
|
||||
if date == "now" or date == ""
|
||||
return parseInt(+(new Date)/1000)
|
||||
else
|
||||
return parseInt(Date.parse(date)/1000)
|
||||
|
||||
|
||||
window.Time = new Time
|
85
plugins/UiFileManager/media/js/lib/ZeroFrame.coffee
Normal file
85
plugins/UiFileManager/media/js/lib/ZeroFrame.coffee
Normal file
|
@ -0,0 +1,85 @@
|
|||
class ZeroFrame extends Class
|
||||
constructor: (url) ->
|
||||
@url = url
|
||||
@waiting_cb = {}
|
||||
@wrapper_nonce = document.location.href.replace(/.*wrapper_nonce=([A-Za-z0-9]+).*/, "$1")
|
||||
@connect()
|
||||
@next_message_id = 1
|
||||
@history_state = {}
|
||||
@init()
|
||||
|
||||
|
||||
init: ->
|
||||
@
|
||||
|
||||
|
||||
connect: ->
|
||||
@target = window.parent
|
||||
window.addEventListener("message", @onMessage, false)
|
||||
@cmd("innerReady")
|
||||
|
||||
# Save scrollTop
|
||||
window.addEventListener "beforeunload", (e) =>
|
||||
@log "save scrollTop", window.pageYOffset
|
||||
@history_state["scrollTop"] = window.pageYOffset
|
||||
@cmd "wrapperReplaceState", [@history_state, null]
|
||||
|
||||
# Restore scrollTop
|
||||
@cmd "wrapperGetState", [], (state) =>
|
||||
@history_state = state if state?
|
||||
@log "restore scrollTop", state, window.pageYOffset
|
||||
if window.pageYOffset == 0 and state
|
||||
window.scroll(window.pageXOffset, state.scrollTop)
|
||||
|
||||
|
||||
onMessage: (e) =>
|
||||
message = e.data
|
||||
cmd = message.cmd
|
||||
if cmd == "response"
|
||||
if @waiting_cb[message.to]?
|
||||
@waiting_cb[message.to](message.result)
|
||||
else
|
||||
@log "Websocket callback not found:", message
|
||||
else if cmd == "wrapperReady" # Wrapper inited later
|
||||
@cmd("innerReady")
|
||||
else if cmd == "ping"
|
||||
@response message.id, "pong"
|
||||
else if cmd == "wrapperOpenedWebsocket"
|
||||
@onOpenWebsocket()
|
||||
else if cmd == "wrapperClosedWebsocket"
|
||||
@onCloseWebsocket()
|
||||
else
|
||||
@onRequest cmd, message.params
|
||||
|
||||
|
||||
onRequest: (cmd, message) =>
|
||||
@log "Unknown request", message
|
||||
|
||||
|
||||
response: (to, result) ->
|
||||
@send {"cmd": "response", "to": to, "result": result}
|
||||
|
||||
|
||||
cmd: (cmd, params={}, cb=null) ->
|
||||
@send {"cmd": cmd, "params": params}, cb
|
||||
|
||||
|
||||
send: (message, cb=null) ->
|
||||
message.wrapper_nonce = @wrapper_nonce
|
||||
message.id = @next_message_id
|
||||
@next_message_id += 1
|
||||
@target.postMessage(message, "*")
|
||||
if cb
|
||||
@waiting_cb[message.id] = cb
|
||||
|
||||
|
||||
onOpenWebsocket: =>
|
||||
@log "Websocket open"
|
||||
|
||||
|
||||
onCloseWebsocket: =>
|
||||
@log "Websocket close"
|
||||
|
||||
|
||||
|
||||
window.ZeroFrame = ZeroFrame
|
770
plugins/UiFileManager/media/js/lib/maquette.js
Normal file
770
plugins/UiFileManager/media/js/lib/maquette.js
Normal file
|
@ -0,0 +1,770 @@
|
|||
(function (root, factory) {
|
||||
if (typeof define === 'function' && define.amd) {
|
||||
// AMD. Register as an anonymous module.
|
||||
define(['exports'], factory);
|
||||
} else if (typeof exports === 'object' && typeof exports.nodeName !== 'string') {
|
||||
// CommonJS
|
||||
factory(exports);
|
||||
} else {
|
||||
// Browser globals
|
||||
factory(root.maquette = {});
|
||||
}
|
||||
}(this, function (exports) {
|
||||
'use strict';
|
||||
;
|
||||
;
|
||||
;
|
||||
;
|
||||
var NAMESPACE_W3 = 'http://www.w3.org/';
|
||||
var NAMESPACE_SVG = NAMESPACE_W3 + '2000/svg';
|
||||
var NAMESPACE_XLINK = NAMESPACE_W3 + '1999/xlink';
|
||||
// Utilities
|
||||
var emptyArray = [];
|
||||
var extend = function (base, overrides) {
|
||||
var result = {};
|
||||
Object.keys(base).forEach(function (key) {
|
||||
result[key] = base[key];
|
||||
});
|
||||
if (overrides) {
|
||||
Object.keys(overrides).forEach(function (key) {
|
||||
result[key] = overrides[key];
|
||||
});
|
||||
}
|
||||
return result;
|
||||
};
|
||||
// Hyperscript helper functions
|
||||
var same = function (vnode1, vnode2) {
|
||||
if (vnode1.vnodeSelector !== vnode2.vnodeSelector) {
|
||||
return false;
|
||||
}
|
||||
if (vnode1.properties && vnode2.properties) {
|
||||
if (vnode1.properties.key !== vnode2.properties.key) {
|
||||
return false;
|
||||
}
|
||||
return vnode1.properties.bind === vnode2.properties.bind;
|
||||
}
|
||||
return !vnode1.properties && !vnode2.properties;
|
||||
};
|
||||
var toTextVNode = function (data) {
|
||||
return {
|
||||
vnodeSelector: '',
|
||||
properties: undefined,
|
||||
children: undefined,
|
||||
text: data.toString(),
|
||||
domNode: null
|
||||
};
|
||||
};
|
||||
var appendChildren = function (parentSelector, insertions, main) {
|
||||
for (var i = 0; i < insertions.length; i++) {
|
||||
var item = insertions[i];
|
||||
if (Array.isArray(item)) {
|
||||
appendChildren(parentSelector, item, main);
|
||||
} else {
|
||||
if (item !== null && item !== undefined) {
|
||||
if (!item.hasOwnProperty('vnodeSelector')) {
|
||||
item = toTextVNode(item);
|
||||
}
|
||||
main.push(item);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
// Render helper functions
|
||||
var missingTransition = function () {
|
||||
throw new Error('Provide a transitions object to the projectionOptions to do animations');
|
||||
};
|
||||
var DEFAULT_PROJECTION_OPTIONS = {
|
||||
namespace: undefined,
|
||||
eventHandlerInterceptor: undefined,
|
||||
styleApplyer: function (domNode, styleName, value) {
|
||||
// Provides a hook to add vendor prefixes for browsers that still need it.
|
||||
domNode.style[styleName] = value;
|
||||
},
|
||||
transitions: {
|
||||
enter: missingTransition,
|
||||
exit: missingTransition
|
||||
}
|
||||
};
|
||||
var applyDefaultProjectionOptions = function (projectorOptions) {
|
||||
return extend(DEFAULT_PROJECTION_OPTIONS, projectorOptions);
|
||||
};
|
||||
var checkStyleValue = function (styleValue) {
|
||||
if (typeof styleValue !== 'string') {
|
||||
throw new Error('Style values must be strings');
|
||||
}
|
||||
};
|
||||
var setProperties = function (domNode, properties, projectionOptions) {
|
||||
if (!properties) {
|
||||
return;
|
||||
}
|
||||
var eventHandlerInterceptor = projectionOptions.eventHandlerInterceptor;
|
||||
var propNames = Object.keys(properties);
|
||||
var propCount = propNames.length;
|
||||
for (var i = 0; i < propCount; i++) {
|
||||
var propName = propNames[i];
|
||||
/* tslint:disable:no-var-keyword: edge case */
|
||||
var propValue = properties[propName];
|
||||
/* tslint:enable:no-var-keyword */
|
||||
if (propName === 'className') {
|
||||
throw new Error('Property "className" is not supported, use "class".');
|
||||
} else if (propName === 'class') {
|
||||
if (domNode.className) {
|
||||
// May happen if classes is specified before class
|
||||
domNode.className += ' ' + propValue;
|
||||
} else {
|
||||
domNode.className = propValue;
|
||||
}
|
||||
} else if (propName === 'classes') {
|
||||
// object with string keys and boolean values
|
||||
var classNames = Object.keys(propValue);
|
||||
var classNameCount = classNames.length;
|
||||
for (var j = 0; j < classNameCount; j++) {
|
||||
var className = classNames[j];
|
||||
if (propValue[className]) {
|
||||
domNode.classList.add(className);
|
||||
}
|
||||
}
|
||||
} else if (propName === 'styles') {
|
||||
// object with string keys and string (!) values
|
||||
var styleNames = Object.keys(propValue);
|
||||
var styleCount = styleNames.length;
|
||||
for (var j = 0; j < styleCount; j++) {
|
||||
var styleName = styleNames[j];
|
||||
var styleValue = propValue[styleName];
|
||||
if (styleValue) {
|
||||
checkStyleValue(styleValue);
|
||||
projectionOptions.styleApplyer(domNode, styleName, styleValue);
|
||||
}
|
||||
}
|
||||
} else if (propName === 'key') {
|
||||
continue;
|
||||
} else if (propValue === null || propValue === undefined) {
|
||||
continue;
|
||||
} else {
|
||||
var type = typeof propValue;
|
||||
if (type === 'function') {
|
||||
if (propName.lastIndexOf('on', 0) === 0) {
|
||||
if (eventHandlerInterceptor) {
|
||||
propValue = eventHandlerInterceptor(propName, propValue, domNode, properties); // intercept eventhandlers
|
||||
}
|
||||
if (propName === 'oninput') {
|
||||
(function () {
|
||||
// record the evt.target.value, because IE and Edge sometimes do a requestAnimationFrame between changing value and running oninput
|
||||
var oldPropValue = propValue;
|
||||
propValue = function (evt) {
|
||||
evt.target['oninput-value'] = evt.target.value;
|
||||
// may be HTMLTextAreaElement as well
|
||||
oldPropValue.apply(this, [evt]);
|
||||
};
|
||||
}());
|
||||
}
|
||||
domNode[propName] = propValue;
|
||||
}
|
||||
} else if (type === 'string' && propName !== 'value' && propName !== 'innerHTML') {
|
||||
if (projectionOptions.namespace === NAMESPACE_SVG && propName === 'href') {
|
||||
domNode.setAttributeNS(NAMESPACE_XLINK, propName, propValue);
|
||||
} else {
|
||||
domNode.setAttribute(propName, propValue);
|
||||
}
|
||||
} else {
|
||||
domNode[propName] = propValue;
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
var updateProperties = function (domNode, previousProperties, properties, projectionOptions) {
|
||||
if (!properties) {
|
||||
return;
|
||||
}
|
||||
var propertiesUpdated = false;
|
||||
var propNames = Object.keys(properties);
|
||||
var propCount = propNames.length;
|
||||
for (var i = 0; i < propCount; i++) {
|
||||
var propName = propNames[i];
|
||||
// assuming that properties will be nullified instead of missing is by design
|
||||
var propValue = properties[propName];
|
||||
var previousValue = previousProperties[propName];
|
||||
if (propName === 'class') {
|
||||
if (previousValue !== propValue) {
|
||||
throw new Error('"class" property may not be updated. Use the "classes" property for conditional css classes.');
|
||||
}
|
||||
} else if (propName === 'classes') {
|
||||
var classList = domNode.classList;
|
||||
var classNames = Object.keys(propValue);
|
||||
var classNameCount = classNames.length;
|
||||
for (var j = 0; j < classNameCount; j++) {
|
||||
var className = classNames[j];
|
||||
var on = !!propValue[className];
|
||||
var previousOn = !!previousValue[className];
|
||||
if (on === previousOn) {
|
||||
continue;
|
||||
}
|
||||
propertiesUpdated = true;
|
||||
if (on) {
|
||||
classList.add(className);
|
||||
} else {
|
||||
classList.remove(className);
|
||||
}
|
||||
}
|
||||
} else if (propName === 'styles') {
|
||||
var styleNames = Object.keys(propValue);
|
||||
var styleCount = styleNames.length;
|
||||
for (var j = 0; j < styleCount; j++) {
|
||||
var styleName = styleNames[j];
|
||||
var newStyleValue = propValue[styleName];
|
||||
var oldStyleValue = previousValue[styleName];
|
||||
if (newStyleValue === oldStyleValue) {
|
||||
continue;
|
||||
}
|
||||
propertiesUpdated = true;
|
||||
if (newStyleValue) {
|
||||
checkStyleValue(newStyleValue);
|
||||
projectionOptions.styleApplyer(domNode, styleName, newStyleValue);
|
||||
} else {
|
||||
projectionOptions.styleApplyer(domNode, styleName, '');
|
||||
}
|
||||
}
|
||||
} else {
|
||||
if (!propValue && typeof previousValue === 'string') {
|
||||
propValue = '';
|
||||
}
|
||||
if (propName === 'value') {
|
||||
if (domNode[propName] !== propValue && domNode['oninput-value'] !== propValue) {
|
||||
domNode[propName] = propValue;
|
||||
// Reset the value, even if the virtual DOM did not change
|
||||
domNode['oninput-value'] = undefined;
|
||||
}
|
||||
// else do not update the domNode, otherwise the cursor position would be changed
|
||||
if (propValue !== previousValue) {
|
||||
propertiesUpdated = true;
|
||||
}
|
||||
} else if (propValue !== previousValue) {
|
||||
var type = typeof propValue;
|
||||
if (type === 'function') {
|
||||
throw new Error('Functions may not be updated on subsequent renders (property: ' + propName + '). Hint: declare event handler functions outside the render() function.');
|
||||
}
|
||||
if (type === 'string' && propName !== 'innerHTML') {
|
||||
if (projectionOptions.namespace === NAMESPACE_SVG && propName === 'href') {
|
||||
domNode.setAttributeNS(NAMESPACE_XLINK, propName, propValue);
|
||||
} else {
|
||||
domNode.setAttribute(propName, propValue);
|
||||
}
|
||||
} else {
|
||||
if (domNode[propName] !== propValue) {
|
||||
domNode[propName] = propValue;
|
||||
}
|
||||
}
|
||||
propertiesUpdated = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return propertiesUpdated;
|
||||
};
|
||||
var findIndexOfChild = function (children, sameAs, start) {
|
||||
if (sameAs.vnodeSelector !== '') {
|
||||
// Never scan for text-nodes
|
||||
for (var i = start; i < children.length; i++) {
|
||||
if (same(children[i], sameAs)) {
|
||||
return i;
|
||||
}
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
};
|
||||
var nodeAdded = function (vNode, transitions) {
|
||||
if (vNode.properties) {
|
||||
var enterAnimation = vNode.properties.enterAnimation;
|
||||
if (enterAnimation) {
|
||||
if (typeof enterAnimation === 'function') {
|
||||
enterAnimation(vNode.domNode, vNode.properties);
|
||||
} else {
|
||||
transitions.enter(vNode.domNode, vNode.properties, enterAnimation);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
var nodeToRemove = function (vNode, transitions) {
|
||||
var domNode = vNode.domNode;
|
||||
if (vNode.properties) {
|
||||
var exitAnimation = vNode.properties.exitAnimation;
|
||||
if (exitAnimation) {
|
||||
domNode.style.pointerEvents = 'none';
|
||||
var removeDomNode = function () {
|
||||
if (domNode.parentNode) {
|
||||
domNode.parentNode.removeChild(domNode);
|
||||
}
|
||||
};
|
||||
if (typeof exitAnimation === 'function') {
|
||||
exitAnimation(domNode, removeDomNode, vNode.properties);
|
||||
return;
|
||||
} else {
|
||||
transitions.exit(vNode.domNode, vNode.properties, exitAnimation, removeDomNode);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (domNode.parentNode) {
|
||||
domNode.parentNode.removeChild(domNode);
|
||||
}
|
||||
};
|
||||
var checkDistinguishable = function (childNodes, indexToCheck, parentVNode, operation) {
|
||||
var childNode = childNodes[indexToCheck];
|
||||
if (childNode.vnodeSelector === '') {
|
||||
return; // Text nodes need not be distinguishable
|
||||
}
|
||||
var properties = childNode.properties;
|
||||
var key = properties ? properties.key === undefined ? properties.bind : properties.key : undefined;
|
||||
if (!key) {
|
||||
for (var i = 0; i < childNodes.length; i++) {
|
||||
if (i !== indexToCheck) {
|
||||
var node = childNodes[i];
|
||||
if (same(node, childNode)) {
|
||||
if (operation === 'added') {
|
||||
throw new Error(parentVNode.vnodeSelector + ' had a ' + childNode.vnodeSelector + ' child ' + 'added, but there is now more than one. You must add unique key properties to make them distinguishable.');
|
||||
} else {
|
||||
throw new Error(parentVNode.vnodeSelector + ' had a ' + childNode.vnodeSelector + ' child ' + 'removed, but there were more than one. You must add unique key properties to make them distinguishable.');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
var createDom;
|
||||
var updateDom;
|
||||
var updateChildren = function (vnode, domNode, oldChildren, newChildren, projectionOptions) {
|
||||
if (oldChildren === newChildren) {
|
||||
return false;
|
||||
}
|
||||
oldChildren = oldChildren || emptyArray;
|
||||
newChildren = newChildren || emptyArray;
|
||||
var oldChildrenLength = oldChildren.length;
|
||||
var newChildrenLength = newChildren.length;
|
||||
var transitions = projectionOptions.transitions;
|
||||
var oldIndex = 0;
|
||||
var newIndex = 0;
|
||||
var i;
|
||||
var textUpdated = false;
|
||||
while (newIndex < newChildrenLength) {
|
||||
var oldChild = oldIndex < oldChildrenLength ? oldChildren[oldIndex] : undefined;
|
||||
var newChild = newChildren[newIndex];
|
||||
if (oldChild !== undefined && same(oldChild, newChild)) {
|
||||
textUpdated = updateDom(oldChild, newChild, projectionOptions) || textUpdated;
|
||||
oldIndex++;
|
||||
} else {
|
||||
var findOldIndex = findIndexOfChild(oldChildren, newChild, oldIndex + 1);
|
||||
if (findOldIndex >= 0) {
|
||||
// Remove preceding missing children
|
||||
for (i = oldIndex; i < findOldIndex; i++) {
|
||||
nodeToRemove(oldChildren[i], transitions);
|
||||
checkDistinguishable(oldChildren, i, vnode, 'removed');
|
||||
}
|
||||
textUpdated = updateDom(oldChildren[findOldIndex], newChild, projectionOptions) || textUpdated;
|
||||
oldIndex = findOldIndex + 1;
|
||||
} else {
|
||||
// New child
|
||||
createDom(newChild, domNode, oldIndex < oldChildrenLength ? oldChildren[oldIndex].domNode : undefined, projectionOptions);
|
||||
nodeAdded(newChild, transitions);
|
||||
checkDistinguishable(newChildren, newIndex, vnode, 'added');
|
||||
}
|
||||
}
|
||||
newIndex++;
|
||||
}
|
||||
if (oldChildrenLength > oldIndex) {
|
||||
// Remove child fragments
|
||||
for (i = oldIndex; i < oldChildrenLength; i++) {
|
||||
nodeToRemove(oldChildren[i], transitions);
|
||||
checkDistinguishable(oldChildren, i, vnode, 'removed');
|
||||
}
|
||||
}
|
||||
return textUpdated;
|
||||
};
|
||||
var addChildren = function (domNode, children, projectionOptions) {
|
||||
if (!children) {
|
||||
return;
|
||||
}
|
||||
for (var i = 0; i < children.length; i++) {
|
||||
createDom(children[i], domNode, undefined, projectionOptions);
|
||||
}
|
||||
};
|
||||
var initPropertiesAndChildren = function (domNode, vnode, projectionOptions) {
|
||||
addChildren(domNode, vnode.children, projectionOptions);
|
||||
// children before properties, needed for value property of <select>.
|
||||
if (vnode.text) {
|
||||
domNode.textContent = vnode.text;
|
||||
}
|
||||
setProperties(domNode, vnode.properties, projectionOptions);
|
||||
if (vnode.properties && vnode.properties.afterCreate) {
|
||||
vnode.properties.afterCreate(domNode, projectionOptions, vnode.vnodeSelector, vnode.properties, vnode.children);
|
||||
}
|
||||
};
|
||||
createDom = function (vnode, parentNode, insertBefore, projectionOptions) {
|
||||
var domNode, i, c, start = 0, type, found;
|
||||
var vnodeSelector = vnode.vnodeSelector;
|
||||
if (vnodeSelector === '') {
|
||||
domNode = vnode.domNode = document.createTextNode(vnode.text);
|
||||
if (insertBefore !== undefined) {
|
||||
parentNode.insertBefore(domNode, insertBefore);
|
||||
} else {
|
||||
parentNode.appendChild(domNode);
|
||||
}
|
||||
} else {
|
||||
for (i = 0; i <= vnodeSelector.length; ++i) {
|
||||
c = vnodeSelector.charAt(i);
|
||||
if (i === vnodeSelector.length || c === '.' || c === '#') {
|
||||
type = vnodeSelector.charAt(start - 1);
|
||||
found = vnodeSelector.slice(start, i);
|
||||
if (type === '.') {
|
||||
domNode.classList.add(found);
|
||||
} else if (type === '#') {
|
||||
domNode.id = found;
|
||||
} else {
|
||||
if (found === 'svg') {
|
||||
projectionOptions = extend(projectionOptions, { namespace: NAMESPACE_SVG });
|
||||
}
|
||||
if (projectionOptions.namespace !== undefined) {
|
||||
domNode = vnode.domNode = document.createElementNS(projectionOptions.namespace, found);
|
||||
} else {
|
||||
domNode = vnode.domNode = document.createElement(found);
|
||||
}
|
||||
if (insertBefore !== undefined) {
|
||||
parentNode.insertBefore(domNode, insertBefore);
|
||||
} else {
|
||||
parentNode.appendChild(domNode);
|
||||
}
|
||||
}
|
||||
start = i + 1;
|
||||
}
|
||||
}
|
||||
initPropertiesAndChildren(domNode, vnode, projectionOptions);
|
||||
}
|
||||
};
|
||||
updateDom = function (previous, vnode, projectionOptions) {
|
||||
var domNode = previous.domNode;
|
||||
var textUpdated = false;
|
||||
if (previous === vnode) {
|
||||
return false; // By contract, VNode objects may not be modified anymore after passing them to maquette
|
||||
}
|
||||
var updated = false;
|
||||
if (vnode.vnodeSelector === '') {
|
||||
if (vnode.text !== previous.text) {
|
||||
var newVNode = document.createTextNode(vnode.text);
|
||||
domNode.parentNode.replaceChild(newVNode, domNode);
|
||||
vnode.domNode = newVNode;
|
||||
textUpdated = true;
|
||||
return textUpdated;
|
||||
}
|
||||
} else {
|
||||
if (vnode.vnodeSelector.lastIndexOf('svg', 0) === 0) {
|
||||
projectionOptions = extend(projectionOptions, { namespace: NAMESPACE_SVG });
|
||||
}
|
||||
if (previous.text !== vnode.text) {
|
||||
updated = true;
|
||||
if (vnode.text === undefined) {
|
||||
domNode.removeChild(domNode.firstChild); // the only textnode presumably
|
||||
} else {
|
||||
domNode.textContent = vnode.text;
|
||||
}
|
||||
}
|
||||
updated = updateChildren(vnode, domNode, previous.children, vnode.children, projectionOptions) || updated;
|
||||
updated = updateProperties(domNode, previous.properties, vnode.properties, projectionOptions) || updated;
|
||||
if (vnode.properties && vnode.properties.afterUpdate) {
|
||||
vnode.properties.afterUpdate(domNode, projectionOptions, vnode.vnodeSelector, vnode.properties, vnode.children);
|
||||
}
|
||||
}
|
||||
if (updated && vnode.properties && vnode.properties.updateAnimation) {
|
||||
vnode.properties.updateAnimation(domNode, vnode.properties, previous.properties);
|
||||
}
|
||||
vnode.domNode = previous.domNode;
|
||||
return textUpdated;
|
||||
};
|
||||
var createProjection = function (vnode, projectionOptions) {
|
||||
return {
|
||||
update: function (updatedVnode) {
|
||||
if (vnode.vnodeSelector !== updatedVnode.vnodeSelector) {
|
||||
throw new Error('The selector for the root VNode may not be changed. (consider using dom.merge and add one extra level to the virtual DOM)');
|
||||
}
|
||||
updateDom(vnode, updatedVnode, projectionOptions);
|
||||
vnode = updatedVnode;
|
||||
},
|
||||
domNode: vnode.domNode
|
||||
};
|
||||
};
|
||||
;
|
||||
// The other two parameters are not added here, because the Typescript compiler creates surrogate code for desctructuring 'children'.
|
||||
exports.h = function (selector) {
|
||||
var properties = arguments[1];
|
||||
if (typeof selector !== 'string') {
|
||||
throw new Error();
|
||||
}
|
||||
var childIndex = 1;
|
||||
if (properties && !properties.hasOwnProperty('vnodeSelector') && !Array.isArray(properties) && typeof properties === 'object') {
|
||||
childIndex = 2;
|
||||
} else {
|
||||
// Optional properties argument was omitted
|
||||
properties = undefined;
|
||||
}
|
||||
var text = undefined;
|
||||
var children = undefined;
|
||||
var argsLength = arguments.length;
|
||||
// Recognize a common special case where there is only a single text node
|
||||
if (argsLength === childIndex + 1) {
|
||||
var onlyChild = arguments[childIndex];
|
||||
if (typeof onlyChild === 'string') {
|
||||
text = onlyChild;
|
||||
} else if (onlyChild !== undefined && onlyChild.length === 1 && typeof onlyChild[0] === 'string') {
|
||||
text = onlyChild[0];
|
||||
}
|
||||
}
|
||||
if (text === undefined) {
|
||||
children = [];
|
||||
for (; childIndex < arguments.length; childIndex++) {
|
||||
var child = arguments[childIndex];
|
||||
if (child === null || child === undefined) {
|
||||
continue;
|
||||
} else if (Array.isArray(child)) {
|
||||
appendChildren(selector, child, children);
|
||||
} else if (child.hasOwnProperty('vnodeSelector')) {
|
||||
children.push(child);
|
||||
} else {
|
||||
children.push(toTextVNode(child));
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
vnodeSelector: selector,
|
||||
properties: properties,
|
||||
children: children,
|
||||
text: text === '' ? undefined : text,
|
||||
domNode: null
|
||||
};
|
||||
};
|
||||
/**
|
||||
* Contains simple low-level utility functions to manipulate the real DOM.
|
||||
*/
|
||||
exports.dom = {
|
||||
/**
|
||||
* Creates a real DOM tree from `vnode`. The [[Projection]] object returned will contain the resulting DOM Node in
|
||||
* its [[Projection.domNode|domNode]] property.
|
||||
* This is a low-level method. Users wil typically use a [[Projector]] instead.
|
||||
* @param vnode - The root of the virtual DOM tree that was created using the [[h]] function. NOTE: [[VNode]]
|
||||
* objects may only be rendered once.
|
||||
* @param projectionOptions - Options to be used to create and update the projection.
|
||||
* @returns The [[Projection]] which also contains the DOM Node that was created.
|
||||
*/
|
||||
create: function (vnode, projectionOptions) {
|
||||
projectionOptions = applyDefaultProjectionOptions(projectionOptions);
|
||||
createDom(vnode, document.createElement('div'), undefined, projectionOptions);
|
||||
return createProjection(vnode, projectionOptions);
|
||||
},
|
||||
/**
|
||||
* Appends a new childnode to the DOM which is generated from a [[VNode]].
|
||||
* This is a low-level method. Users wil typically use a [[Projector]] instead.
|
||||
* @param parentNode - The parent node for the new childNode.
|
||||
* @param vnode - The root of the virtual DOM tree that was created using the [[h]] function. NOTE: [[VNode]]
|
||||
* objects may only be rendered once.
|
||||
* @param projectionOptions - Options to be used to create and update the [[Projection]].
|
||||
* @returns The [[Projection]] that was created.
|
||||
*/
|
||||
append: function (parentNode, vnode, projectionOptions) {
|
||||
projectionOptions = applyDefaultProjectionOptions(projectionOptions);
|
||||
createDom(vnode, parentNode, undefined, projectionOptions);
|
||||
return createProjection(vnode, projectionOptions);
|
||||
},
|
||||
/**
|
||||
* Inserts a new DOM node which is generated from a [[VNode]].
|
||||
* This is a low-level method. Users wil typically use a [[Projector]] instead.
|
||||
* @param beforeNode - The node that the DOM Node is inserted before.
|
||||
* @param vnode - The root of the virtual DOM tree that was created using the [[h]] function.
|
||||
* NOTE: [[VNode]] objects may only be rendered once.
|
||||
* @param projectionOptions - Options to be used to create and update the projection, see [[createProjector]].
|
||||
* @returns The [[Projection]] that was created.
|
||||
*/
|
||||
insertBefore: function (beforeNode, vnode, projectionOptions) {
|
||||
projectionOptions = applyDefaultProjectionOptions(projectionOptions);
|
||||
createDom(vnode, beforeNode.parentNode, beforeNode, projectionOptions);
|
||||
return createProjection(vnode, projectionOptions);
|
||||
},
|
||||
/**
|
||||
* Merges a new DOM node which is generated from a [[VNode]] with an existing DOM Node.
|
||||
* This means that the virtual DOM and the real DOM will have one overlapping element.
|
||||
* Therefore the selector for the root [[VNode]] will be ignored, but its properties and children will be applied to the Element provided.
|
||||
* This is a low-level method. Users wil typically use a [[Projector]] instead.
|
||||
* @param domNode - The existing element to adopt as the root of the new virtual DOM. Existing attributes and childnodes are preserved.
|
||||
* @param vnode - The root of the virtual DOM tree that was created using the [[h]] function. NOTE: [[VNode]] objects
|
||||
* may only be rendered once.
|
||||
* @param projectionOptions - Options to be used to create and update the projection, see [[createProjector]].
|
||||
* @returns The [[Projection]] that was created.
|
||||
*/
|
||||
merge: function (element, vnode, projectionOptions) {
|
||||
projectionOptions = applyDefaultProjectionOptions(projectionOptions);
|
||||
vnode.domNode = element;
|
||||
initPropertiesAndChildren(element, vnode, projectionOptions);
|
||||
return createProjection(vnode, projectionOptions);
|
||||
}
|
||||
};
|
||||
/**
|
||||
* Creates a [[CalculationCache]] object, useful for caching [[VNode]] trees.
|
||||
* In practice, caching of [[VNode]] trees is not needed, because achieving 60 frames per second is almost never a problem.
|
||||
* For more information, see [[CalculationCache]].
|
||||
*
|
||||
* @param <Result> The type of the value that is cached.
|
||||
*/
|
||||
exports.createCache = function () {
|
||||
var cachedInputs = undefined;
|
||||
var cachedOutcome = undefined;
|
||||
var result = {
|
||||
invalidate: function () {
|
||||
cachedOutcome = undefined;
|
||||
cachedInputs = undefined;
|
||||
},
|
||||
result: function (inputs, calculation) {
|
||||
if (cachedInputs) {
|
||||
for (var i = 0; i < inputs.length; i++) {
|
||||
if (cachedInputs[i] !== inputs[i]) {
|
||||
cachedOutcome = undefined;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!cachedOutcome) {
|
||||
cachedOutcome = calculation();
|
||||
cachedInputs = inputs;
|
||||
}
|
||||
return cachedOutcome;
|
||||
}
|
||||
};
|
||||
return result;
|
||||
};
|
||||
/**
|
||||
* Creates a {@link Mapping} instance that keeps an array of result objects synchronized with an array of source objects.
|
||||
* See {@link http://maquettejs.org/docs/arrays.html|Working with arrays}.
|
||||
*
|
||||
* @param <Source> The type of source items. A database-record for instance.
|
||||
* @param <Target> The type of target items. A [[Component]] for instance.
|
||||
* @param getSourceKey `function(source)` that must return a key to identify each source object. The result must either be a string or a number.
|
||||
* @param createResult `function(source, index)` that must create a new result object from a given source. This function is identical
|
||||
* to the `callback` argument in `Array.map(callback)`.
|
||||
* @param updateResult `function(source, target, index)` that updates a result to an updated source.
|
||||
*/
|
||||
exports.createMapping = function (getSourceKey, createResult, updateResult) {
|
||||
var keys = [];
|
||||
var results = [];
|
||||
return {
|
||||
results: results,
|
||||
map: function (newSources) {
|
||||
var newKeys = newSources.map(getSourceKey);
|
||||
var oldTargets = results.slice();
|
||||
var oldIndex = 0;
|
||||
for (var i = 0; i < newSources.length; i++) {
|
||||
var source = newSources[i];
|
||||
var sourceKey = newKeys[i];
|
||||
if (sourceKey === keys[oldIndex]) {
|
||||
results[i] = oldTargets[oldIndex];
|
||||
updateResult(source, oldTargets[oldIndex], i);
|
||||
oldIndex++;
|
||||
} else {
|
||||
var found = false;
|
||||
for (var j = 1; j < keys.length; j++) {
|
||||
var searchIndex = (oldIndex + j) % keys.length;
|
||||
if (keys[searchIndex] === sourceKey) {
|
||||
results[i] = oldTargets[searchIndex];
|
||||
updateResult(newSources[i], oldTargets[searchIndex], i);
|
||||
oldIndex = searchIndex + 1;
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
results[i] = createResult(source, i);
|
||||
}
|
||||
}
|
||||
}
|
||||
results.length = newSources.length;
|
||||
keys = newKeys;
|
||||
}
|
||||
};
|
||||
};
|
||||
/**
|
||||
* Creates a [[Projector]] instance using the provided projectionOptions.
|
||||
*
|
||||
* For more information, see [[Projector]].
|
||||
*
|
||||
* @param projectionOptions Options that influence how the DOM is rendered and updated.
|
||||
*/
|
||||
exports.createProjector = function (projectorOptions) {
|
||||
var projector;
|
||||
var projectionOptions = applyDefaultProjectionOptions(projectorOptions);
|
||||
projectionOptions.eventHandlerInterceptor = function (propertyName, eventHandler, domNode, properties) {
|
||||
return function () {
|
||||
// intercept function calls (event handlers) to do a render afterwards.
|
||||
projector.scheduleRender();
|
||||
return eventHandler.apply(properties.bind || this, arguments);
|
||||
};
|
||||
};
|
||||
var renderCompleted = true;
|
||||
var scheduled;
|
||||
var stopped = false;
|
||||
var projections = [];
|
||||
var renderFunctions = [];
|
||||
// matches the projections array
|
||||
var doRender = function () {
|
||||
scheduled = undefined;
|
||||
if (!renderCompleted) {
|
||||
return; // The last render threw an error, it should be logged in the browser console.
|
||||
}
|
||||
renderCompleted = false;
|
||||
for (var i = 0; i < projections.length; i++) {
|
||||
var updatedVnode = renderFunctions[i]();
|
||||
projections[i].update(updatedVnode);
|
||||
}
|
||||
renderCompleted = true;
|
||||
};
|
||||
projector = {
|
||||
scheduleRender: function () {
|
||||
if (!scheduled && !stopped) {
|
||||
scheduled = requestAnimationFrame(doRender);
|
||||
}
|
||||
},
|
||||
stop: function () {
|
||||
if (scheduled) {
|
||||
cancelAnimationFrame(scheduled);
|
||||
scheduled = undefined;
|
||||
}
|
||||
stopped = true;
|
||||
},
|
||||
resume: function () {
|
||||
stopped = false;
|
||||
renderCompleted = true;
|
||||
projector.scheduleRender();
|
||||
},
|
||||
append: function (parentNode, renderMaquetteFunction) {
|
||||
projections.push(exports.dom.append(parentNode, renderMaquetteFunction(), projectionOptions));
|
||||
renderFunctions.push(renderMaquetteFunction);
|
||||
},
|
||||
insertBefore: function (beforeNode, renderMaquetteFunction) {
|
||||
projections.push(exports.dom.insertBefore(beforeNode, renderMaquetteFunction(), projectionOptions));
|
||||
renderFunctions.push(renderMaquetteFunction);
|
||||
},
|
||||
merge: function (domNode, renderMaquetteFunction) {
|
||||
projections.push(exports.dom.merge(domNode, renderMaquetteFunction(), projectionOptions));
|
||||
renderFunctions.push(renderMaquetteFunction);
|
||||
},
|
||||
replace: function (domNode, renderMaquetteFunction) {
|
||||
var vnode = renderMaquetteFunction();
|
||||
createDom(vnode, domNode.parentNode, domNode, projectionOptions);
|
||||
domNode.parentNode.removeChild(domNode);
|
||||
projections.push(createProjection(vnode, projectionOptions));
|
||||
renderFunctions.push(renderMaquetteFunction);
|
||||
},
|
||||
detach: function (renderMaquetteFunction) {
|
||||
for (var i = 0; i < renderFunctions.length; i++) {
|
||||
if (renderFunctions[i] === renderMaquetteFunction) {
|
||||
renderFunctions.splice(i, 1);
|
||||
return projections.splice(i, 1)[0];
|
||||
}
|
||||
}
|
||||
throw new Error('renderMaquetteFunction was not found');
|
||||
}
|
||||
};
|
||||
return projector;
|
||||
};
|
||||
}));
|
Loading…
Add table
Add a link
Reference in a new issue