jquery.json-editor.js 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540
  1. /*
  2. Copyright (c) 2013, Andrew Cantino
  3. Copyright (c) 2009, Andrew Cantino & Kyle Maxwell
  4. Permission is hereby granted, free of charge, to any person obtaining a copy
  5. of this software and associated documentation files (the "Software"), to deal
  6. in the Software without restriction, including without limitation the rights
  7. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  8. copies of the Software, and to permit persons to whom the Software is
  9. furnished to do so, subject to the following conditions:
  10. The above copyright notice and this permission notice shall be included in
  11. all copies or substantial portions of the Software.
  12. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  13. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  14. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  15. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  16. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  17. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  18. THE SOFTWARE.
  19. You will probably need to tell the editor where to find its add and delete images. In your
  20. code before you make the editor, do something like this:
  21. JSONEditor.prototype.ADD_IMG = '/javascripts/jsoneditor/add.png';
  22. JSONEditor.prototype.DELETE_IMG = '/javascripts/jsoneditor/delete.png';
  23. You can enable or disable visual truncation in the structure editor with the following:
  24. myEditor.doTruncation(false);
  25. myEditor.doTruncation(true); // The default
  26. You can show a 'w'ipe button that does a more aggressive delete by calling showWipe(true|false) or by passing in 'showWipe: true'.
  27. */
  28. function JSONEditorBase(options) {
  29. if (!options) options = {};
  30. this.builderShowing = true;
  31. this.ADD_IMG = options.ADD_IMG || 'lib/images/add.png';
  32. this.DELETE_IMG = options.DELETE_IMG || 'lib/images/delete.png';
  33. this.functionButtonsEnabled = false;
  34. this._doTruncation = true;
  35. this._showWipe = options.showWipe;
  36. }
  37. function JSONEditor(wrapped, width, height) {
  38. this.history = [];
  39. this.historyPointer = -1;
  40. if (wrapped == null || (wrapped.get && wrapped.get(0) == null)) throw "Must provide an element to wrap.";
  41. var width = width || 600;
  42. var height = height || 300;
  43. this.wrapped = $(wrapped);
  44. this.wrapped.wrap('<div class="json-editor"></div>');
  45. this.container = $(this.wrapped.parent());
  46. this.container.width(width).height(height);
  47. this.wrapped.width(width).height(height);
  48. this.wrapped.hide();
  49. this.container.css("position", "relative");
  50. this.doAutoFocus = false;
  51. this.editingUnfocused();
  52. this.rebuild();
  53. var self = this;
  54. this.container.focus(function(){
  55. $(this).children('textarea').height(self.container.height() - self.functionButtons.height() - 5);
  56. $(this).children('.builder').height(self.container.height() - self.functionButtons.height() - 10);
  57. });
  58. return this;
  59. }
  60. JSONEditor.prototype = new JSONEditorBase();
  61. JSONEditor.prototype.braceUI = function(key, struct) {
  62. var self = this;
  63. return $('<a class="icon" href="#"><strong>{</strong></a>').click(function(e) {
  64. struct[key] = { "??": struct[key] };
  65. self.doAutoFocus = true;
  66. self.rebuild();
  67. return false;
  68. });
  69. };
  70. JSONEditor.prototype.bracketUI = function(key, struct) {
  71. var self = this;
  72. return $('<a class="icon" href="#"><strong>[</a>').click(function(e) {
  73. struct[key] = [ struct[key] ];
  74. self.doAutoFocus = true;
  75. self.rebuild();
  76. return false;
  77. });
  78. };
  79. JSONEditor.prototype.deleteUI = function(key, struct, fullDelete) {
  80. var self = this;
  81. return $('<a class="icon" href="#" title="delete"><img src="' + this.DELETE_IMG + '" border=0/></a>').click(function(e) {
  82. if (!fullDelete) {
  83. var didSomething = false;
  84. if (struct[key] instanceof Array) {
  85. if(struct[key].length > 0) {
  86. struct[key] = struct[key][0];
  87. didSomething = true;
  88. }
  89. } else if (struct[key] instanceof Object) {
  90. for (var i in struct[key]) {
  91. struct[key] = struct[key][i];
  92. didSomething = true;
  93. break;
  94. }
  95. }
  96. if (didSomething) {
  97. self.rebuild();
  98. return false;
  99. }
  100. }
  101. if (struct instanceof Array) {
  102. struct.splice(key, 1);
  103. } else {
  104. delete struct[key];
  105. }
  106. self.rebuild();
  107. return false;
  108. });
  109. };
  110. JSONEditor.prototype.wipeUI = function(key, struct) {
  111. var self = this;
  112. return $('<a class="icon" href="#" title="wipe"><strong>W</strong></a>').click(function(e) {
  113. if (struct instanceof Array) {
  114. struct.splice(key, 1);
  115. } else {
  116. delete struct[key];
  117. }
  118. self.rebuild();
  119. return false;
  120. });
  121. };
  122. JSONEditor.prototype.addUI = function(struct) {
  123. var self = this;
  124. return $('<a class="icon" href="#" title="add"><img src="' + this.ADD_IMG + '" border=0/></a>').click(function(e) {
  125. if (struct instanceof Array) {
  126. struct.push('??');
  127. } else {
  128. struct['??'] = '??';
  129. }
  130. self.doAutoFocus = true;
  131. self.rebuild();
  132. return false;
  133. });
  134. };
  135. JSONEditor.prototype.undo = function() {
  136. if (this.saveStateIfTextChanged()) {
  137. if (this.historyPointer > 0) this.historyPointer -= 1;
  138. this.restore();
  139. }
  140. };
  141. JSONEditor.prototype.redo = function() {
  142. if (this.historyPointer + 1 < this.history.length) {
  143. if (this.saveStateIfTextChanged()) {
  144. this.historyPointer += 1;
  145. this.restore();
  146. }
  147. }
  148. };
  149. JSONEditor.prototype.showBuilder = function() {
  150. if (this.checkJsonInText()) {
  151. this.setJsonFromText();
  152. this.rebuild();
  153. this.wrapped.hide();
  154. this.builder.show();
  155. return true;
  156. } else {
  157. alert("Sorry, there appears to be an error in your JSON input. Please fix it before continuing.");
  158. return false;
  159. }
  160. };
  161. JSONEditor.prototype.showText = function() {
  162. this.builder.hide();
  163. this.wrapped.show();
  164. };
  165. JSONEditor.prototype.toggleBuilder = function() {
  166. if(this.builderShowing){
  167. this.showText();
  168. this.builderShowing = !this.builderShowing;
  169. } else {
  170. if (this.showBuilder()) {
  171. this.builderShowing = !this.builderShowing;
  172. }
  173. }
  174. };
  175. JSONEditor.prototype.showFunctionButtons = function(insider) {
  176. if (!insider) this.functionButtonsEnabled = true;
  177. if (this.functionButtonsEnabled) if (!this.functionButtons) {
  178. this.functionButtons = $('<div class="function_buttons"></div>');
  179. var self = this;
  180. this.functionButtons.append($('<a href="#" style="padding-right: 10px;"></a>').click(function() {
  181. self.undo();
  182. return false;
  183. }).text('Undo')).append($('<a href="#" style="padding-right: 10px;"></a>').click(function() {
  184. self.redo();
  185. return false;
  186. }).text('Redo')).append($('<a id="toggle_view" href="#" style="padding-right: 10px;"></a>').click(function() {
  187. self.toggleBuilder();
  188. return false;
  189. }).text('Toggle View').css("float", "right"));
  190. this.container.prepend(this.functionButtons);
  191. this.container.height(this.container.height() + this.functionButtons.height() + 5);
  192. }
  193. if (this.functionButtons) {
  194. this.wrapped.css('top', this.functionButtons.height() + 5 + 'px');
  195. this.builder.css('top', this.functionButtons.height() + 5 + 'px');
  196. }
  197. };
  198. JSONEditor.prototype.saveStateIfTextChanged = function() {
  199. if (JSON.stringify(this.json, null, 2) != this.wrapped.get(0).value) {
  200. if (this.checkJsonInText()) {
  201. this.saveState(true);
  202. } else {
  203. if (confirm("The current JSON is malformed. If you continue, the current JSON will not be saved. Do you wish to continue?")) {
  204. this.historyPointer += 1;
  205. return true;
  206. } else {
  207. return false;
  208. }
  209. }
  210. }
  211. return true;
  212. };
  213. JSONEditor.prototype.restore = function() {
  214. if (this.history[this.historyPointer]) {
  215. this.wrapped.get(0).value = this.history[this.historyPointer];
  216. this.rebuild(true);
  217. }
  218. };
  219. JSONEditor.prototype.saveState = function(skipStoreText) {
  220. if (this.json) {
  221. if (!skipStoreText) this.storeToText();
  222. var text = this.wrapped.get(0).value;
  223. if (this.history[this.historyPointer] != text) {
  224. this.historyTruncate();
  225. this.history.push(text);
  226. this.historyPointer += 1;
  227. }
  228. }
  229. };
  230. JSONEditor.prototype.fireChange = function() {
  231. $(this.wrapped).trigger('change');
  232. };
  233. JSONEditor.prototype.historyTruncate = function() {
  234. if (this.historyPointer + 1 < this.history.length) {
  235. this.history.splice(this.historyPointer + 1, this.history.length - this.historyPointer);
  236. }
  237. };
  238. JSONEditor.prototype.storeToText = function() {
  239. this.wrapped.get(0).value = JSON.stringify(this.json, null, 2);
  240. };
  241. JSONEditor.prototype.getJSONText = function() {
  242. this.rebuild();
  243. return this.wrapped.get(0).value;
  244. };
  245. JSONEditor.prototype.getJSON = function() {
  246. this.rebuild();
  247. return this.json;
  248. };
  249. JSONEditor.prototype.rebuild = function(doNotRefreshText) {
  250. if (!this.json) this.setJsonFromText();
  251. var changed = this.haveThingsChanged();
  252. if (this.json && !doNotRefreshText) {
  253. this.saveState();
  254. }
  255. this.cleanBuilder();
  256. this.setJsonFromText();
  257. this.alreadyFocused = false;
  258. var elem = this.build(this.json, this.builder, null, null, this.json);
  259. this.recoverScrollPosition();
  260. // Auto-focus to edit '??' keys and values.
  261. if (elem) if (elem.text() == '??' && !this.alreadyFocused && this.doAutoFocus) {
  262. this.alreadyFocused = true;
  263. this.doAutoFocus = false;
  264. elem = elem.find('.editable');
  265. elem.click();
  266. elem.find('input').focus().select();
  267. //still missing a proper scrolling into the selected input
  268. }
  269. if (changed) this.fireChange();
  270. };
  271. JSONEditor.prototype.haveThingsChanged = function() {
  272. return (this.json && JSON.stringify(this.json, null, 2) != this.wrapped.get(0).value);
  273. }
  274. JSONEditor.prototype.saveScrollPosition = function() {
  275. this.oldScrollHeight = this.builder.scrollTop();
  276. };
  277. JSONEditor.prototype.recoverScrollPosition = function() {
  278. this.builder.scrollTop(this.oldScrollHeight);
  279. };
  280. JSONEditor.prototype.setJsonFromText = function() {
  281. if (this.wrapped.get(0).value.length == 0) this.wrapped.get(0).value = "{}";
  282. try {
  283. this.wrapped.get(0).value = this.wrapped.get(0).value.replace(/((^|[^\\])(\\\\)*)\\n/g, '$1\\\\n').replace(/((^|[^\\])(\\\\)*)\\t/g, '$1\\\\t');
  284. this.json = JSON.parse(this.wrapped.get(0).value);
  285. } catch(e) {
  286. alert("Got bad JSON from text.");
  287. }
  288. };
  289. JSONEditor.prototype.checkJsonInText = function() {
  290. try {
  291. JSON.parse(this.wrapped.get(0).value);
  292. return true;
  293. } catch(e) {
  294. return false;
  295. }
  296. };
  297. JSONEditor.prototype.logJSON = function() {
  298. console.log(JSON.stringify(this.json, null, 2));
  299. };
  300. JSONEditor.prototype.cleanBuilder = function() {
  301. if (!this.builder) {
  302. this.builder = $('<div class="builder"></div>');
  303. this.container.append(this.builder);
  304. }
  305. this.saveScrollPosition();
  306. this.builder.text('');
  307. this.builder.css("position", "absolute").css("top", 0).css("left", 0);
  308. this.builder.width(this.wrapped.width()).height(this.wrapped.height());
  309. this.wrapped.css("position", "absolute").css("top", 0).css("left", 0);
  310. this.showFunctionButtons("defined");
  311. };
  312. JSONEditor.prototype.updateStruct = function(struct, key, val, kind, selectionStart, selectionEnd) {
  313. if(kind == 'key') {
  314. if (selectionStart && selectionEnd) val = key.substring(0, selectionStart) + val + key.substring(selectionEnd, key.length);
  315. struct[val] = struct[key];
  316. //order keys
  317. var orderrest = 0;
  318. $.each(struct, function (index, value) {
  319. //re set rest of the keys
  320. if(orderrest & index != val) {
  321. var tempval = struct[index];
  322. delete struct[index];
  323. struct[index] = tempval;
  324. }
  325. if(key == index) {
  326. orderrest = 1;
  327. }
  328. });
  329. // end of order keys
  330. if (key != val) delete struct[key];
  331. } else {
  332. if (selectionStart && selectionEnd) val = struct[key].substring(0, selectionStart) + val + struct[key].substring(selectionEnd, struct[key].length);
  333. struct[key] = val;
  334. }
  335. };
  336. JSONEditor.prototype.getValFromStruct = function(struct, key, kind) {
  337. if(kind == 'key') {
  338. return key;
  339. } else {
  340. return struct[key];
  341. }
  342. };
  343. JSONEditor.prototype.doTruncation = function(trueOrFalse) {
  344. if (this._doTruncation != trueOrFalse) {
  345. this._doTruncation = trueOrFalse;
  346. this.rebuild();
  347. }
  348. };
  349. JSONEditor.prototype.showWipe = function(trueOrFalse) {
  350. if (this._showWipe != trueOrFalse) {
  351. this._showWipe = trueOrFalse;
  352. this.rebuild();
  353. }
  354. };
  355. JSONEditor.prototype.truncate = function(text, length) {
  356. if (text.length == 0) return '-empty-';
  357. if(this._doTruncation && text.length > (length || 30)) return(text.substring(0, (length || 30)) + '...');
  358. return text;
  359. };
  360. JSONEditor.prototype.replaceLastSelectedFieldIfRecent = function(text) {
  361. if (this.lastEditingUnfocusedTime > (new Date()).getTime() - 200) { // Short delay for unfocus to occur.
  362. this.setLastEditingFocus(text);
  363. this.rebuild();
  364. }
  365. };
  366. JSONEditor.prototype.editingUnfocused = function(elem, struct, key, root, kind) {
  367. var self = this;
  368. var selectionStart = elem && elem.target.selectionStart;
  369. var selectionEnd = elem && elem.target.selectionEnd;
  370. this.setLastEditingFocus = function(text) {
  371. self.updateStruct(struct, key, text, kind, selectionStart, selectionEnd);
  372. self.json = root; // Because self.json is a new reference due to rebuild.
  373. };
  374. this.lastEditingUnfocusedTime = (new Date()).getTime();
  375. };
  376. JSONEditor.prototype.edit = function(e, key, struct, root, kind){
  377. var self = this;
  378. var form = $("<form></form>").css('display', 'inline');
  379. var input = document.createElement("INPUT");
  380. input.value = this.getValFromStruct(struct, key, kind);
  381. //alert(this.getValFromStruct(struct, key, kind));
  382. input.className = 'edit_field';
  383. var onblur = function(elem) {
  384. var val = input.value;
  385. self.updateStruct(struct, key, val, kind);
  386. self.editingUnfocused(elem, struct, (kind == 'key' ? val : key), root, kind);
  387. e.text(self.truncate(val));
  388. e.get(0).editing = false;
  389. if (key != val) self.rebuild();
  390. return false;
  391. };
  392. $(input).blur(onblur);
  393. $(input).keydown(function(e) {
  394. if (e.keyCode == 9 || e.keyCode == 13) { // Tab and enter
  395. self.doAutoFocus = true;
  396. onblur(e);
  397. return false;
  398. }
  399. });
  400. $(form).submit(function(e) { self.doAutoFocus = true; onblur(e); return false;}).append(input);
  401. $(e).html(form);
  402. input.focus();
  403. };
  404. JSONEditor.prototype.editable = function(text, key, struct, root, kind) {
  405. var self = this;
  406. var elem = $('<span class="editable" href="#"></span>').text(this.truncate(text)).click(function(e) {
  407. if (!this.editing) {
  408. this.editing = true;
  409. self.edit($(this), key, struct, root, kind);
  410. }
  411. return true;
  412. });
  413. return elem;
  414. }
  415. JSONEditor.prototype.build = function(json, node, parent, key, root) {
  416. var elem = null;
  417. if(json instanceof Array){
  418. var bq = $(document.createElement("BLOCKQUOTE"));
  419. bq.append($('<div class="brackets">[</div>'));
  420. bq.prepend(this.addUI(json));
  421. if (parent) {
  422. if (this._showWipe) bq.prepend(this.wipeUI(key, parent));
  423. bq.prepend(this.deleteUI(key, parent));
  424. }
  425. for(var i = 0; i < json.length; i++) {
  426. var innerbq = $(document.createElement("BLOCKQUOTE"));
  427. var newElem = this.build(json[i], innerbq, json, i, root);
  428. if (newElem) if (newElem.text() == "??") elem = newElem;
  429. bq.append(innerbq);
  430. }
  431. bq.append($('<div class="brackets">]</div>'));
  432. node.append(bq);
  433. } else if (json instanceof Object) {
  434. var bq = $(document.createElement("BLOCKQUOTE"));
  435. bq.append($('<div class="bracers">{</div>'));
  436. for(var i in json){
  437. var innerbq = $(document.createElement("BLOCKQUOTE"));
  438. var newElem = this.editable(i.toString(), i.toString(), json, root, 'key').wrap('<span class="key"></b>').parent();
  439. innerbq.append(newElem);
  440. if (newElem) if (newElem.text() == "??") elem = newElem;
  441. if (typeof json[i] != 'string') {
  442. innerbq.prepend(this.braceUI(i, json));
  443. innerbq.prepend(this.bracketUI(i, json));
  444. if (this._showWipe) innerbq.prepend(this.wipeUI(i, json));
  445. innerbq.prepend(this.deleteUI(i, json, true));
  446. }
  447. innerbq.append($('<span class="colon">: </span>'));
  448. newElem = this.build(json[i], innerbq, json, i, root);
  449. if (newElem) if (newElem.text() == "??") elem = newElem;
  450. bq.append(innerbq);
  451. }
  452. bq.prepend(this.addUI(json));
  453. if (parent) {
  454. if (this._showWipe) bq.prepend(this.wipeUI(key, parent));
  455. bq.prepend(this.deleteUI(key, parent));
  456. }
  457. bq.append($('<div class="bracers">}</div>'));
  458. node.append(bq);
  459. } else {
  460. elem = this.editable(json.toString(), key, parent, root, 'value').wrap('<span class="val"></span>').parent();
  461. node.append(elem);
  462. node.prepend(this.braceUI(key, parent));
  463. node.prepend(this.bracketUI(key, parent));
  464. if (parent) {
  465. if (this._showWipe) node.prepend(this.wipeUI(key, parent));
  466. node.prepend(this.deleteUI(key, parent));
  467. }
  468. }
  469. return elem;
  470. };