for.js 11 KB

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