browseminiprogram.ui.js 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. if(!window.aiBrowseMiniProgram) window.aiBrowseMiniProgram = {};
  2. let firstGenerate = true;
  3. let aiChatView = null;
  4. const fieldArr = Array.from(Object.values(fields));
  5. /**
  6. * Format datetime.
  7. *
  8. * @param {Date?} date
  9. * @returns {string}
  10. */
  11. function formatDateTime(date = new Date())
  12. {
  13. const year = date.getFullYear();
  14. const month = date.getMonth() + 1;
  15. const day = date.getDate();
  16. const hours = date.getHours();
  17. const minutes = date.getMinutes();
  18. const formattedDate = `${year}/${month}/${day}`;
  19. const formattedTime = `${hours}:${minutes < 10 ? '0' + minutes : minutes}`;
  20. return `${formattedDate} ${formattedTime}`;
  21. }
  22. /**
  23. * Get form value map.
  24. */
  25. function getFormValue()
  26. {
  27. const fieldValueMap = new Map();
  28. fieldArr.forEach(field =>
  29. {
  30. const {id, name} = field;
  31. let $field = $(`[name="field-${id}"]`);
  32. if(!$field.length) $field = $(`.form-group[data-name="${name}"]`).find('input,textarea,select');
  33. const picker = zui.FormHelper.globalControls.picker($field, $('#miniProgramForm'));
  34. fieldValueMap.set(name, picker ? picker.getVal() : $field.prop('value'));
  35. });
  36. return fieldValueMap;
  37. }
  38. /**
  39. * Get required fields.
  40. *
  41. * @returns {string[]}
  42. */
  43. function getRequiredFields()
  44. {
  45. return fieldArr
  46. .filter(field => field.required === '1')
  47. .map(field => field.name);
  48. }
  49. /**
  50. * Generate prompt string.
  51. *
  52. * @param {Map<string, string>} fieldArr
  53. * @returns {string}
  54. */
  55. function generatePrompt(fieldArr)
  56. {
  57. let promptStr = prompt;
  58. fieldArr.forEach((value, key) =>
  59. {
  60. promptStr = promptStr.replace(new RegExp(`\\s&lt;${key}&gt;\\s`, 'g'), value);
  61. promptStr = promptStr.replace(new RegExp(`\\s<${key}>\\s`, 'g'), value);
  62. });
  63. return promptStr;
  64. }
  65. /**
  66. * Check required fields.
  67. *
  68. * @param {string[]} requiredFieldNames
  69. * @param {Map<string, string>} fieldArr
  70. * @returns {true|string}
  71. */
  72. function checkRequiredFields(requiredFieldNames, fieldArr)
  73. {
  74. for(const name of requiredFieldNames)
  75. {
  76. if(!fieldArr.has(name) || !fieldArr.get(name)) return name;
  77. }
  78. return true;
  79. }
  80. /**
  81. * Clear error tip.
  82. */
  83. function clearErrorTip()
  84. {
  85. $('.form-container').find('.has-error').removeClass('has-error');
  86. $('.form-container').find('.form-tip').remove();
  87. }
  88. /**
  89. * Send message to ai.
  90. *
  91. * @param {string} message
  92. * @param {boolean} renew
  93. */
  94. function sendMessagesToAI(message, renew)
  95. {
  96. const postOptions = {content: message, chat: {userPrompt: message, type: 'miniprogram', contexts: [{code: 'zentao-knowledgeLibs', data: {memory: {collections: (knowledgeLibs || '').split(',').filter(Boolean).map(x => `zentao:${x}`)}}}]}};
  97. aiChatView.$.postMessage(postOptions);
  98. }
  99. window.aiBrowseMiniProgram.initAIChatView = function(options)
  100. {
  101. const $aiChatView = $('#aiChatView');
  102. aiChatView = parent.zui.create('AIChatView', $aiChatView, $.extend({$notDestroyOnDetach: true}, options, {isEmbed: true}));
  103. if(!parent.isZaiOK) $('.generate-btn').addClass('disabled');
  104. };
  105. window.aiBrowseMiniProgram.startAIChat = function()
  106. {
  107. clearErrorTip();
  108. const fieldArr = getFormValue();
  109. const requiredFieldNames = getRequiredFields();
  110. const result = checkRequiredFields(requiredFieldNames, fieldArr);
  111. if(typeof result === 'string')
  112. {
  113. const $container = $('.form-container').find(`[data-name="${result}"]`);
  114. const fid = $container.attr('data-fid');
  115. const $formGroup = $container.closest('.form-group');
  116. $formGroup
  117. .attr('name', `field-${fid}`)
  118. .addClass('has-error')
  119. .append(`<div class="form-tip" id="field-${fid}Tip">${emptyNameWarning.replace('%s', result)}</div>`);
  120. return;
  121. }
  122. const promptStr = generatePrompt(fieldArr);
  123. if(firstGenerate)
  124. {
  125. $(this).text(regenerateLang);
  126. firstGenerate = false;
  127. }
  128. sendMessagesToAI(promptStr, true);
  129. };
  130. window.aiBrowseMiniProgram.handleStarBtnClick = function()
  131. {
  132. const $btn = $(this);
  133. const url = $btn.attr('data-url');
  134. $.get(url, function (response)
  135. {
  136. if(response.status == '1')
  137. {
  138. $btn.children('img').attr('src', 'static/svg/star.svg');
  139. $btn.attr('data-url', $btn.attr('data-url').replace('false', 'true'));
  140. }
  141. else
  142. {
  143. $btn.children('img').attr('src', 'static/svg/star-empty.svg');
  144. $btn.attr('data-url', $btn.attr('data-url').replace('true', 'false'));
  145. }
  146. }, 'json');
  147. };
  148. window.aiBrowseMiniProgram.handleRestBtnClick = function()
  149. {
  150. try
  151. {
  152. $('.form-container .picker-box').each(function()
  153. {
  154. $(this).zui('picker').$.clear();
  155. });
  156. $('.form-container .form-group .form-field').val('');
  157. }
  158. catch (error) {}
  159. };
  160. window.aiBrowseMiniProgram.backToSquare = function()
  161. {
  162. window.location.href = $.createLink('aiapp', 'square');
  163. };
  164. window.onPageUnmount = function()
  165. {
  166. if(aiChatView) aiChatView.destroy();
  167. };
  168. $(function()
  169. {
  170. $('#reload-current').on('click', () =>
  171. {
  172. loadCurrentPage('.mini-program');
  173. });
  174. });