sharejs.js 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424
  1. import { generateSHA1Hash } from '../../shared/utils/sha1'
  2. import { debugging, debugConsole } from '@/utils/debugging'
  3. import getMeta from '@/utils/meta'
  4. var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
  5. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  6. var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
  7. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  8. /* eslint-disable
  9. camelcase,
  10. max-len,
  11. no-class-assign,
  12. no-return-assign,
  13. no-undef,
  14. no-unused-vars,
  15. no-use-before-define,
  16. standard/object-curly-even-spacing,
  17. */
  18. // TODO: This file was created by bulk-decaffeinate.
  19. // Fix any style issues and re-enable lint.
  20. /*
  21. * decaffeinate suggestions:
  22. * DS101: Remove unnecessary use of Array.from
  23. * DS102: Remove unnecessary code created because of implicit returns
  24. * DS205: Consider reworking code to avoid use of IIFEs
  25. * DS207: Consider shorter variations of null checks
  26. * Full docs: https://github.com/decaffeinate/decaffeinate/blob/master/docs/suggestions.md
  27. */
  28. export const { Doc } = (() => {
  29. var append = void 0,
  30. bootstrapTransform = void 0,
  31. exports = void 0,
  32. transformComponent = void 0;
  33. var WEB = true;
  34. window.sharejs = exports = {};
  35. var types = exports.types = {};
  36. // These methods let you build a transform function from a transformComponent function
  37. // for OT types like text and JSON in which operations are lists of components
  38. // and transforming them requires N^2 work.
  39. // Add transform and transformX functions for an OT type which has transformComponent defined.
  40. // transformComponent(destination array, component, other component, side)
  41. exports['_bt'] = bootstrapTransform = function bootstrapTransform(type, transformComponent, checkValidOp, append) {
  42. var _transformX = void 0;
  43. var transformComponentX = function transformComponentX(left, right, destLeft, destRight) {
  44. transformComponent(destLeft, left, right, 'left');
  45. return transformComponent(destRight, right, left, 'right');
  46. };
  47. // Transforms rightOp by leftOp. Returns ['rightOp', clientOp']
  48. type.transformX = type['transformX'] = _transformX = function transformX(leftOp, rightOp) {
  49. checkValidOp(leftOp);
  50. checkValidOp(rightOp);
  51. var newRightOp = [];
  52. var _iteratorNormalCompletion = true;
  53. var _didIteratorError = false;
  54. var _iteratorError = undefined;
  55. try {
  56. for (var _iterator = Array.from(rightOp)[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
  57. var rightComponent = _step.value;
  58. // Generate newLeftOp by composing leftOp by rightComponent
  59. var newLeftOp = [];
  60. var k = 0;
  61. while (k < leftOp.length) {
  62. var l;
  63. var nextC = [];
  64. transformComponentX(leftOp[k], rightComponent, newLeftOp, nextC);
  65. k++;
  66. if (nextC.length === 1) {
  67. rightComponent = nextC[0];
  68. } else if (nextC.length === 0) {
  69. var _iteratorNormalCompletion2 = true;
  70. var _didIteratorError2 = false;
  71. var _iteratorError2 = undefined;
  72. try {
  73. for (var _iterator2 = Array.from(leftOp.slice(k))[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
  74. l = _step2.value;
  75. append(newLeftOp, l);
  76. }
  77. } catch (err) {
  78. _didIteratorError2 = true;
  79. _iteratorError2 = err;
  80. } finally {
  81. try {
  82. if (!_iteratorNormalCompletion2 && _iterator2.return) {
  83. _iterator2.return();
  84. }
  85. } finally {
  86. if (_didIteratorError2) {
  87. throw _iteratorError2;
  88. }
  89. }
  90. }
  91. rightComponent = null;
  92. break;
  93. } else {
  94. // Recurse.
  95. var _Array$from = Array.from(_transformX(leftOp.slice(k), nextC)),
  96. _Array$from2 = _slicedToArray(_Array$from, 2),
  97. l_ = _Array$from2[0],
  98. r_ = _Array$from2[1];
  99. var _iteratorNormalCompletion3 = true;
  100. var _didIteratorError3 = false;
  101. var _iteratorError3 = undefined;
  102. try {
  103. for (var _iterator3 = Array.from(l_)[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
  104. l = _step3.value;
  105. append(newLeftOp, l);
  106. }
  107. } catch (err) {
  108. _didIteratorError3 = true;
  109. _iteratorError3 = err;
  110. } finally {
  111. try {
  112. if (!_iteratorNormalCompletion3 && _iterator3.return) {
  113. _iterator3.return();
  114. }
  115. } finally {
  116. if (_didIteratorError3) {
  117. throw _iteratorError3;
  118. }
  119. }
  120. }
  121. var _iteratorNormalCompletion4 = true;
  122. var _didIteratorError4 = false;
  123. var _iteratorError4 = undefined;
  124. try {
  125. for (var _iterator4 = Array.from(r_)[Symbol.iterator](), _step4; !(_iteratorNormalCompletion4 = (_step4 = _iterator4.next()).done); _iteratorNormalCompletion4 = true) {
  126. var r = _step4.value;
  127. append(newRightOp, r);
  128. }
  129. } catch (err) {
  130. _didIteratorError4 = true;
  131. _iteratorError4 = err;
  132. } finally {
  133. try {
  134. if (!_iteratorNormalCompletion4 && _iterator4.return) {
  135. _iterator4.return();
  136. }
  137. } finally {
  138. if (_didIteratorError4) {
  139. throw _iteratorError4;
  140. }
  141. }
  142. }
  143. rightComponent = null;
  144. break;
  145. }
  146. }
  147. if (rightComponent != null) {
  148. append(newRightOp, rightComponent);
  149. }
  150. leftOp = newLeftOp;
  151. }
  152. } catch (err) {
  153. _didIteratorError = true;
  154. _iteratorError = err;
  155. } finally {
  156. try {
  157. if (!_iteratorNormalCompletion && _iterator.return) {
  158. _iterator.return();
  159. }
  160. } finally {
  161. if (_didIteratorError) {
  162. throw _iteratorError;
  163. }
  164. }
  165. }
  166. return [leftOp, newRightOp];
  167. };
  168. // Transforms op with specified type ('left' or 'right') by otherOp.
  169. return type.transform = type['transform'] = function (op, otherOp, type) {
  170. var _ = void 0;
  171. if (type !== 'left' && type !== 'right') {
  172. throw new Error("type must be 'left' or 'right'");
  173. }
  174. if (otherOp.length === 0) {
  175. return op;
  176. }
  177. // TODO: Benchmark with and without this line. I _think_ it'll make a big difference...?
  178. if (op.length === 1 && otherOp.length === 1) {
  179. return transformComponent([], op[0], otherOp[0], type);
  180. }
  181. if (type === 'left') {
  182. var left = void 0;
  183. var _Array$from3 = Array.from(_transformX(op, otherOp));
  184. var _Array$from4 = _slicedToArray(_Array$from3, 2);
  185. left = _Array$from4[0];
  186. _ = _Array$from4[1];
  187. return left;
  188. } else {
  189. var right = void 0;
  190. var _Array$from5 = Array.from(_transformX(otherOp, op));
  191. var _Array$from6 = _slicedToArray(_Array$from5, 2);
  192. _ = _Array$from6[0];
  193. right = _Array$from6[1];
  194. return right;
  195. }
  196. };
  197. };
  198. // A simple text implementation
  199. //
  200. // Operations are lists of components.
  201. // Each component either inserts or deletes at a specified position in the document.
  202. //
  203. // Components are either:
  204. // {i:'str', p:100}: Insert 'str' at position 100 in the document
  205. // {d:'str', p:100}: Delete 'str' at position 100 in the document
  206. //
  207. // Components in an operation are executed sequentially, so the position of components
  208. // assumes previous components have already executed.
  209. //
  210. // Eg: This op:
  211. // [{i:'abc', p:0}]
  212. // is equivalent to this op:
  213. // [{i:'a', p:0}, {i:'b', p:1}, {i:'c', p:2}]
  214. // NOTE: The global scope here is shared with other sharejs files when built with closure.
  215. // Be careful what ends up in your namespace.
  216. var text = {};
  217. text.name = 'text';
  218. text.create = function () {
  219. return '';
  220. };
  221. var strInject = function strInject(s1, pos, s2) {
  222. return s1.slice(0, pos) + s2 + s1.slice(pos);
  223. };
  224. var checkValidComponent = function checkValidComponent(c) {
  225. if (typeof c.p !== 'number') {
  226. throw new Error('component missing position field');
  227. }
  228. var i_type = _typeof(c.i);
  229. var d_type = _typeof(c.d);
  230. var c_type = _typeof(c.c);
  231. if (!(i_type === 'string' ^ d_type === 'string' ^ c_type === 'string')) {
  232. throw new Error('component needs an i, d or c field');
  233. }
  234. if (!(c.p >= 0)) {
  235. throw new Error('position cannot be negative');
  236. }
  237. };
  238. var checkValidOp = function checkValidOp(op) {
  239. var _iteratorNormalCompletion5 = true;
  240. var _didIteratorError5 = false;
  241. var _iteratorError5 = undefined;
  242. try {
  243. for (var _iterator5 = Array.from(op)[Symbol.iterator](), _step5; !(_iteratorNormalCompletion5 = (_step5 = _iterator5.next()).done); _iteratorNormalCompletion5 = true) {
  244. var c = _step5.value;
  245. checkValidComponent(c);
  246. }
  247. } catch (err) {
  248. _didIteratorError5 = true;
  249. _iteratorError5 = err;
  250. } finally {
  251. try {
  252. if (!_iteratorNormalCompletion5 && _iterator5.return) {
  253. _iterator5.return();
  254. }
  255. } finally {
  256. if (_didIteratorError5) {
  257. throw _iteratorError5;
  258. }
  259. }
  260. }
  261. return true;
  262. };
  263. text.apply = function (snapshot, op) {
  264. checkValidOp(op);
  265. var _iteratorNormalCompletion6 = true;
  266. var _didIteratorError6 = false;
  267. var _iteratorError6 = undefined;
  268. try {
  269. for (var _iterator6 = Array.from(op)[Symbol.iterator](), _step6; !(_iteratorNormalCompletion6 = (_step6 = _iterator6.next()).done); _iteratorNormalCompletion6 = true) {
  270. var component = _step6.value;
  271. if (component.i != null) {
  272. snapshot = strInject(snapshot, component.p, component.i);
  273. } else if (component.d != null) {
  274. var deleted = snapshot.slice(component.p, component.p + component.d.length);
  275. if (component.d !== deleted) {
  276. throw new Error('Delete component \'' + component.d + '\' does not match deleted text \'' + deleted + '\'');
  277. }
  278. snapshot = snapshot.slice(0, component.p) + snapshot.slice(component.p + component.d.length);
  279. } else if (component.c != null) {
  280. var comment = snapshot.slice(component.p, component.p + component.c.length);
  281. if (component.c !== comment) {
  282. throw new Error('Comment component \'' + component.c + '\' does not match commented text \'' + comment + '\'');
  283. }
  284. } else {
  285. throw new Error('Unknown op type');
  286. }
  287. }
  288. } catch (err) {
  289. _didIteratorError6 = true;
  290. _iteratorError6 = err;
  291. } finally {
  292. try {
  293. if (!_iteratorNormalCompletion6 && _iterator6.return) {
  294. _iterator6.return();
  295. }
  296. } finally {
  297. if (_didIteratorError6) {
  298. throw _iteratorError6;
  299. }
  300. }
  301. }
  302. return snapshot;
  303. };
  304. var cloneAndModify = function cloneAndModify(op, modifications) {
  305. var v = void 0;
  306. var newOp = {};
  307. for (var k in op) {
  308. v = op[k];
  309. newOp[k] = v;
  310. }
  311. for (k in modifications) {
  312. v = modifications[k];
  313. newOp[k] = v;
  314. }
  315. return newOp;
  316. };
  317. // Exported for use by the random op generator.
  318. //
  319. // For simplicity, this version of append does not compress adjacent inserts and deletes of
  320. // the same text. It would be nice to change that at some stage.
  321. text._append = append = function append(newOp, c) {
  322. if (c.i === '' || c.d === '') {
  323. return;
  324. }
  325. if (newOp.length === 0) {
  326. return newOp.push(c);
  327. } else {
  328. var last = newOp[newOp.length - 1];
  329. // Compose the insert into the previous insert if possible
  330. if (last.i != null && c.i != null && last.p <= c.p && c.p <= last.p + last.i.length && last.u === c.u) {
  331. return newOp[newOp.length - 1] = cloneAndModify(last, { i: strInject(last.i, c.p - last.p, c.i) });
  332. } else if (last.d != null && c.d != null && c.p <= last.p && last.p <= c.p + c.d.length && last.u === c.u) {
  333. return newOp[newOp.length - 1] = cloneAndModify(last, { d: strInject(c.d, last.p - c.p, last.d), p: c.p });
  334. } else {
  335. return newOp.push(c);
  336. }
  337. }
  338. };
  339. text.compose = function (op1, op2) {
  340. checkValidOp(op1);
  341. checkValidOp(op2);
  342. var newOp = op1.slice();
  343. var _iteratorNormalCompletion7 = true;
  344. var _didIteratorError7 = false;
  345. var _iteratorError7 = undefined;
  346. try {
  347. for (var _iterator7 = Array.from(op2)[Symbol.iterator](), _step7; !(_iteratorNormalCompletion7 = (_step7 = _iterator7.next()).done); _iteratorNormalCompletion7 = true) {
  348. var c = _step7.value;
  349. append(newOp, c);
  350. }
  351. } catch (err) {
  352. _didIteratorError7 = true;
  353. _iteratorError7 = err;
  354. } finally {
  355. try {
  356. if (!_iteratorNormalCompletion7 && _iterator7.return) {
  357. _iterator7.return();
  358. }
  359. } finally {
  360. if (_didIteratorError7) {
  361. throw _iteratorError7;
  362. }
  363. }
  364. }
  365. return newOp;
  366. };
  367. // Attempt to compress the op components together 'as much as possible'.
  368. // This implementation preserves order and preserves create/delete pairs.
  369. text.compress = function (op) {
  370. return text.compose([], op);
  371. };
  372. text.normalize = function (op) {
  373. var newOp = [];
  374. // Normalize should allow ops which are a single (unwrapped) component:
  375. // {i:'asdf', p:23}.
  376. // There's no good way to test if something is an array:
  377. // http://perfectionkills.com/instanceof-considered-harmful-or-how-to-write-a-robust-isarray/
  378. // so this is probably the least bad solution.
  379. if (op.i != null || op.p != null) {
  380. op = [op];
  381. }
  382. var _iteratorNormalCompletion8 = true;
  383. var _didIteratorError8 = false;
  384. var _iteratorError8 = undefined;
  385. try {
  386. for (var _iterator8 = Array.from(op)[Symbol.iterator](), _step8; !(_iteratorNormalCompletion8 = (_step8 = _iterator8.next()).done); _iteratorNormalCompletion8 = true) {
  387. var c = _step8.value;
  388. if (c.p == null) {
  389. c.p = 0;
  390. }
  391. append(newOp, c);
  392. }
  393. } catch (err) {
  394. _didIteratorError8 = true;
  395. _iteratorError8 = err;
  396. } finally {
  397. try {
  398. if (!_iteratorNormalCompletion8 && _iterator8.return) {
  399. _iterator8.return();
  400. }
  401. } finally {
  402. if (_didIteratorError8) {
  403. throw _iteratorError8;
  404. }
  405. }
  406. }
  407. return newOp;
  408. };
  409. // This helper method transforms a position by an op component.
  410. //
  411. // If c is an insert, insertAfter specifies whether the transform
  412. // is pushed after the insert (true) or before it (false).
  413. //
  414. // insertAfter is optional for deletes.
  415. var transformPosition = function transformPosition(pos, c, insertAfter) {
  416. if (c.i != null) {
  417. if (c.p < pos || c.p === pos && insertAfter) {
  418. return pos + c.i.length;
  419. } else {
  420. return pos;
  421. }
  422. } else if (c.d != null) {
  423. // I think this could also be written as: Math.min(c.p, Math.min(c.p - otherC.p, otherC.d.length))
  424. // but I think its harder to read that way, and it compiles using ternary operators anyway
  425. // so its no slower written like this.
  426. if (pos <= c.p) {
  427. return pos;
  428. } else if (pos <= c.p + c.d.length) {
  429. return c.p;
  430. } else {
  431. return pos - c.d.length;
  432. }
  433. } else if (c.c != null) {
  434. return pos;
  435. } else {
  436. throw new Error('unknown op type');
  437. }
  438. };
  439. // Helper method to transform a cursor position as a result of an op.
  440. //
  441. // Like transformPosition above, if c is an insert, insertAfter specifies whether the cursor position
  442. // is pushed after an insert (true) or before it (false).
  443. text.transformCursor = function (position, op, side) {
  444. var insertAfter = side === 'right';
  445. var _iteratorNormalCompletion9 = true;
  446. var _didIteratorError9 = false;
  447. var _iteratorError9 = undefined;
  448. try {
  449. for (var _iterator9 = Array.from(op)[Symbol.iterator](), _step9; !(_iteratorNormalCompletion9 = (_step9 = _iterator9.next()).done); _iteratorNormalCompletion9 = true) {
  450. var c = _step9.value;
  451. position = transformPosition(position, c, insertAfter);
  452. }
  453. } catch (err) {
  454. _didIteratorError9 = true;
  455. _iteratorError9 = err;
  456. } finally {
  457. try {
  458. if (!_iteratorNormalCompletion9 && _iterator9.return) {
  459. _iterator9.return();
  460. }
  461. } finally {
  462. if (_didIteratorError9) {
  463. throw _iteratorError9;
  464. }
  465. }
  466. }
  467. return position;
  468. };
  469. // Transform an op component by another op component. Asymmetric.
  470. // The result will be appended to destination.
  471. //
  472. // exported for use in JSON type
  473. text._tc = transformComponent = function transformComponent(dest, c, otherC, side) {
  474. var cIntersect = void 0,
  475. intersectEnd = void 0,
  476. intersectStart = void 0,
  477. newC = void 0,
  478. otherIntersect = void 0;
  479. checkValidOp([c]);
  480. checkValidOp([otherC]);
  481. if (c.i != null) {
  482. append(dest, cloneAndModify(c, { p: transformPosition(c.p, otherC, side === 'right') }));
  483. } else if (c.d != null) {
  484. // Delete
  485. if (otherC.i != null) {
  486. // delete vs insert
  487. var s = c.d;
  488. if (c.p < otherC.p) {
  489. append(dest, cloneAndModify(c, { d: s.slice(0, otherC.p - c.p) }));
  490. s = s.slice(otherC.p - c.p);
  491. }
  492. if (s !== '') {
  493. append(dest, cloneAndModify(c, { d: s, p: c.p + otherC.i.length }));
  494. }
  495. } else if (otherC.d != null) {
  496. // Delete vs delete
  497. if (c.p >= otherC.p + otherC.d.length) {
  498. append(dest, cloneAndModify(c, { p: c.p - otherC.d.length }));
  499. } else if (c.p + c.d.length <= otherC.p) {
  500. append(dest, c);
  501. } else {
  502. // They overlap somewhere.
  503. newC = cloneAndModify(c, { d: '' });
  504. if (c.p < otherC.p) {
  505. newC.d = c.d.slice(0, otherC.p - c.p);
  506. }
  507. if (c.p + c.d.length > otherC.p + otherC.d.length) {
  508. newC.d += c.d.slice(otherC.p + otherC.d.length - c.p);
  509. }
  510. // This is entirely optional - just for a check that the deleted
  511. // text in the two ops matches
  512. intersectStart = Math.max(c.p, otherC.p);
  513. intersectEnd = Math.min(c.p + c.d.length, otherC.p + otherC.d.length);
  514. cIntersect = c.d.slice(intersectStart - c.p, intersectEnd - c.p);
  515. otherIntersect = otherC.d.slice(intersectStart - otherC.p, intersectEnd - otherC.p);
  516. if (cIntersect !== otherIntersect) {
  517. throw new Error('Delete ops delete different text in the same region of the document');
  518. }
  519. if (newC.d !== '') {
  520. // This could be rewritten similarly to insert v delete, above.
  521. newC.p = transformPosition(newC.p, otherC);
  522. append(dest, newC);
  523. }
  524. }
  525. } else if (otherC.c != null) {
  526. append(dest, c);
  527. } else {
  528. throw new Error('unknown op type');
  529. }
  530. } else if (c.c != null) {
  531. // Comment
  532. if (otherC.i != null) {
  533. if (c.p < otherC.p && otherC.p < c.p + c.c.length) {
  534. var offset = otherC.p - c.p;
  535. var new_c = c.c.slice(0, +(offset - 1) + 1 || undefined) + otherC.i + c.c.slice(offset);
  536. append(dest, cloneAndModify(c, { c: new_c }));
  537. } else {
  538. append(dest, cloneAndModify(c, { p: transformPosition(c.p, otherC, true) }));
  539. }
  540. } else if (otherC.d != null) {
  541. if (c.p >= otherC.p + otherC.d.length) {
  542. append(dest, cloneAndModify(c, { p: c.p - otherC.d.length }));
  543. } else if (c.p + c.c.length <= otherC.p) {
  544. append(dest, c);
  545. } else {
  546. // Delete overlaps comment
  547. // They overlap somewhere.
  548. newC = cloneAndModify(c, { c: '' });
  549. if (c.p < otherC.p) {
  550. newC.c = c.c.slice(0, otherC.p - c.p);
  551. }
  552. if (c.p + c.c.length > otherC.p + otherC.d.length) {
  553. newC.c += c.c.slice(otherC.p + otherC.d.length - c.p);
  554. }
  555. // This is entirely optional - just for a check that the deleted
  556. // text in the two ops matches
  557. intersectStart = Math.max(c.p, otherC.p);
  558. intersectEnd = Math.min(c.p + c.c.length, otherC.p + otherC.d.length);
  559. cIntersect = c.c.slice(intersectStart - c.p, intersectEnd - c.p);
  560. otherIntersect = otherC.d.slice(intersectStart - otherC.p, intersectEnd - otherC.p);
  561. if (cIntersect !== otherIntersect) {
  562. throw new Error('Delete ops delete different text in the same region of the document');
  563. }
  564. newC.p = transformPosition(newC.p, otherC);
  565. append(dest, newC);
  566. }
  567. } else if (otherC.c != null) {
  568. append(dest, c);
  569. } else {
  570. throw new Error('unknown op type');
  571. }
  572. }
  573. return dest;
  574. };
  575. var invertComponent = function invertComponent(c) {
  576. if (c.i != null) {
  577. return { d: c.i, p: c.p };
  578. } else {
  579. return { i: c.d, p: c.p };
  580. }
  581. };
  582. // No need to use append for invert, because the components won't be able to
  583. // cancel with one another.
  584. text.invert = function (op) {
  585. return Array.from(op.slice().reverse()).map(function (c) {
  586. return invertComponent(c);
  587. });
  588. };
  589. if (WEB != null) {
  590. if (!exports.types) {
  591. exports.types = {};
  592. }
  593. // This is kind of awful - come up with a better way to hook this helper code up.
  594. bootstrapTransform(text, transformComponent, checkValidOp, append);
  595. // [] is used to prevent closure from renaming types.text
  596. exports.types.text = text;
  597. }
  598. // Text document API for text
  599. text.api = {
  600. provides: { text: true },
  601. // The number of characters in the string
  602. getLength: function getLength() {
  603. return this.snapshot.length;
  604. },
  605. // Get the text contents of a document
  606. getText: function getText() {
  607. return this.snapshot;
  608. },
  609. insert: function insert(pos, text, fromUndo, callback) {
  610. var op = { p: pos, i: text };
  611. if (fromUndo) {
  612. op.u = true;
  613. }
  614. op = [op];
  615. this.submitOp(op, callback);
  616. return op;
  617. },
  618. del: function del(pos, length, fromUndo, callback) {
  619. var op = { p: pos, d: this.snapshot.slice(pos, pos + length) };
  620. if (fromUndo) {
  621. op.u = true;
  622. }
  623. op = [op];
  624. this.submitOp(op, callback);
  625. return op;
  626. },
  627. _register: function _register() {
  628. return this.on('remoteop', function (op) {
  629. var _this = this;
  630. return function () {
  631. var result = [];
  632. var _iteratorNormalCompletion10 = true;
  633. var _didIteratorError10 = false;
  634. var _iteratorError10 = undefined;
  635. try {
  636. for (var _iterator10 = Array.from(op)[Symbol.iterator](), _step10; !(_iteratorNormalCompletion10 = (_step10 = _iterator10.next()).done); _iteratorNormalCompletion10 = true) {
  637. var component = _step10.value;
  638. if (component.i !== undefined) {
  639. result.push(_this.emit('insert', component.p, component.i));
  640. } else if (component.d !== undefined) {
  641. result.push(_this.emit('delete', component.p, component.d));
  642. } else {
  643. result.push(undefined);
  644. }
  645. }
  646. } catch (err) {
  647. _didIteratorError10 = true;
  648. _iteratorError10 = err;
  649. } finally {
  650. try {
  651. if (!_iteratorNormalCompletion10 && _iterator10.return) {
  652. _iterator10.return();
  653. }
  654. } finally {
  655. if (_didIteratorError10) {
  656. throw _iteratorError10;
  657. }
  658. }
  659. }
  660. return result;
  661. }();
  662. });
  663. }
  664. };
  665. // This is a simple port of microevent.js to Coffeescript. I've changed the
  666. // function names to be consistent with node.js EventEmitter.
  667. //
  668. // microevent.js is copyright Jerome Etienne, and licensed under the MIT license:
  669. // https://github.com/jeromeetienne/microevent.js
  670. var nextTick = WEB != null ? function (fn) {
  671. return setTimeout(fn, 0);
  672. } : process['nextTick'];
  673. var MicroEvent = function () {
  674. function MicroEvent() {
  675. _classCallCheck(this, MicroEvent);
  676. }
  677. _createClass(MicroEvent, [{
  678. key: 'on',
  679. value: function on(event, fct) {
  680. if (!this._events) {
  681. this._events = {};
  682. }
  683. if (!this._events[event]) {
  684. this._events[event] = [];
  685. }
  686. this._events[event].push(fct);
  687. return this;
  688. }
  689. }, {
  690. key: 'removeListener',
  691. value: function removeListener(event, fct) {
  692. var _this2 = this;
  693. if (!this._events) {
  694. this._events = {};
  695. }
  696. var listeners = this._events[event] || (this._events[event] = []);
  697. // Sadly, there's no IE8- support for indexOf.
  698. var i = 0;
  699. while (i < listeners.length) {
  700. if (listeners[i] === fct) {
  701. listeners[i] = undefined;
  702. }
  703. i++;
  704. }
  705. nextTick(function () {
  706. return _this2._events[event] = Array.from(_this2._events[event]).filter(function (x) {
  707. return x;
  708. });
  709. });
  710. return this;
  711. }
  712. }, {
  713. key: 'emit',
  714. value: function emit(event) {
  715. if (!(this._events != null ? this._events[event] : undefined)) {
  716. return this;
  717. }
  718. for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  719. args[_key - 1] = arguments[_key];
  720. }
  721. var _iteratorNormalCompletion11 = true;
  722. var _didIteratorError11 = false;
  723. var _iteratorError11 = undefined;
  724. try {
  725. for (var _iterator11 = Array.from(this._events[event])[Symbol.iterator](), _step11; !(_iteratorNormalCompletion11 = (_step11 = _iterator11.next()).done); _iteratorNormalCompletion11 = true) {
  726. var fn = _step11.value;
  727. if (fn) {
  728. fn.apply(this, args);
  729. }
  730. }
  731. } catch (err) {
  732. _didIteratorError11 = true;
  733. _iteratorError11 = err;
  734. } finally {
  735. try {
  736. if (!_iteratorNormalCompletion11 && _iterator11.return) {
  737. _iterator11.return();
  738. }
  739. } finally {
  740. if (_didIteratorError11) {
  741. throw _iteratorError11;
  742. }
  743. }
  744. }
  745. return this;
  746. }
  747. }]);
  748. return MicroEvent;
  749. }();
  750. // mixin will delegate all MicroEvent.js function in the destination object
  751. MicroEvent.mixin = function (obj) {
  752. var proto = obj.prototype || obj;
  753. // Damn closure compiler :/
  754. proto.on = MicroEvent.prototype.on;
  755. proto.removeListener = MicroEvent.prototype.removeListener;
  756. proto.emit = MicroEvent.prototype.emit;
  757. return obj;
  758. };
  759. if (WEB == null) {
  760. module.exports = MicroEvent;
  761. }
  762. if (WEB != null) {
  763. exports.extendDoc = function (name, fn) {
  764. return Doc.prototype[name] = fn;
  765. };
  766. }
  767. // A Doc is a client's view on a sharejs document.
  768. //
  769. // Documents are created by calling Connection.open().
  770. //
  771. // Documents are event emitters - use doc.on(eventname, fn) to subscribe.
  772. //
  773. // Documents get mixed in with their type's API methods. So, you can .insert('foo', 0) into
  774. // a text document and stuff like that.
  775. //
  776. // Events:
  777. // - remoteop (op)
  778. // - changed (op)
  779. // - acknowledge (op)
  780. // - error
  781. // - open, closing, closed. 'closing' is not guaranteed to fire before closed.
  782. var Doc = function () {
  783. // connection is a Connection object.
  784. // name is the documents' docName.
  785. // data can optionally contain known document data, and initial open() call arguments:
  786. // {v[erson], snapshot={...}, type, create=true/false/undefined}
  787. // callback will be called once the document is first opened.
  788. function Doc(connection, name, openData) {
  789. _classCallCheck(this, Doc);
  790. // Any of these can be null / undefined at this stage.
  791. this.flush = this.flush.bind(this);
  792. this.setFlushDelay = this.setFlushDelay.bind(this);
  793. this.shout = this.shout.bind(this);
  794. this.connection = connection;
  795. this.name = name;
  796. if (!openData) {
  797. openData = {};
  798. }
  799. this.version = openData.v;
  800. this.lastServerActivity = performance.now()
  801. this.snapshot = openData.snaphot;
  802. if (openData.type) {
  803. this._setType(openData.type);
  804. }
  805. this.state = 'closed';
  806. this.autoOpen = false;
  807. // Has the document already been created?
  808. this._create = openData.create;
  809. // The op that is currently roundtripping to the server, or null.
  810. //
  811. // When the connection reconnects, the inflight op is resubmitted.
  812. this.inflightOp = null;
  813. this.inflightCallbacks = [];
  814. // The auth ids which the client has previously used to attempt to send inflightOp. This is
  815. // usually empty.
  816. this.inflightSubmittedIds = [];
  817. // All ops that are waiting for the server to acknowledge @inflightOp
  818. this.pendingOp = null;
  819. this.pendingCallbacks = [];
  820. }
  821. // Transform a server op by a client op, and vice versa.
  822. _createClass(Doc, [{
  823. key: '_xf',
  824. value: function _xf(client, server) {
  825. if (this.type.transformX) {
  826. return this.type.transformX(client, server);
  827. } else {
  828. var client_ = this.type.transform(client, server, 'left');
  829. var server_ = this.type.transform(server, client, 'right');
  830. return [client_, server_];
  831. }
  832. }
  833. }, {
  834. key: '_otApply',
  835. value: function _otApply(docOp, isRemote, msg) {
  836. var oldSnapshot = this.snapshot;
  837. this.snapshot = this.type.apply(this.snapshot, docOp);
  838. // Its important that these event handlers are called with oldSnapshot.
  839. // The reason is that the OT type APIs might need to access the snapshots to
  840. // determine information about the received op.
  841. this.emit('change', docOp, oldSnapshot, msg);
  842. if (isRemote) {
  843. return this.emit('remoteop', docOp, oldSnapshot, msg);
  844. }
  845. }
  846. }, {
  847. key: '_connectionStateChanged',
  848. value: function _connectionStateChanged(state, data) {
  849. switch (state) {
  850. case 'disconnected':
  851. this.state = 'closed';
  852. // This is used by the server to make sure that when an op is resubmitted it
  853. // doesn't end up getting applied twice.
  854. if (this.inflightOp) {
  855. this.inflightSubmittedIds.push(this.connection.id);
  856. }
  857. this.emit('closed');
  858. break;
  859. case 'ok':
  860. // Might be able to do this when we're connecting... that would save a roundtrip.
  861. if (this.autoOpen) {
  862. this.open();
  863. }
  864. break;
  865. case 'stopped':
  866. if (typeof this._openCallback === 'function') {
  867. this._openCallback(data);
  868. }
  869. break;
  870. }
  871. return this.emit(state, data);
  872. }
  873. }, {
  874. key: '_setType',
  875. value: function _setType(type) {
  876. if (typeof type === 'string') {
  877. type = types[type];
  878. }
  879. if (!type || !type.compose) {
  880. throw new Error('Support for types without compose() is not implemented');
  881. }
  882. this.type = type;
  883. if (type.api) {
  884. for (var k in type.api) {
  885. var v = type.api[k];this[k] = v;
  886. }
  887. return typeof this._register === 'function' ? this._register() : undefined;
  888. } else {
  889. return this.provides = {};
  890. }
  891. }
  892. }, {
  893. key: '_onMessage',
  894. value: function _onMessage(msg) {
  895. // debugConsole.warn('s->c', msg)
  896. if (msg.open === true) {
  897. // The document has been successfully opened.
  898. this.state = 'open';
  899. this._create = false; // Don't try and create the document again next time open() is called.
  900. if (this.created == null) {
  901. this.created = !!msg.create;
  902. }
  903. if (msg.type) {
  904. this._setType(msg.type);
  905. }
  906. if (msg.create) {
  907. this.created = true;
  908. this.snapshot = this.type.create();
  909. } else {
  910. if (this.created !== true) {
  911. this.created = false;
  912. }
  913. if (msg.snapshot !== undefined) {
  914. this.snapshot = msg.snapshot;
  915. }
  916. }
  917. if (msg.v != null) {
  918. this.version = msg.v;
  919. }
  920. // Resend any previously queued operation.
  921. if (this.inflightOp) {
  922. var response = {
  923. doc: this.name,
  924. op: this.inflightOp,
  925. v: this.version
  926. };
  927. if (this.inflightSubmittedIds.length) {
  928. response.dupIfSource = this.inflightSubmittedIds;
  929. }
  930. this.connection.send(response);
  931. } else {
  932. this.flush();
  933. }
  934. this.emit('open');
  935. return typeof this._openCallback === 'function' ? this._openCallback(null) : undefined;
  936. } else if (msg.open === false) {
  937. // The document has either been closed, or an open request has failed.
  938. if (msg.error) {
  939. // An error occurred opening the document.
  940. debugConsole.error('Could not open document: ' + msg.error);
  941. this.emit('error', msg.error);
  942. if (typeof this._openCallback === 'function') {
  943. this._openCallback(msg.error);
  944. }
  945. }
  946. this.state = 'closed';
  947. this.emit('closed');
  948. if (typeof this._closeCallback === 'function') {
  949. this._closeCallback();
  950. }
  951. return this._closeCallback = null;
  952. } else if (msg.op === null && error === 'Op already submitted') {
  953. // We've tried to resend an op to the server, which has already been received successfully. Do nothing.
  954. // The op will be confirmed normally when we get the op itself was echoed back from the server
  955. // (handled below).
  956. } else if (msg.op === undefined && msg.v !== undefined || msg.op && Array.from(this.inflightSubmittedIds).includes(msg.meta.source)) {
  957. // Our inflight op has been acknowledged.
  958. var callback = void 0;
  959. var oldInflightOp = this.inflightOp;
  960. this.inflightOp = null;
  961. this.inflightSubmittedIds.length = 0;
  962. if (this.pendingOp === null) {
  963. // All ops are acked
  964. this.emit('saved');
  965. }
  966. var error = msg.error;
  967. if (error) {
  968. // The server has rejected an op from the client for some reason.
  969. // We'll send the error message to the user and roll back the change.
  970. //
  971. // If the server isn't going to allow edits anyway, we should probably
  972. // figure out some way to flag that (readonly:true in the open request?)
  973. if (this.type.invert) {
  974. var undo = this.type.invert(oldInflightOp);
  975. // Now we have to transform the undo operation by any server ops & pending ops
  976. if (this.pendingOp) {
  977. var _Array$from7 = Array.from(this._xf(this.pendingOp, undo));
  978. var _Array$from8 = _slicedToArray(_Array$from7, 2);
  979. this.pendingOp = _Array$from8[0];
  980. undo = _Array$from8[1];
  981. }
  982. // ... and apply it locally, reverting the changes.
  983. //
  984. // This call will also call @emit 'remoteop'. I'm still not 100% sure about this
  985. // functionality, because its really a local op. Basically, the problem is that
  986. // if the client's op is rejected by the server, the editor window should update
  987. // to reflect the undo.
  988. this._otApply(undo, true, msg);
  989. } else {
  990. this.emit('error', 'Op apply failed (' + error + ') and the op could not be reverted');
  991. }
  992. var _iteratorNormalCompletion12 = true;
  993. var _didIteratorError12 = false;
  994. var _iteratorError12 = undefined;
  995. try {
  996. for (var _iterator12 = Array.from(this.inflightCallbacks)[Symbol.iterator](), _step12; !(_iteratorNormalCompletion12 = (_step12 = _iterator12.next()).done); _iteratorNormalCompletion12 = true) {
  997. callback = _step12.value;
  998. callback(error);
  999. }
  1000. } catch (err) {
  1001. _didIteratorError12 = true;
  1002. _iteratorError12 = err;
  1003. } finally {
  1004. try {
  1005. if (!_iteratorNormalCompletion12 && _iterator12.return) {
  1006. _iterator12.return();
  1007. }
  1008. } finally {
  1009. if (_didIteratorError12) {
  1010. throw _iteratorError12;
  1011. }
  1012. }
  1013. }
  1014. } else {
  1015. // The op applied successfully.
  1016. // We may get multiple acks of the same message if we retried it,
  1017. // so its ok if we receive an ack for a version that we've already gone past.
  1018. // If so, just ignore it
  1019. if (msg.v < this.version) {
  1020. return;
  1021. }
  1022. if (msg.v !== this.version) {
  1023. throw new Error('Invalid version from server');
  1024. }
  1025. this.version++;
  1026. this.lastServerActivity = performance.now()
  1027. this.emit('acknowledge', oldInflightOp);
  1028. var _iteratorNormalCompletion13 = true;
  1029. var _didIteratorError13 = false;
  1030. var _iteratorError13 = undefined;
  1031. try {
  1032. for (var _iterator13 = Array.from(this.inflightCallbacks)[Symbol.iterator](), _step13; !(_iteratorNormalCompletion13 = (_step13 = _iterator13.next()).done); _iteratorNormalCompletion13 = true) {
  1033. callback = _step13.value;
  1034. callback(null, oldInflightOp);
  1035. }
  1036. } catch (err) {
  1037. _didIteratorError13 = true;
  1038. _iteratorError13 = err;
  1039. } finally {
  1040. try {
  1041. if (!_iteratorNormalCompletion13 && _iterator13.return) {
  1042. _iterator13.return();
  1043. }
  1044. } finally {
  1045. if (_didIteratorError13) {
  1046. throw _iteratorError13;
  1047. }
  1048. }
  1049. }
  1050. }
  1051. // Send the next op.
  1052. return this.delayedFlush();
  1053. } else if (msg.op) {
  1054. // We got a new op from the server.
  1055. // msg is {doc:, op:, v:}
  1056. // There is a bug in socket.io (produced on firefox 3.6) which causes messages
  1057. // to be duplicated sometimes.
  1058. // We'll just silently drop subsequent messages.
  1059. if (msg.v < this.version) {
  1060. return;
  1061. }
  1062. if (msg.doc !== this.name) {
  1063. return this.emit('error', 'Expected docName \'' + this.name + '\' but got ' + msg.doc);
  1064. }
  1065. if (msg.v !== this.version) {
  1066. return this.emit('error', 'Expected version ' + this.version + ' but got ' + msg.v);
  1067. }
  1068. // p "if: #{i @inflightOp} pending: #{i @pendingOp} doc '#{@snapshot}' op: #{i msg.op}"
  1069. var docOp = msg.op;
  1070. if (this.inflightOp !== null) {
  1071. var _Array$from9 = Array.from(this._xf(this.inflightOp, docOp));
  1072. var _Array$from10 = _slicedToArray(_Array$from9, 2);
  1073. this.inflightOp = _Array$from10[0];
  1074. docOp = _Array$from10[1];
  1075. }
  1076. if (this.pendingOp !== null) {
  1077. var _Array$from11 = Array.from(this._xf(this.pendingOp, docOp));
  1078. var _Array$from12 = _slicedToArray(_Array$from11, 2);
  1079. this.pendingOp = _Array$from12[0];
  1080. docOp = _Array$from12[1];
  1081. }
  1082. this.version++;
  1083. this.lastServerActivity = performance.now()
  1084. // Finally, apply the op to @snapshot and trigger any event listeners
  1085. return this._otApply(docOp, true, msg);
  1086. } else if (msg.meta) {
  1087. var _msg$meta = msg.meta,
  1088. path = _msg$meta.path,
  1089. value = _msg$meta.value;
  1090. switch (path != null ? path[0] : undefined) {
  1091. case 'shout':
  1092. return this.emit('shout', value);
  1093. default:
  1094. return debugConsole.warn('Unhandled meta op:', msg);
  1095. }
  1096. } else {
  1097. return debugConsole.warn('Unhandled document message:', msg);
  1098. }
  1099. }
  1100. // Send ops to the server, if appropriate.
  1101. //
  1102. // Only one op can be in-flight at a time, so if an op is already on its way then
  1103. // this method does nothing.
  1104. }, {
  1105. key: 'flush',
  1106. value: function flush() {
  1107. this.flushTimeout = null;
  1108. // console.log "CALLED FLUSH"
  1109. if (this.connection.state !== 'ok' || this.inflightOp !== null || this.pendingOp === null) {
  1110. return;
  1111. }
  1112. // Rotate null -> pending -> inflight
  1113. this.inflightOp = this.pendingOp;
  1114. this.inflightCallbacks = this.pendingCallbacks;
  1115. this.pendingOp = null;
  1116. this.pendingCallbacks = [];
  1117. this.emit('flipped_pending_to_inflight');
  1118. if (getMeta('ol-useShareJsHash') || debugging) {
  1119. var now = Date.now()
  1120. var age = this.__lastSubmitTimestamp && (now - this.__lastSubmitTimestamp)
  1121. var RECOMPUTE_HASH_INTERVAL = 5000
  1122. // check the document hash regularly (but not if we have checked in the last 5 seconds)
  1123. var needToRecomputeHash = !this.__lastSubmitTimestamp || (age > RECOMPUTE_HASH_INTERVAL) || (age < 0)
  1124. if (needToRecomputeHash || debugging) {
  1125. // send git hash of current snapshot
  1126. var sha1 = generateSHA1Hash("blob " + this.snapshot.length + "\x00" + this.snapshot)
  1127. this.__lastSubmitTimestamp = now;
  1128. }
  1129. }
  1130. // console.log "SENDING OP TO SERVER", @inflightOp, @version
  1131. var lastVersion = this.__lastVersion;
  1132. this.__lastVersion = this.version;
  1133. return this.connection.send({ doc: this.name, op: this.inflightOp, v: this.version, lastV: lastVersion, hash: sha1});
  1134. }
  1135. // Submit an op to the server. The op maybe held for a little while before being sent, as only one
  1136. // op can be inflight at any time.
  1137. }, {
  1138. key: 'submitOp',
  1139. value: function submitOp(op, callback) {
  1140. if (this.type.normalize != null) {
  1141. op = this.type.normalize(op);
  1142. }
  1143. var oldSnapshot = this.snapshot;
  1144. // If this throws an exception, no changes should have been made to the doc
  1145. this.snapshot = this.type.apply(this.snapshot, op);
  1146. if (this.pendingOp !== null) {
  1147. this.pendingOp = this.type.compose(this.pendingOp, op);
  1148. } else {
  1149. this.pendingOp = op;
  1150. }
  1151. if (callback) {
  1152. this.pendingCallbacks.push(callback);
  1153. }
  1154. this.emit('change', op, oldSnapshot);
  1155. return this.delayedFlush();
  1156. }
  1157. }, {
  1158. key: 'delayedFlush',
  1159. value: function delayedFlush() {
  1160. if (this.flushTimeout == null) {
  1161. return this.flushTimeout = setTimeout(this.flush, this._flushDelay || 0);
  1162. }
  1163. }
  1164. }, {
  1165. key: 'setFlushDelay',
  1166. value: function setFlushDelay(delay) {
  1167. return this._flushDelay = delay;
  1168. }
  1169. }, {
  1170. key: 'shout',
  1171. value: function shout(msg) {
  1172. // Meta ops don't have to queue, they can go direct. Good/bad idea?
  1173. return this.connection.send({ doc: this.name, meta: { path: ['shout'], value: msg } });
  1174. }
  1175. // Open a document. The document starts closed.
  1176. }, {
  1177. key: 'open',
  1178. value: function open(callback) {
  1179. var _this3 = this;
  1180. this.autoOpen = true;
  1181. if (this.state !== 'closed') {
  1182. return;
  1183. }
  1184. var message = {
  1185. doc: this.name,
  1186. open: true
  1187. };
  1188. if (this.snapshot === undefined) {
  1189. message.snapshot = null;
  1190. }
  1191. if (this.type) {
  1192. message.type = this.type.name;
  1193. }
  1194. if (this.version != null) {
  1195. message.v = this.version;
  1196. }
  1197. if (this._create) {
  1198. message.create = true;
  1199. }
  1200. this.connection.send(message);
  1201. this.state = 'opening';
  1202. return this._openCallback = function (error) {
  1203. _this3._openCallback = null;
  1204. return typeof callback === 'function' ? callback(error) : undefined;
  1205. };
  1206. }
  1207. // Close a document.
  1208. }, {
  1209. key: 'close',
  1210. value: function close(callback) {
  1211. this.autoOpen = false;
  1212. if (this.state === 'closed') {
  1213. return typeof callback === 'function' ? callback() : undefined;
  1214. }
  1215. this.connection.send({ doc: this.name, open: false });
  1216. // Should this happen immediately or when we get open:false back from the server?
  1217. this.state = 'closed';
  1218. this.emit('closing');
  1219. return this._closeCallback = callback;
  1220. }
  1221. }]);
  1222. return Doc;
  1223. }();
  1224. // Make documents event emitters
  1225. MicroEvent.mixin(Doc);
  1226. exports.Doc = Doc;
  1227. return exports;
  1228. })()
  1229. export default window.sharejs