for.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  1. var _ = require('../util')
  2. var FragmentFactory = require('../fragment/factory')
  3. var isObject = _.isObject
  4. var uid = 0
  5. // TODO: ref, el
  6. module.exports = {
  7. bind: function () {
  8. // support "item in items" syntax
  9. var inMatch = this.expression.match(/(.*) in (.*)/)
  10. if (inMatch) {
  11. this.alias = inMatch[1]
  12. this._watcherExp = inMatch[2]
  13. } else {
  14. process.env.NODE_ENV !== 'production' && _.warn(
  15. 'Alias is required in v-for.'
  16. )
  17. return
  18. }
  19. // uid as a cache identifier
  20. this.id = '__v-for__' + (++uid)
  21. // setup anchor nodes
  22. this.start = _.createAnchor('v-repeat-start')
  23. this.end = _.createAnchor('v-repeat-end')
  24. _.replace(this.el, this.end)
  25. _.before(this.start, this.end)
  26. // check for trackby param
  27. this.idKey = this._checkParam('track-by')
  28. // check for transition stagger
  29. var stagger = +this._checkParam('stagger')
  30. this.enterStagger = +this._checkParam('enter-stagger') || stagger
  31. this.leaveStagger = +this._checkParam('leave-stagger') || stagger
  32. // cache
  33. this.cache = Object.create(null)
  34. // fragment factory
  35. this.factory = new FragmentFactory(this.vm, this.el)
  36. },
  37. create: function (value, alias, index, key) {
  38. var host = this._host
  39. // create iteration scope
  40. var parentScope = this._scope || this.vm
  41. var scope = Object.create(parentScope)
  42. // define scope properties
  43. _.defineReactive(scope, alias, value)
  44. _.defineReactive(scope, '$index', index)
  45. if (key) {
  46. _.defineReactive(scope, '$key', key)
  47. }
  48. var frag = this.factory.create(host, scope, this.id)
  49. this.cacheFrag(value, frag, index, key)
  50. return frag
  51. },
  52. update: function (data) {
  53. var self = this
  54. var idKey = this.idKey
  55. var converted = this.converted
  56. var oldFrags = this.frags
  57. var frags = this.frags = new Array(data.length)
  58. var alias = this.alias
  59. var start = this.start
  60. var end = this.end
  61. var inDoc = _.inDoc(start)
  62. var init = !oldFrags
  63. var i, l, frag, item, key, value, primitive
  64. // First pass, go through the new Array and fill up
  65. // the new frags array. If a piece of data has a cached
  66. // instance for it, we reuse it. Otherwise build a new
  67. // instance.
  68. for (i = 0, l = data.length; i < l; i++) {
  69. item = data[i]
  70. key = converted ? itme.$key : null
  71. value = converted ? item.$value : item
  72. frag = !init && this.getCachedFrag(value, i, key)
  73. if (frag) { // reusable fragment
  74. frag.reused = true
  75. frag.scope.$index = i // update $index
  76. // update data for track-by, object repeat &
  77. // primitive values.
  78. if (idKey || converted || primitive) {
  79. frag.scope[alias] = value
  80. }
  81. } else { // new isntance
  82. frag = this.create(value, alias, i, key)
  83. }
  84. frags[i] = frag
  85. if (init) {
  86. frag.before(end)
  87. }
  88. }
  89. // we're done for the initial render.
  90. if (init) {
  91. return
  92. }
  93. // Second pass, go through the old fragments and
  94. // destroy those who are not reused (and remove them
  95. // from cache)
  96. var removalIndex = 0
  97. var totalRemoved = oldFrags.length - frags.length
  98. for (i = 0, l = oldFrags.length; i < l; i++) {
  99. frag = oldFrags[i]
  100. if (!frag.reused) {
  101. this.deleteCachedFrag(frag)
  102. frag.unlink()
  103. this.remove(frag, removalIndex++, totalRemoved, inDoc)
  104. }
  105. }
  106. // Final pass, move/insert new fragments into the
  107. // right place.
  108. var targetPrev, prevEl, currentPrev
  109. var insertionIndex = 0
  110. for (i = 0, l = frags.length; i < l; i++) {
  111. frag = frags[i]
  112. // this is the frag that we should be after
  113. targetPrev = frags[i - 1]
  114. prevEl = targetPrev
  115. ? targetPrev.staggerCb
  116. ? targetPrev.staggerAnchor
  117. : targetPrev.end || targetPrev.node
  118. : start
  119. if (frag.reused && !frag.staggerCb) {
  120. currentPrev = findPrevFrag(frag, start, this.id)
  121. if (currentPrev !== targetPrev) {
  122. this.move(frag, prevEl)
  123. }
  124. } else {
  125. // new instance, or still in stagger.
  126. // insert with updated stagger index.
  127. this.insert(frag, insertionIndex++, prevEl, inDoc)
  128. }
  129. frag.reused = false
  130. }
  131. },
  132. insert: function (frag, index, prevEl, inDoc) {
  133. if (frag.staggerCb) {
  134. frag.staggerCb.cancel()
  135. frag.staggerCb = null
  136. }
  137. var staggerAmount = this.getStagger(frag, index, null, 'enter')
  138. if (inDoc && staggerAmount) {
  139. // create an anchor and insert it synchronously,
  140. // so that we can resolve the correct order without
  141. // worrying about some elements not inserted yet
  142. var anchor = frag.staggerAnchor
  143. if (!anchor) {
  144. anchor = frag.staggerAnchor = _.createAnchor('stagger-anchor')
  145. anchor.__vfrag__ = frag
  146. }
  147. _.after(anchor, prevEl)
  148. var op = frag.staggerCb = _.cancellable(function () {
  149. frag.staggerCb = null
  150. frag.before(anchor)
  151. _.remove(anchor)
  152. })
  153. setTimeout(op, staggerAmount)
  154. } else {
  155. frag.before(prevEl.nextSibling)
  156. }
  157. },
  158. remove: function (frag, index, total, inDoc) {
  159. if (frag.staggerCb) {
  160. frag.staggerCb.cancel()
  161. frag.staggerCb = null
  162. // it's not possible for the same frag to be removed
  163. // twice, so if we have a pending stagger callback,
  164. // it means this frag is queued for enter but removed
  165. // before its transition started. Since it is already
  166. // destroyed, we can just leave it in detached state.
  167. return
  168. }
  169. var staggerAmount = this.getStagger(frag, index, total, 'leave')
  170. if (inDoc && staggerAmount) {
  171. var op = frag.staggerCb = _.cancellable(function () {
  172. frag.staggerCb = null
  173. frag.remove()
  174. })
  175. setTimeout(op, staggerAmount)
  176. } else {
  177. frag.remove()
  178. }
  179. },
  180. move: function (frag, prevEl) {
  181. frag.before(prevEl.nextSibling)
  182. },
  183. cacheFrag: function (value, frag, index, key) {
  184. var idKey = this.idKey
  185. var cache = this.cache
  186. var primitive = !isObject(value)
  187. var id
  188. if (key || idKey || primitive) {
  189. id = idKey
  190. ? idKey === '$index'
  191. ? index
  192. : value[idKey]
  193. : (key || index)
  194. if (!cache[id]) {
  195. cache[id] = frag
  196. } else if (!primitive && idKey !== '$index') {
  197. process.env.NODE_ENV !== 'production' && _.warn(
  198. 'Duplicate track-by key in v-repeat: ' + id
  199. )
  200. }
  201. } else {
  202. id = this.id
  203. if (value.hasOwnProperty(id)) {
  204. if (value[id] === null) {
  205. value[id] = frag
  206. } else {
  207. process.env.NODE_ENV !== 'production' && _.warn(
  208. 'Duplicate objects are not supported in v-repeat ' +
  209. 'when using components or transitions.'
  210. )
  211. }
  212. } else {
  213. _.define(value, id, frag)
  214. }
  215. }
  216. frag.raw = value
  217. },
  218. getCachedFrag: function (value, index, key) {
  219. var idKey = this.idKey
  220. var primitive = !isObject(value)
  221. if (key || idKey || primitive) {
  222. var id = idKey
  223. ? idKey === '$index'
  224. ? index
  225. : value[idKey]
  226. : (key || index)
  227. return this.cache[id]
  228. } else {
  229. return value[this.id]
  230. }
  231. },
  232. deleteCachedFrag: function (frag) {
  233. var value = frag.raw
  234. var idKey = this.idKey
  235. var scope = frag.scope
  236. var index = scope.$index
  237. // fix #948: avoid accidentally fall through to
  238. // a parent repeater which happens to have $key.
  239. var key = scope.hasOwnProperty('$key') && scope.$key
  240. var primitive = !isObject(value)
  241. if (idKey || key || primitive) {
  242. var id = idKey
  243. ? idKey === '$index'
  244. ? index
  245. : value[idKey]
  246. : (key || index)
  247. this.cache[id] = null
  248. } else {
  249. value[this.id] = null
  250. frag.raw = null
  251. }
  252. },
  253. /**
  254. * Get the stagger amount for an insertion/removal.
  255. *
  256. * @param {Fragment} frag
  257. * @param {Number} index
  258. * @param {Number} total
  259. * @param {String} type
  260. */
  261. getStagger: function (frag, index, total, type) {
  262. type = type + 'Stagger'
  263. var transition = frag.node.__v_trans
  264. var hooks = transition && transition.hooks
  265. var hook = hooks && (hooks[type] || hooks.stagger)
  266. return hook
  267. ? hook.call(frag, index, total)
  268. : index * this[type]
  269. },
  270. /**
  271. * Pre-process the value before piping it through the
  272. * filters, and convert non-Array objects to arrays.
  273. *
  274. * This function will be bound to this directive instance
  275. * and passed into the watcher.
  276. *
  277. * @param {*} value
  278. * @return {Array}
  279. * @private
  280. */
  281. _preProcess: function (value) {
  282. // regardless of type, store the un-filtered raw value.
  283. this.rawValue = value
  284. var type = this.rawType = typeof value
  285. if (!_.isPlainObject(value)) {
  286. this.converted = false
  287. if (type === 'number') {
  288. value = range(value)
  289. } else if (type === 'string') {
  290. value = _.toArray(value)
  291. }
  292. return value || []
  293. } else {
  294. // convert plain object to array.
  295. var keys = Object.keys(value)
  296. var i = keys.length
  297. var res = new Array(i)
  298. var key
  299. while (i--) {
  300. key = keys[i]
  301. res[i] = {
  302. $key: key,
  303. $value: value[key]
  304. }
  305. }
  306. this.converted = true
  307. return res
  308. }
  309. }
  310. }
  311. /**
  312. * Helper to find the previous element that is a fragment
  313. * anchor. This is necessary because a destroyed frag's
  314. * element could still be lingering in the DOM before its
  315. * leaving transition finishes, but its __vue__ reference
  316. * should have been removed so we can skip them.
  317. *
  318. * If this is a block repeat, we want to make sure we only
  319. * return frag that is bound to this v-repeat. (see #929)
  320. *
  321. * @param {Fragment} frag
  322. * @param {Comment|Text} anchor
  323. * @param {String} id
  324. * @return {Fragment}
  325. */
  326. function findPrevFrag (frag, anchor, id) {
  327. var el = frag.node.previousSibling
  328. /* istanbul ignore if */
  329. if (!el) return
  330. while (
  331. (!el.__vfrag__ || el.__vfrag__.id !== id) &&
  332. el !== anchor
  333. ) {
  334. el = el.previousSibling
  335. }
  336. return el.__vfrag__
  337. }