v1.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453
  1. function updateItemName(item, name)
  2. {
  3. if(name === undefined) name = item.name;
  4. if(item.infoName === name) return;
  5. item.infoName = name;
  6. item.name = name;
  7. const namePath = name.split('.');
  8. item.order = namePath.reduce((total, level, index) => total + (+level * ([1000000, 1000, 1, 0.001, 0.000001][index])), 0);
  9. item.level = namePath.length;
  10. item.selfName = namePath.pop();
  11. item.parentName = namePath.join('.');
  12. }
  13. function updateChildrenName(item)
  14. {
  15. if(!item.children) return;
  16. item.children.forEach((subItem, subIndex) =>
  17. {
  18. updateItemName(subItem, `${item.name}.${subIndex + 1}`);
  19. updateChildrenName(subItem);
  20. });
  21. }
  22. /** Steps editor component. */
  23. class StepsEditor extends zui.Component
  24. {
  25. static NAME = 'StepsEditor';
  26. static DEFAULT =
  27. {
  28. name: 'steps',
  29. expectsName: 'expects',
  30. data: ['1', '2', '3'],
  31. sameLevelIcon: 'plus',
  32. subLevelIcon: 'split',
  33. moveIcon: 'move',
  34. deleteIcon: 'trash',
  35. expectDisabledTip: '',
  36. deleteStepTip: '',
  37. dragNestedTip: '',
  38. changeLevelByDrag: false,
  39. expectDisabled: true,
  40. postDataID: false
  41. };
  42. init()
  43. {
  44. this.reset(this.options.data, true);
  45. }
  46. afterInit()
  47. {
  48. this.render();
  49. const $element = this.$element;
  50. $element.attr('zui-form-field', this.options.name)
  51. .on('focus', 'textarea', e =>
  52. {
  53. const $textarea = $(e.target);
  54. $textarea.closest('.steps-editor-col-step').addClass('focus');
  55. $textarea.closest('.steps-editor-item').addClass('is-focus');
  56. })
  57. .on('blur', 'textarea', e =>
  58. {
  59. const $textarea = $(e.target);
  60. $textarea.closest('.steps-editor-col-step').removeClass('focus');
  61. $textarea.closest('.steps-editor-item').removeClass('is-focus');
  62. if($textarea.val().length > 0 && $textarea.closest('.steps-editor-row').next('.steps-editor-row').length == 0)
  63. {
  64. this.addSib($textarea.closest('.steps-editor-body').find('.steps-editor-row[data-level="1"]').last().attr('data-name'), false);
  65. }
  66. })
  67. .on('click', '.btn-action', e =>
  68. {
  69. const $btn = $(e.currentTarget);
  70. if($btn.is('.disabled')) return;
  71. const action = $btn.attr('data-action');
  72. const name = $btn.closest('.steps-editor-item').attr('data-name');
  73. if(action === 'delete') this.deleteStep(name);
  74. else if(action === 'sib') this.addSib(name);
  75. else if(action === 'sub') this.addSub(name);
  76. }).on('mouseenter', '.steps-editor-step-move', e =>
  77. {
  78. $element.find('.move-hover').removeClass('move-hover');
  79. $(e.currentTarget).closest('.steps-editor-item').addClass('move-hover');
  80. }).on('mouseleave', '.steps-editor-step-move', e =>
  81. {
  82. $element.find('.move-hover').removeClass('move-hover');
  83. });
  84. $element.draggable(
  85. {
  86. selector: '.steps-editor-item',
  87. handle: '.steps-editor-step-move',
  88. beforeDrag: (_event, dragElement) =>
  89. {
  90. const dragName = $(dragElement).attr('data-name');
  91. this.dragName = dragName;
  92. this.dragItem = this.getByName(dragName);
  93. this.dragMaxLevel = this.dragItem.level;
  94. this.isValidLevel = true;
  95. $element.find(`.steps-editor-item[data-name^="${dragName}."]`).addClass('is-sub-dragging').each((_index, ele) =>
  96. {
  97. const level = +($(ele).attr('data-level'));
  98. if(level > this.dragMaxLevel) this.dragMaxLevel = level;
  99. });
  100. $element.removeClass('cursor-not-allowed');
  101. },
  102. onDragStart: (event, dragElement) =>
  103. {
  104. event.dataTransfer.setDragImage($(dragElement).find('.steps-editor-drag-ghost')[0], 0, 0);
  105. },
  106. onDragEnd: () =>
  107. {
  108. $element.find('.is-sub-dragging').removeClass('is-sub-dragging');
  109. const dropName = this.dropName;
  110. if(dropName)
  111. {
  112. this.dropName = null;
  113. const $dropRow = this.getRow(dropName);
  114. if($dropRow && $dropRow.length) $dropRow.removeAttr('data-drop-side').removeAttr('data-drop-level');
  115. }
  116. if(!this.isValidLevel) return;
  117. const dragName = this.dragName;
  118. if(!dropName || dragName === dropName) return;
  119. if(this.dropSide === 'bottom') this.moveAfter(dragName, dropName);
  120. else this.moveBefore(dragName, dropName);
  121. },
  122. onDragOver: (event, dragElement, dropElement) =>
  123. {
  124. const $row = $(dropElement);
  125. const dropName = $row.attr('data-name');
  126. let idDiff = false;
  127. if(dropName !== this.dropName)
  128. {
  129. this.dropName = dropName;
  130. const $oldRow = this.getRow(dropName);
  131. $oldRow.removeAttr('data-drop-side')
  132. .removeAttr('data-drop-level')
  133. .removeAttr('data-invalid-nested');
  134. $oldRow.find('.steps-editor-step-name').removeClass('is-invalid-drop-level');
  135. this.dropSide = '';
  136. this.dropLevel = '';
  137. this.isValidLevel = undefined;
  138. idDiff = true;
  139. }
  140. const dropItem = this.getByName(dropName);
  141. const dropBounding = dropElement.getBoundingClientRect();
  142. const dropSide = event.clientY > (dropBounding.top + dropBounding.height / 2) ? 'bottom' : 'top';
  143. const dropLevel = Math.max(1, Math.min(3, (!this.options.changeLevelByDrag || event.clientX <= (dropBounding.left + 24)) ? dropItem.level : (Math.round((event.clientX - dropBounding.left - 24 - 8) / 14))));
  144. const isValidLevel = (this.dragMaxLevel + (dropLevel - this.dragItem.level)) <= 3;
  145. if(this.isValidLevel !== isValidLevel)
  146. {
  147. this.isValidLevel = isValidLevel;
  148. $row.toggleClass('is-invalid-drop-level', !isValidLevel);
  149. const $name = $row.find('.steps-editor-step-name');
  150. if(isValidLevel) $name.removeAttr('data-invalid-nested');
  151. else $name.attr('data-invalid-nested', this.options.dragNestedTip);
  152. }
  153. $element.toggleClass('cursor-not-allowed', !isValidLevel);
  154. if(this.dropSide !== dropSide)
  155. {
  156. this.dropSide = dropSide;
  157. $row.attr('data-drop-side', dropSide);
  158. idDiff = true;
  159. }
  160. if(this.dropLevel !== dropLevel)
  161. {
  162. this.dropLevel = dropLevel;
  163. $row.attr('data-drop-level', dropLevel);
  164. idDiff = true;
  165. }
  166. },
  167. target: (dragElement) =>
  168. {
  169. return $element.find('.steps-editor-item').not('.is-sub-dragging').not(dragElement);
  170. }
  171. });
  172. }
  173. getByID(id)
  174. {
  175. return this._items.find(x => x.id === id);
  176. }
  177. getByName(name)
  178. {
  179. return this._items.find(x => x.name === name);
  180. }
  181. getParent(item)
  182. {
  183. if(typeof item === 'string') item = this.getByName(item);
  184. return (item && item.parentName) ? this.getByName(item.parentName) : null;
  185. }
  186. getRow(name)
  187. {
  188. return this.$element.find(`.steps-editor-item[data-name="${name}"]`);
  189. }
  190. reset(data, skipRender)
  191. {
  192. this._items = [];
  193. this.update(data, skipRender);
  194. }
  195. update(data, skipRender)
  196. {
  197. data.forEach(item =>{this.updateItem(item, true);});
  198. if(!skipRender) this.render();
  199. }
  200. updateItem(item, skipRender)
  201. {
  202. item = typeof item === 'string' ? {name: item, id: $.guid++, step: '', expect: ''} : $.extend({id: $.guid++, step: '', expect: ''}, item);
  203. updateItemName(item);
  204. const index = this._items.findIndex(x => x.id === item.id);
  205. if(index >= 0)
  206. {
  207. const oldItem = this._items[index];
  208. const parent = this.getParent(oldItem);
  209. if(parent) parent.children.splice(parent.children.indexOf(oldItem), 1);
  210. item = $.extend(oldItem, item);
  211. this._items.splice(index, 1);
  212. updateChildrenName(item);
  213. }
  214. if(item.level > 1)
  215. {
  216. this._items.push(item);
  217. const parent = this._ensureItem(item.parentName);
  218. const siblings = parent.children || [];
  219. const oldIndex = siblings.findIndex(x => x.id === item.id);
  220. if(oldIndex >= 0) siblings.splice(oldIndex, 1);
  221. const index = siblings.findIndex(x => x.order > item.order);
  222. if(index === 0) siblings.unshift(item);
  223. else if(index < 0) siblings.push(item);
  224. else if(index > 0) siblings.splice(index, 0, item);
  225. parent.children = siblings;
  226. }
  227. else
  228. {
  229. const siblings = this._items;
  230. const index = siblings.findIndex(x => x.level === 1 && x.order > item.order);
  231. if(index === 0) siblings.unshift(item);
  232. else if(index < 0) siblings.push(item);
  233. else if(index > 0) siblings.splice(index, 0, item);
  234. }
  235. if(!skipRender) this.render();
  236. return item;
  237. }
  238. _ensureItem(name)
  239. {
  240. return this.getByName(name) || this.updateItem(name);
  241. }
  242. _createRow(item, options)
  243. {
  244. const $row = $
  245. ([
  246. `<div class="steps-editor-row steps-editor-item" data-id="${item.id}">`,
  247. '<div class="steps-editor-drag-ghost"></div>',
  248. options.postDataID ? `<input type="hidden" class="steps-editor-post-data-id" value="${item.id}">` : '',
  249. '<div class="steps-editor-col steps-editor-col-step form-control">',
  250. '<div class="steps-editor-step-move"><i class="icon icon-move"></i></div>',
  251. '<div class="steps-editor-step-name"></div>',
  252. `<textarea class="steps-editor-step-text" rows="1">${item.step}</textarea>`,
  253. '</div>',
  254. '<div class="steps-editor-col steps-editor-col-add">',
  255. `<div><button type="button" class="btn ghost rounded size-sm square btn-action" data-action="sib"><i class="icon icon-${options.sameLevelIcon}"></i></button></div>`,
  256. `<div><button type="button" class="btn ghost rounded size-sm square btn-action" data-action="sub"><i class="icon icon-${options.subLevelIcon}"></i></button></div>`,
  257. '</div>',
  258. '<div class="steps-editor-col steps-editor-col-expect">',
  259. `<textarea class="steps-editor-step-expect form-control" rows="1">${item.expect}</textarea>`,
  260. `<div class="steps-editor-step-expect-tip">${options.expectDisabledTip}</div>`,
  261. '</div>',
  262. '<div class="steps-editor-col steps-editor-col-delete">',
  263. `<div><button type="button" class="btn ghost rounded size-sm square btn-action" data-action="delete"><i class="icon icon-${options.deleteIcon}"></i></button></div>`,
  264. '<input class="steps-editor-step-type" type="hidden" />',
  265. '</div>',
  266. '</div>'
  267. ].join(''));
  268. return $row;
  269. }
  270. _renderRow(item, $preRow, $list, $rows)
  271. {
  272. const options = this.options;
  273. let $row = $rows.filter(`[data-id="${item.id}"]`);
  274. let isNew = !$row.length;
  275. if(isNew) $row = this._createRow(item, options);
  276. if($preRow) $row.insertAfter($preRow);
  277. else $list.prepend($row);
  278. const hasSub = !!(item.children && item.children.length);
  279. $row.attr('data-level', item.level)
  280. .attr('data-name', item.name)
  281. .attr('data-index', item.index)
  282. .toggleClass('has-children', hasSub)
  283. .toggleClass('no-child', !hasSub)
  284. .removeClass('is-expired');
  285. requestAnimationFrame(() => {
  286. $row.css('--name-indent', `${(item.level - 1) * 14}px`).find('.steps-editor-step-name').css('width', item.name.length * 12).text(item.name).css('paddingLeft', (item.level - 1) * 14);
  287. $row.find('.steps-editor-step-text').attr('name', `${options.name}[${item.name}]`);
  288. $row.find('.steps-editor-step-type').attr('name', `stepType[${item.name}]`).val(hasSub ? 'group' : (!!item.parent && item.parent != '0' ? 'item' : 'step'));
  289. if(options.postDataID) $row.find('.steps-editor-post-data-id').attr('name', `id[${item.name}]`);
  290. const $expect = $row.find('.steps-editor-step-expect').attr(
  291. {
  292. name: `${options.expectsName}[${item.name}]`,
  293. disabled: hasSub && options.expectDisabled ? 'disabled' : null
  294. }).toggleClass('disabled', hasSub && options.expectDisabled);
  295. $expect.parent().toggleClass('disabled', hasSub && options.expectDisabled);
  296. $row.find('.steps-editor-col-delete .btn').toggleClass('disabled', hasSub || this._items.length == 1);
  297. $row.find('.steps-editor-col-delete .btn.disabled').attr('title', options.deleteStepTip);
  298. $row.find('.steps-editor-col-add .btn-action[data-action="sub"]').toggleClass('disabled', item.level >= 3);
  299. if(isNew) $row.find('textarea').autoHeight({fast: true});
  300. });
  301. return $row;
  302. }
  303. render()
  304. {
  305. const items = this._items;
  306. let rootIndex = 0;
  307. items.forEach(item =>
  308. {
  309. updateItemName(item);
  310. if(item.level === 1)
  311. {
  312. item.index = rootIndex;
  313. rootIndex++;
  314. updateItemName(item, `${rootIndex}`);
  315. }
  316. if(item.children)
  317. {
  318. item.children.forEach((subItem, subIndex) =>
  319. {
  320. subItem.index = subIndex;
  321. updateItemName(subItem, `${item.name}.${subIndex + 1}`);
  322. });
  323. }
  324. });
  325. items.sort((a, b) => a.order - b.order);
  326. const $list = this.$element.find('.steps-editor-body');
  327. const $rows = $list.find('.steps-editor-item').addClass('is-expired');
  328. let $preRow = null;
  329. items.forEach(item =>
  330. {
  331. $preRow = this._renderRow(item, $preRow, $list, $rows);
  332. });
  333. $rows.filter('.is-expired').remove();
  334. }
  335. deleteStep(name)
  336. {
  337. const index = this._items.findIndex(x => x.name === name);
  338. if (index < 0) return;
  339. const item = this._items[index];
  340. this._items.splice(index, 1);
  341. const parent = this.getParent(item);
  342. if(parent)
  343. {
  344. const siblings = parent.children;
  345. const index = siblings.indexOf(item);
  346. if(index > -1) siblings.splice(index, 1);
  347. }
  348. if (!this._items.length) this.update(['1'], false);
  349. this.render();
  350. }
  351. focus(name)
  352. {
  353. const $step = this.$element.find('.steps-editor-item[data-name="' + name + '"] .steps-editor-step-text');
  354. if($step.length) $step[0].focus();
  355. }
  356. addSub(fromName)
  357. {
  358. const item = this.getByName(fromName);
  359. if(!item) return;
  360. const newStepName = item.children ? `${item.name}.${item.children.length + 1}` : `${item.name}.1`;
  361. this.updateItem(newStepName);
  362. this.focus(newStepName);
  363. }
  364. addSib(fromName, focus = true)
  365. {
  366. const item = this.getByName(fromName);
  367. if(!item) return;
  368. const newItem = this.updateItem(item.name);
  369. if(focus) this.focus(newItem.name);
  370. }
  371. moveAfter(fromName, toName)
  372. {
  373. if(fromName === toName) return;
  374. const item = this.getByName(fromName);
  375. if(!item) return;
  376. item.name = toName;
  377. this.updateItem(item);
  378. }
  379. moveBefore(fromName, toName)
  380. {
  381. const item = this.getByName(fromName);
  382. const toItem = this.getByName(toName);
  383. if(!item || !toItem) return;
  384. item.name = toItem.level > 1 ? `${toItem.parentName}.${+toItem.selfName - 1}` : `${+toItem.selfName - 1}`;
  385. this.updateItem(item);
  386. }
  387. getData()
  388. {
  389. return this._items;
  390. }
  391. }
  392. /* Define $.fn.stepsEditor() helper. */
  393. StepsEditor.register();
  394. /* Extend StepsEditor to zui object. */
  395. $.extend(zui, {StepsEditor});
  396. /* Register stepsEditor to zui.FormHelper. */
  397. zui.FormHelper.registerControl('stepsEditor', ($field, $scope) =>
  398. {
  399. const $stepsEditor = $field.closest('[z-use-stepseditor]');
  400. if (!$stepsEditor.length || !$stepsEditor.closest($scope).length) {
  401. return;
  402. }
  403. const instance = $stepsEditor.zui('StepsEditor');
  404. return {
  405. type: 'stepsEditor',
  406. $element: $stepsEditor,
  407. instance: instance,
  408. getVal: () => instance.getData(),
  409. setVal: (value) => {
  410. if(!Array.isArray(value)) return;
  411. instance.reset(value.map((x, idx) => ({name: String(idx + 1), step: x.step || x.steps, expect: x.expect || x.expects})));
  412. return true;
  413. },
  414. };
  415. });