index.js 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. /**
  2. * Copyright (c) 2014-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. /**
  8. * Cursor is expected to be required in a node or other CommonJS context:
  9. *
  10. * var Cursor = require('immutable/contrib/cursor');
  11. *
  12. * If you wish to use it in the browser, please check out Browserify or WebPack!
  13. */
  14. var Immutable = require('../../');
  15. var Iterable = Immutable.Iterable;
  16. var Iterator = Iterable.Iterator;
  17. var Seq = Immutable.Seq;
  18. var Map = Immutable.Map;
  19. var Record = Immutable.Record;
  20. function cursorFrom(rootData, keyPath, onChange) {
  21. if (arguments.length === 1) {
  22. keyPath = [];
  23. } else if (typeof keyPath === 'function') {
  24. onChange = keyPath;
  25. keyPath = [];
  26. } else {
  27. keyPath = valToKeyPath(keyPath);
  28. }
  29. return makeCursor(rootData, keyPath, onChange);
  30. }
  31. var KeyedCursorPrototype = Object.create(Seq.Keyed.prototype);
  32. var IndexedCursorPrototype = Object.create(Seq.Indexed.prototype);
  33. function KeyedCursor(rootData, keyPath, onChange, size) {
  34. this.size = size;
  35. this._rootData = rootData;
  36. this._keyPath = keyPath;
  37. this._onChange = onChange;
  38. }
  39. KeyedCursorPrototype.constructor = KeyedCursor;
  40. function IndexedCursor(rootData, keyPath, onChange, size) {
  41. this.size = size;
  42. this._rootData = rootData;
  43. this._keyPath = keyPath;
  44. this._onChange = onChange;
  45. }
  46. IndexedCursorPrototype.constructor = IndexedCursor;
  47. KeyedCursorPrototype.toString = function() {
  48. return this.__toString('Cursor {', '}');
  49. }
  50. IndexedCursorPrototype.toString = function() {
  51. return this.__toString('Cursor [', ']');
  52. }
  53. KeyedCursorPrototype.deref =
  54. KeyedCursorPrototype.valueOf =
  55. IndexedCursorPrototype.deref =
  56. IndexedCursorPrototype.valueOf = function(notSetValue) {
  57. return this._rootData.getIn(this._keyPath, notSetValue);
  58. }
  59. KeyedCursorPrototype.get =
  60. IndexedCursorPrototype.get = function(key, notSetValue) {
  61. return this.getIn([key], notSetValue);
  62. }
  63. KeyedCursorPrototype.getIn =
  64. IndexedCursorPrototype.getIn = function(keyPath, notSetValue) {
  65. keyPath = listToKeyPath(keyPath);
  66. if (keyPath.length === 0) {
  67. return this;
  68. }
  69. var value = this._rootData.getIn(newKeyPath(this._keyPath, keyPath), NOT_SET);
  70. return value === NOT_SET ? notSetValue : wrappedValue(this, keyPath, value);
  71. }
  72. IndexedCursorPrototype.set =
  73. KeyedCursorPrototype.set = function(key, value) {
  74. if(arguments.length === 1) {
  75. return updateCursor(this, function() { return key; }, []);
  76. } else {
  77. return updateCursor(this, function (m) { return m.set(key, value); }, [key]);
  78. }
  79. }
  80. IndexedCursorPrototype.push = function(/* values */) {
  81. var args = arguments;
  82. return updateCursor(this, function (m) {
  83. return m.push.apply(m, args);
  84. });
  85. }
  86. IndexedCursorPrototype.pop = function() {
  87. return updateCursor(this, function (m) {
  88. return m.pop();
  89. });
  90. }
  91. IndexedCursorPrototype.unshift = function(/* values */) {
  92. var args = arguments;
  93. return updateCursor(this, function (m) {
  94. return m.unshift.apply(m, args);
  95. });
  96. }
  97. IndexedCursorPrototype.shift = function() {
  98. return updateCursor(this, function (m) {
  99. return m.shift();
  100. });
  101. }
  102. IndexedCursorPrototype.setIn =
  103. KeyedCursorPrototype.setIn = Map.prototype.setIn;
  104. KeyedCursorPrototype.remove =
  105. KeyedCursorPrototype['delete'] =
  106. IndexedCursorPrototype.remove =
  107. IndexedCursorPrototype['delete'] = function(key) {
  108. return updateCursor(this, function (m) { return m.remove(key); }, [key]);
  109. }
  110. IndexedCursorPrototype.removeIn =
  111. IndexedCursorPrototype.deleteIn =
  112. KeyedCursorPrototype.removeIn =
  113. KeyedCursorPrototype.deleteIn = Map.prototype.deleteIn;
  114. KeyedCursorPrototype.clear =
  115. IndexedCursorPrototype.clear = function() {
  116. return updateCursor(this, function (m) { return m.clear(); });
  117. }
  118. IndexedCursorPrototype.update =
  119. KeyedCursorPrototype.update = function(keyOrFn, notSetValue, updater) {
  120. return arguments.length === 1 ?
  121. updateCursor(this, keyOrFn) :
  122. this.updateIn([keyOrFn], notSetValue, updater);
  123. }
  124. IndexedCursorPrototype.updateIn =
  125. KeyedCursorPrototype.updateIn = function(keyPath, notSetValue, updater) {
  126. return updateCursor(this, function (m) {
  127. return m.updateIn(keyPath, notSetValue, updater);
  128. }, keyPath);
  129. }
  130. IndexedCursorPrototype.merge =
  131. KeyedCursorPrototype.merge = function(/*...iters*/) {
  132. var args = arguments;
  133. return updateCursor(this, function (m) {
  134. return m.merge.apply(m, args);
  135. });
  136. }
  137. IndexedCursorPrototype.mergeWith =
  138. KeyedCursorPrototype.mergeWith = function(merger/*, ...iters*/) {
  139. var args = arguments;
  140. return updateCursor(this, function (m) {
  141. return m.mergeWith.apply(m, args);
  142. });
  143. }
  144. IndexedCursorPrototype.mergeIn =
  145. KeyedCursorPrototype.mergeIn = Map.prototype.mergeIn;
  146. IndexedCursorPrototype.mergeDeep =
  147. KeyedCursorPrototype.mergeDeep = function(/*...iters*/) {
  148. var args = arguments;
  149. return updateCursor(this, function (m) {
  150. return m.mergeDeep.apply(m, args);
  151. });
  152. }
  153. IndexedCursorPrototype.mergeDeepWith =
  154. KeyedCursorPrototype.mergeDeepWith = function(merger/*, ...iters*/) {
  155. var args = arguments;
  156. return updateCursor(this, function (m) {
  157. return m.mergeDeepWith.apply(m, args);
  158. });
  159. }
  160. IndexedCursorPrototype.mergeDeepIn =
  161. KeyedCursorPrototype.mergeDeepIn = Map.prototype.mergeDeepIn;
  162. KeyedCursorPrototype.withMutations =
  163. IndexedCursorPrototype.withMutations = function(fn) {
  164. return updateCursor(this, function (m) {
  165. return (m || Map()).withMutations(fn);
  166. });
  167. }
  168. KeyedCursorPrototype.cursor =
  169. IndexedCursorPrototype.cursor = function(subKeyPath) {
  170. subKeyPath = valToKeyPath(subKeyPath);
  171. return subKeyPath.length === 0 ? this : subCursor(this, subKeyPath);
  172. }
  173. /**
  174. * All iterables need to implement __iterate
  175. */
  176. KeyedCursorPrototype.__iterate =
  177. IndexedCursorPrototype.__iterate = function(fn, reverse) {
  178. var cursor = this;
  179. var deref = cursor.deref();
  180. return deref && deref.__iterate ? deref.__iterate(
  181. function (v, k) { return fn(wrappedValue(cursor, [k], v), k, cursor); },
  182. reverse
  183. ) : 0;
  184. }
  185. /**
  186. * All iterables need to implement __iterator
  187. */
  188. KeyedCursorPrototype.__iterator =
  189. IndexedCursorPrototype.__iterator = function(type, reverse) {
  190. var deref = this.deref();
  191. var cursor = this;
  192. var iterator = deref && deref.__iterator &&
  193. deref.__iterator(Iterator.ENTRIES, reverse);
  194. return new Iterator(function () {
  195. if (!iterator) {
  196. return { value: undefined, done: true };
  197. }
  198. var step = iterator.next();
  199. if (step.done) {
  200. return step;
  201. }
  202. var entry = step.value;
  203. var k = entry[0];
  204. var v = wrappedValue(cursor, [k], entry[1]);
  205. return {
  206. value: type === Iterator.KEYS ? k : type === Iterator.VALUES ? v : [k, v],
  207. done: false
  208. };
  209. });
  210. }
  211. KeyedCursor.prototype = KeyedCursorPrototype;
  212. IndexedCursor.prototype = IndexedCursorPrototype;
  213. var NOT_SET = {}; // Sentinel value
  214. function makeCursor(rootData, keyPath, onChange, value) {
  215. if (arguments.length < 4) {
  216. value = rootData.getIn(keyPath);
  217. }
  218. var size = value && value.size;
  219. var CursorClass = Iterable.isIndexed(value) ? IndexedCursor : KeyedCursor;
  220. var cursor = new CursorClass(rootData, keyPath, onChange, size);
  221. if (value instanceof Record) {
  222. defineRecordProperties(cursor, value);
  223. }
  224. return cursor;
  225. }
  226. function defineRecordProperties(cursor, value) {
  227. try {
  228. value._keys.forEach(setProp.bind(undefined, cursor));
  229. } catch (error) {
  230. // Object.defineProperty failed. Probably IE8.
  231. }
  232. }
  233. function setProp(prototype, name) {
  234. Object.defineProperty(prototype, name, {
  235. get: function() {
  236. return this.get(name);
  237. },
  238. set: function(value) {
  239. if (!this.__ownerID) {
  240. throw new Error('Cannot set on an immutable record.');
  241. }
  242. }
  243. });
  244. }
  245. function wrappedValue(cursor, keyPath, value) {
  246. return Iterable.isIterable(value) ? subCursor(cursor, keyPath, value) : value;
  247. }
  248. function subCursor(cursor, keyPath, value) {
  249. if (arguments.length < 3) {
  250. return makeCursor( // call without value
  251. cursor._rootData,
  252. newKeyPath(cursor._keyPath, keyPath),
  253. cursor._onChange
  254. );
  255. }
  256. return makeCursor(
  257. cursor._rootData,
  258. newKeyPath(cursor._keyPath, keyPath),
  259. cursor._onChange,
  260. value
  261. );
  262. }
  263. function updateCursor(cursor, changeFn, changeKeyPath) {
  264. var deepChange = arguments.length > 2;
  265. var newRootData = cursor._rootData.updateIn(
  266. cursor._keyPath,
  267. deepChange ? Map() : undefined,
  268. changeFn
  269. );
  270. var keyPath = cursor._keyPath || [];
  271. var result = cursor._onChange && cursor._onChange.call(
  272. undefined,
  273. newRootData,
  274. cursor._rootData,
  275. deepChange ? newKeyPath(keyPath, changeKeyPath) : keyPath
  276. );
  277. if (result !== undefined) {
  278. newRootData = result;
  279. }
  280. return makeCursor(newRootData, cursor._keyPath, cursor._onChange);
  281. }
  282. function newKeyPath(head, tail) {
  283. return head.concat(listToKeyPath(tail));
  284. }
  285. function listToKeyPath(list) {
  286. return Array.isArray(list) ? list : Immutable.Iterable(list).toArray();
  287. }
  288. function valToKeyPath(val) {
  289. return Array.isArray(val) ? val :
  290. Iterable.isIterable(val) ? val.toArray() :
  291. [val];
  292. }
  293. exports.from = cursorFrom;