v1.js 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455
  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. /** ThinkMatrixOptions component. */
  23. class ThinkMatrixOptions extends zui.Component
  24. {
  25. static NAME = 'ThinkMatrixOptions';
  26. static DEFAULT =
  27. {
  28. colName: 'colFields',
  29. cols: ['', '', '', ''],
  30. moveIcon: 'move',
  31. deleteIcon: 'close',
  32. deleteColTip: '',
  33. addColTip: '',
  34. changeLevelByDrag: false,
  35. colPlaceholder: '',
  36. addColText: '',
  37. isSaveData: true,
  38. };
  39. init()
  40. {
  41. this.reset(this.options.cols, true);
  42. }
  43. afterInit()
  44. {
  45. this.render();
  46. const $element = this.$element;
  47. const multipleData = $('.think-multiple').data();
  48. const quotedQuestions = multipleData.quotedQuestions;
  49. const linkColumn = multipleData.linkColumn;
  50. $element.on('focus', 'input', e =>
  51. {
  52. const $input = $(e.target);
  53. $input.closest('.think-multiple-item').addClass('is-focus');
  54. })
  55. .on('blur', 'input', e =>
  56. {
  57. const $input = $(e.target);
  58. $input.closest('.think-multiple-item').removeClass('is-focus');
  59. this.saveData();
  60. })
  61. .on('input', 'input', e => {this.saveData();})
  62. .on('click', '.btn-action', e =>
  63. {
  64. const $btn = $(e.currentTarget);
  65. if($btn.is('.disabled')) return;
  66. const action = $btn.attr('data-action');
  67. const name = $btn.closest('.think-multiple-item').attr('data-name');
  68. if(action === 'delete') this.deleteItem(name);
  69. else if(action === 'sib') this.addSib();
  70. }).on('mouseenter', '.think-multiple-item-move', e =>
  71. {
  72. $element.find('.move-hover').removeClass('move-hover');
  73. $(e.currentTarget).closest('.think-multiple-item').addClass('move-hover');
  74. }).on('mouseleave', '.think-multiple-item-move', e =>
  75. {
  76. $element.find('.move-hover').removeClass('move-hover');
  77. });
  78. /* 如果当前多列填空题被其他多选题引用,不可以重新排列列标题顺序。*/
  79. /* If the current multiple column fill in the blank question is referenced by other multiple-choice questions, the column headings cannot be rearranged. */
  80. if((!quotedQuestions || !quotedQuestions.length) && !linkColumn.length)
  81. {
  82. $element.draggable(
  83. {
  84. selector: '.think-multiple-item',
  85. handle: '.think-multiple-item-move',
  86. beforeDrag: (_event, dragElement) =>
  87. {
  88. const dragName = $(dragElement).attr('data-name');
  89. this.dragName = dragName;
  90. this.dragItem = this.getByName(dragName);
  91. this.dragMaxLevel = this.dragItem.level;
  92. this.isValidLevel = true;
  93. $element.find(`.think-multiple-item[data-name^="${dragName}."]`).addClass('is-sub-dragging').each((_index, ele) =>
  94. {
  95. const level = +($(ele).attr('data-level'));
  96. if(level > this.dragMaxLevel) this.dragMaxLevel = level;
  97. });
  98. $element.removeClass('cursor-not-allowed');
  99. },
  100. onDragStart: (event, dragElement) =>
  101. {
  102. event.dataTransfer.setDragImage($(dragElement).find('.think-multiple-drag-ghost')[0], 0, 0);
  103. },
  104. onDragEnd: () =>
  105. {
  106. $element.find('.is-sub-dragging').removeClass('is-sub-dragging');
  107. const dropName = this.dropName;
  108. if(dropName)
  109. {
  110. this.dropName = null;
  111. const $dropRow = this.getRow(dropName);
  112. if($dropRow && $dropRow.length) $dropRow.removeAttr('data-drop-side').removeAttr('data-drop-level');
  113. }
  114. if(!this.isValidLevel) return;
  115. const dragName = this.dragName;
  116. if(!dropName || dragName === dropName) return;
  117. if(this.dropSide === 'right') this.moveAfter(dragName, dropName);
  118. else this.moveBefore(dragName, dropName);
  119. this.saveData(true);
  120. },
  121. onDragOver: (event, dragElement, dropElement) =>
  122. {
  123. const $col = $(dropElement);
  124. const dropName = $col.attr('data-name');
  125. let idDiff = false;
  126. if(dropName !== this.dropName)
  127. {
  128. this.dropName = dropName;
  129. const $oldRow = this.getRow(dropName);
  130. $oldRow.removeAttr('data-drop-side')
  131. .removeAttr('data-drop-level')
  132. .removeAttr('data-invalid-nested');
  133. this.dropSide = '';
  134. this.dropLevel = '';
  135. this.isValidLevel = undefined;
  136. idDiff = true;
  137. }
  138. const dropItem = this.getByName(dropName);
  139. const dropBounding = dropElement.getBoundingClientRect();
  140. const dropSide = event.clientX > (dropBounding.left + dropBounding.width / 2) ? 'right' : 'left';
  141. const dropLevel = Math.max(1, Math.min(4, (!this.options.changeLevelByDrag || event.clientX <= (dropBounding.left + 24)) ? dropItem.level : (Math.round((event.clientX - dropBounding.left - 24 - 8) / 14))));
  142. const isValidLevel = (this.dragMaxLevel + (dropLevel - this.dragItem.level)) <= 4;
  143. if(this.isValidLevel !== isValidLevel)
  144. {
  145. this.isValidLevel = isValidLevel;
  146. $col.toggleClass('is-invalid-drop-level', !isValidLevel);
  147. }
  148. $element.toggleClass('cursor-not-allowed', !isValidLevel);
  149. if(this.dropSide !== dropSide)
  150. {
  151. this.dropSide = dropSide;
  152. $col.attr('data-drop-side', dropSide);
  153. idDiff = true;
  154. }
  155. if(this.dropLevel !== dropLevel)
  156. {
  157. this.dropLevel = dropLevel;
  158. $col.attr('data-drop-level', dropLevel);
  159. idDiff = true;
  160. }
  161. },
  162. target: (dragElement) =>
  163. {
  164. return $element.find('.think-multiple-item').not('.is-sub-dragging').not(dragElement);
  165. }
  166. });
  167. }
  168. }
  169. saveData(isClear = false)
  170. {
  171. if(!this.options.isSaveData) return;
  172. const cols = [];
  173. $('.think-multiple-body .think-multiple-item-text').each(function()
  174. {
  175. if($(this).val())
  176. {
  177. const item = {value: $(this).closest('.think-multiple-item').data('name'), text: $(this).val()};
  178. cols.push(item);
  179. }
  180. });
  181. let values = $('.required-options .picker-box').zui('picker').$.value;
  182. values = values.split('');
  183. const result = [];
  184. values.forEach(function(item)
  185. {
  186. if($(`.think-multiple-item[data-name="${item}"] .think-multiple-item-text`).val()) result.push(item);
  187. });
  188. $('.required-options .picker-box').zui('picker').$.setValue(result.join(','));
  189. $('.required-options .picker-box').zui('picker').render({items: cols});
  190. if(isClear) $('.required-options .picker-box').zui('picker').$.setValue('');
  191. }
  192. getByID(id)
  193. {
  194. return this._items.find(x => x.id === id);
  195. }
  196. getByName(name)
  197. {
  198. return this._items.find(x => x.name === name);
  199. }
  200. getParent(item)
  201. {
  202. if(typeof item === 'string') item = this.getByName(item);
  203. return (item && item.parentName) ? this.getByName(item.parentName) : null;
  204. }
  205. getRow(name)
  206. {
  207. return this.$element.find(`.think-multiple-item[data-name="${name}"]`);
  208. }
  209. reset(data, skipRender)
  210. {
  211. this._items = [];
  212. this.update(data, skipRender);
  213. }
  214. update(data, skipRender)
  215. {
  216. data.forEach(item =>{this.updateItem(item, true);});
  217. if(!skipRender) this.render();
  218. }
  219. updateItem(item, skipRender)
  220. {
  221. item = typeof item === 'string' ? {name: item, id: $.guid++, step: ''} : $.extend({id: $.guid++, step: ''}, item);
  222. updateItemName(item);
  223. const index = this._items.findIndex(x => x.id === item.id);
  224. if(index >= 0)
  225. {
  226. const oldItem = this._items[index];
  227. const parent = this.getParent(oldItem);
  228. if(parent) parent.children.splice(parent.children.indexOf(oldItem), 1);
  229. item = $.extend(oldItem, item);
  230. this._items.splice(index, 1);
  231. updateChildrenName(item);
  232. }
  233. if(item.level > 1)
  234. {
  235. this._items.push(item);
  236. const parent = this._ensureItem(item.parentName);
  237. const siblings = parent.children || [];
  238. const oldIndex = siblings.findIndex(x => x.id === item.id);
  239. if(oldIndex >= 0) siblings.splice(oldIndex, 1);
  240. const index = siblings.findIndex(x => x.order > item.order);
  241. if(index === 0) siblings.unshift(item);
  242. else if(index < 0) siblings.push(item);
  243. else if(index > 0) siblings.splice(index, 0, item);
  244. parent.children = siblings;
  245. }
  246. else
  247. {
  248. const siblings = this._items;
  249. const index = siblings.findIndex(x => x.level === 1 && x.order > item.order);
  250. if(index === 0) siblings.unshift(item);
  251. else if(index < 0) siblings.push(item);
  252. else if(index > 0) siblings.splice(index, 0, item);
  253. }
  254. if(!skipRender) this.render();
  255. return item;
  256. }
  257. _ensureItem(name)
  258. {
  259. return this.getByName(name) || this.updateItem(name);
  260. }
  261. _createCol(item, options)
  262. {
  263. const name = options.cols[item.index] || '';
  264. const $col = $
  265. ([
  266. `<div class="think-multiple-item flex-1 py-1.5" data-id="${item.id}">`,
  267. '<div class="think-multiple-drag-ghost"></div>',
  268. '<div class="think-multiple-item-move think-multiple-action"><i class="icon icon-move"></i></div>',
  269. '<div class="flex-1">',
  270. `<input class="form-control think-multiple-item-text w-full" placeholder="${options.colPlaceholder}${item.name}" value="${name}" />`,
  271. '<div class="mt-2 rounded ring bg-gray-100" style="height: 30px; --tw-ring-color: var(--form-control-border);"></div>',
  272. '</div>',
  273. '<div class="think-multiple-col-delete think-multiple-action">',
  274. `<button type="button" class="btn ghost rounded size-sm square btn-action border-none" data-action="delete"><i class="icon icon-${options.deleteIcon}"></i></button>`,
  275. '</div>',
  276. '</div>'
  277. ].join(''));
  278. return $col;
  279. }
  280. _renderCol(item, $preCol, $list, $cols)
  281. {
  282. const options = this.options;
  283. const multipleData = $('.think-multiple').data();
  284. const tipQuestion = multipleData.tipQuestion;
  285. const cannotDeleteColumnTip = multipleData.cannotDeleteColumnTip;
  286. const linkCannotDeleteTip = multipleData.linkCannotDeleteTip;
  287. let $col = $cols.filter(`[data-id="${item.id}"]`);
  288. if(!$col.length) $col = this._createCol(item, options);
  289. if($preCol) $col.insertAfter($preCol);
  290. else $list.prepend($col);
  291. const hasSub = !!(item.children && item.children.length);
  292. $col.attr('data-level', item.level)
  293. .attr('data-name', item.name)
  294. .attr('data-index', item.index)
  295. .toggleClass('has-children', hasSub)
  296. .toggleClass('no-child', !hasSub)
  297. .removeClass('is-expired');
  298. $col.find('.think-multiple-item-text').attr({'name': `${options.colName}[${item.name}]`, placeholder: `${options.colPlaceholder}${item.name}`});
  299. $col.find('.think-multiple-col-delete .btn').toggleClass('disabled', hasSub || this._items.length == 1);
  300. $col.find('.think-multiple-col-delete .btn.disabled').attr('title', options.deleteColTip);
  301. $col.find('.think-multiple-item-move').toggleClass('disabled', this._items.length == 1);
  302. /* 当前多列填空被其他多选题引用时禁用删除按钮和移动按钮,并提示出引用当前问题的题号。 */
  303. /* When the current multi-column fill-in-the-blank question is referenced by other multiple-choice questions, the delete button and move button are disabled, and the question number that references the current question is prompted. */
  304. const quotedQuestions = multipleData.quotedQuestions;
  305. const linkColumn = multipleData.linkColumn
  306. if((quotedQuestions && quotedQuestions.length) || linkColumn.length)
  307. {
  308. let quotedIndex = '';
  309. quotedQuestions.forEach(function(item, index)
  310. {
  311. quotedIndex = quotedIndex + tipQuestion.replace(/%s/g, item.index) + ((index + 1 == quotedQuestions.length) ? '' : '、');
  312. })
  313. const quotedCannotDeleteTip = cannotDeleteColumnTip.replace(/%s/g, quotedIndex);
  314. $col.find('.think-multiple-item-move').attr('disabled', true);
  315. $col.find('.think-multiple-col-delete .btn').attr('disabled', true);
  316. $col.find('.think-multiple-col-delete .btn').attr('title', quotedIndex ? quotedCannotDeleteTip : linkCannotDeleteTip);
  317. $col.find('.think-multiple-item-move').attr('title', quotedIndex ? quotedCannotDeleteTip : linkCannotDeleteTip);
  318. }
  319. else
  320. {
  321. $col.find('.think-multiple-item-move').removeAttr('disabled');
  322. $col.find('.think-multiple-col-delete .btn').removeAttr('disabled');
  323. $col.find('.think-multiple-col-delete .btn').removeAttr('title');
  324. $col.find('.think-multiple-item-move').removeAttr('title');
  325. }
  326. return $col;
  327. }
  328. render()
  329. {
  330. const items = this._items;
  331. let rootIndex = 0;
  332. items.forEach(item =>
  333. {
  334. updateItemName(item);
  335. if(item.level === 1)
  336. {
  337. item.index = rootIndex;
  338. rootIndex++;
  339. updateItemName(item, `${rootIndex}`);
  340. }
  341. if(item.children)
  342. {
  343. item.children.forEach((subItem, subIndex) =>
  344. {
  345. subItem.index = subIndex;
  346. updateItemName(subItem, `${item.name}.${subIndex + 1}`);
  347. });
  348. }
  349. });
  350. items.sort((a, b) => a.order - b.order);
  351. const $list = this.$element.find('.think-multiple-body');
  352. const $cols = $list.find('.think-multiple-item').addClass('is-expired');
  353. let $preCol = null;
  354. items.forEach(item =>
  355. {
  356. $preCol = this._renderCol(item, $preCol, $list, $cols);
  357. });
  358. $cols.filter('.is-expired').remove();
  359. if(!this.$element.find('.think-multiple-buttons').length) this.$element.find('.think-multiple-body').append(`<div class="think-multiple-buttons"><button type="button" class="btn ghost text-primary rounded size-sm square btn-action action-add" data-action="sib"><i class="icon icon-plus"></i>${this.options.addColText}</button></div>`);
  360. this.$element.find('.think-multiple-buttons .action-add').prop('disabled', items?.length && items.length > 15).attr('title', items?.length && items.length > 15 ? this.options.addColTip : '');
  361. }
  362. deleteItem(name)
  363. {
  364. const index = this._items.findIndex(x => x.name === name);
  365. if (index < 0) return;
  366. const item = this._items[index];
  367. this._items.splice(index, 1);
  368. const parent = this.getParent(item);
  369. if(parent)
  370. {
  371. const siblings = parent.children;
  372. const index = siblings.indexOf(item);
  373. if(index > -1) siblings.splice(index, 1);
  374. }
  375. if (!this._items.length) this.update(['1'], false);
  376. const inputValue = this.$element.find(`.think-multiple-item[data-id="${item.id}"] .think-multiple-item-text`).val();
  377. this.render();
  378. this.saveData(!!inputValue);
  379. }
  380. focus(name)
  381. {
  382. const $step = this.$element.find('.think-multiple-item[data-name="' + name + '"] .think-multiple-item-text');
  383. if($step.length) $step[0].focus();
  384. }
  385. addSib(focus = true)
  386. {
  387. if(this._items.length > 15) return;
  388. const fromName = this.$element.find('.think-multiple-item').last().attr('data-name');
  389. const item = this.getByName(fromName);
  390. if(!item) return;
  391. const newItem = this.updateItem(item.name);
  392. if(focus) this.focus(newItem.name);
  393. this.$element.find(`.think-multiple-item[data-id="${newItem.id}"] .think-multiple-item-text`).val('');
  394. }
  395. moveAfter(fromName, toName)
  396. {
  397. if(fromName === toName) return;
  398. const item = this.getByName(fromName);
  399. if(!item) return;
  400. item.name = toName;
  401. this.updateItem(item);
  402. }
  403. moveBefore(fromName, toName)
  404. {
  405. if(fromName === toName) return;
  406. const item = this.getByName(fromName);
  407. const toItem = this.getByName(toName);
  408. if(!item || !toItem) return;
  409. item.name = toItem.level > 1 ? `${toItem.parentName}.${+toItem.selfName - 1}` : `${+toItem.selfName - 1}`;
  410. this.updateItem(item);
  411. }
  412. }
  413. /* Define $.fn.ThinkMatrixOptions() helper. */
  414. ThinkMatrixOptions.defineFn();
  415. /* Extend ThinkMatrixOptions to zui object. */
  416. $.extend(zui, {ThinkMatrixOptions});