script.js 140 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497
  1. /**
  2. * TrendRadar 配置文件编辑器核心逻辑
  3. * 特点:确保原始 YAML 的注释和格式 100% 保留
  4. */
  5. // ==========================================
  6. // 0. 注释高亮功能
  7. // ==========================================
  8. /**
  9. * 对文本应用高亮,# 后的内容显示为灰色
  10. */
  11. function applyHighlight(text) {
  12. const escape = s => s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
  13. return text.split('\n').map(line => {
  14. const idx = line.indexOf('#');
  15. if (idx === -1) return escape(line);
  16. return escape(line.slice(0, idx)) + '<span class="syntax-comment">' + escape(line.slice(idx)) + '</span>';
  17. }).join('\n');
  18. }
  19. /**
  20. * 更新高亮层
  21. */
  22. function updateBackdrop(textareaId, backdropId) {
  23. const ta = document.getElementById(textareaId);
  24. const bd = document.getElementById(backdropId);
  25. if (ta && bd) bd.innerHTML = applyHighlight(ta.value) + '\n';
  26. }
  27. /**
  28. * 同步滚动
  29. */
  30. function syncScroll(textareaId, backdropId) {
  31. const ta = document.getElementById(textareaId);
  32. const bd = document.getElementById(backdropId);
  33. if (ta && bd) {
  34. bd.scrollTop = ta.scrollTop;
  35. bd.scrollLeft = ta.scrollLeft;
  36. }
  37. }
  38. // ==========================================
  39. // 12. 支持项目弹窗逻辑
  40. // ==========================================
  41. /**
  42. * 打开支持弹窗
  43. */
  44. function openSupportModal() {
  45. const modal = document.getElementById('support-modal');
  46. if (modal) {
  47. modal.classList.remove('hidden');
  48. document.body.style.overflow = 'hidden'; // 禁止背景滚动
  49. }
  50. }
  51. /**
  52. * 关闭支持弹窗
  53. */
  54. function closeSupportModal() {
  55. const modal = document.getElementById('support-modal');
  56. if (modal) {
  57. modal.classList.add('hidden');
  58. document.body.style.overflow = ''; // 恢复滚动
  59. }
  60. }
  61. /**
  62. * 点击外部关闭
  63. */
  64. function closeSupportModalOutside(event) {
  65. if (event.target.id === 'support-modal') {
  66. closeSupportModal();
  67. }
  68. }
  69. window.openSupportModal = openSupportModal;
  70. window.closeSupportModal = closeSupportModal;
  71. window.closeSupportModalOutside = closeSupportModalOutside;
  72. const MODULE_DEFS = [
  73. { id: 1, name: "1. 基础设置", key: "app", editable: false },
  74. { id: 2, name: "2. 数据源 - 热榜平台", key: "platforms", editable: true },
  75. { id: 3, name: "3. 数据源 - RSS 订阅", key: "rss", editable: true },
  76. { id: 4, name: "4. 报告模式", key: "report", editable: true },
  77. { id: 5, name: "5. 推送内容控制", key: "display", editable: true },
  78. { id: 6, name: "6. 推送通知 (仅限时间窗口)", key: "notification", editable: true, partial: true },
  79. { id: 7, name: "7. 存储配置", key: "storage", editable: false },
  80. { id: 8, name: "8. AI 模型配置", key: "ai", editable: true },
  81. { id: 9, name: "9. AI 分析功能", key: "ai_analysis", editable: true },
  82. { id: 10, name: "10. AI 翻译功能", key: "ai_translation", editable: true },
  83. { id: 11, name: "11. 高级设置", key: "advanced", editable: false }
  84. ];
  85. // 初始默认内容 (用于空状态) - 只显示提示文本
  86. const INITIAL_YAML = `# 在此粘贴你的 config.yaml...
  87. # 或拖拽文件到编辑器区域
  88. # 或点击右上角"加载官网最新配置"`;
  89. // LocalStorage 键名
  90. const STORAGE_KEY_CONFIG = 'trendradar_config_yaml';
  91. const STORAGE_KEY_FREQUENCY = 'trendradar_frequency_txt';
  92. const STORAGE_KEY_CONFIG_TIME = 'trendradar_config_time';
  93. const STORAGE_KEY_FREQUENCY_TIME = 'trendradar_frequency_time';
  94. // 官网配置文件 URL
  95. const REMOTE_CONFIG_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/config/config.yaml';
  96. const REMOTE_FREQUENCY_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/config/frequency_words.txt';
  97. const REMOTE_VERSION_URL = 'https://raw.githubusercontent.com/sansan0/TrendRadar/refs/heads/master/version_configs';
  98. let currentYaml = "";
  99. let currentFrequency = "";
  100. let currentFrequencyData = null; // 缓存解析后的数据,避免重复解析导致索引错位
  101. let currentTab = "config";
  102. // ==========================================
  103. // 2. 初始化与事件绑定
  104. // ==========================================
  105. // 防抖定时器
  106. let configSaveTimer = null;
  107. let frequencySaveTimer = null;
  108. document.addEventListener('DOMContentLoaded', () => {
  109. const yamlEditor = document.getElementById('yaml-editor');
  110. const frequencyEditor = document.getElementById('frequency-editor');
  111. // 尝试从 LocalStorage 恢复配置
  112. const savedConfig = localStorage.getItem(STORAGE_KEY_CONFIG);
  113. const savedFrequency = localStorage.getItem(STORAGE_KEY_FREQUENCY);
  114. // 初始化编辑器
  115. if (savedConfig && savedConfig.trim() && savedConfig !== INITIAL_YAML) {
  116. yamlEditor.value = savedConfig;
  117. currentYaml = savedConfig;
  118. showToast('已恢复上次保存的配置', 'info');
  119. } else {
  120. yamlEditor.value = INITIAL_YAML;
  121. currentYaml = INITIAL_YAML;
  122. }
  123. if (savedFrequency && savedFrequency.trim()) {
  124. frequencyEditor.value = savedFrequency;
  125. currentFrequency = savedFrequency;
  126. } else {
  127. frequencyEditor.value = "# 在此粘贴你的 frequency_words.txt 内容...\n# 或拖拽文件到编辑器区域\n\n[GLOBAL_FILTER]\n\n[WORD_GROUPS]\n";
  128. currentFrequency = frequencyEditor.value;
  129. }
  130. // 渲染右侧模块列表
  131. renderModules();
  132. // 监听编辑器输入(实时同步到 UI + 防抖保存)
  133. yamlEditor.addEventListener('input', (e) => {
  134. currentYaml = e.target.value;
  135. updateBackdrop('yaml-editor', 'yaml-backdrop');
  136. syncYamlToUI();
  137. debounceSaveConfig();
  138. });
  139. frequencyEditor.addEventListener('input', (e) => {
  140. currentFrequency = e.target.value;
  141. updateBackdrop('frequency-editor', 'frequency-backdrop');
  142. currentFrequencyData = null;
  143. syncFrequencyToUI();
  144. debounceSaveFrequency();
  145. });
  146. // 同步滚动
  147. yamlEditor.addEventListener('scroll', () => syncScroll('yaml-editor', 'yaml-backdrop'));
  148. frequencyEditor.addEventListener('scroll', () => syncScroll('frequency-editor', 'frequency-backdrop'));
  149. // 初始化拖拽上传功能
  150. initDragAndDrop(yamlEditor, 'config');
  151. initDragAndDrop(frequencyEditor, 'frequency');
  152. // 页面关闭/刷新时立即保存
  153. window.addEventListener('beforeunload', saveAllToLocalStorage);
  154. document.addEventListener('keydown', function(e) {
  155. if ((e.ctrlKey || e.metaKey) && e.key === 's') {
  156. e.preventDefault();
  157. saveAllToLocalStorage();
  158. showToast('已手动保存配置', 'success');
  159. }
  160. });
  161. syncYamlToUI();
  162. updateBackdrop('yaml-editor', 'yaml-backdrop');
  163. updateBackdrop('frequency-editor', 'frequency-backdrop');
  164. updateSaveTimeDisplay();
  165. });
  166. // 防抖保存 config.yaml
  167. function debounceSaveConfig() {
  168. if (configSaveTimer) clearTimeout(configSaveTimer);
  169. configSaveTimer = setTimeout(() => {
  170. saveConfigToLocalStorage();
  171. }, 1000);
  172. }
  173. // 防抖保存 frequency_words.txt
  174. function debounceSaveFrequency() {
  175. if (frequencySaveTimer) clearTimeout(frequencySaveTimer);
  176. frequencySaveTimer = setTimeout(() => {
  177. saveFrequencyToLocalStorage();
  178. }, 1000);
  179. }
  180. // ==========================================
  181. // 2.1 拖拽上传功能
  182. // ==========================================
  183. function initDragAndDrop(editor, type) {
  184. const container = editor.parentElement;
  185. const dropOverlay = document.createElement('div');
  186. dropOverlay.className = 'drop-overlay hidden';
  187. dropOverlay.innerHTML = `
  188. <div class="drop-overlay-content">
  189. <i class="fa-solid fa-cloud-arrow-up text-4xl mb-2"></i>
  190. <div class="text-sm font-bold">释放以加载文件</div>
  191. <div class="text-xs opacity-75">${type === 'config' ? 'config.yaml' : 'frequency_words.txt'}</div>
  192. </div>
  193. `;
  194. container.style.position = 'relative';
  195. container.appendChild(dropOverlay);
  196. editor.addEventListener('dragover', (e) => {
  197. e.preventDefault();
  198. e.stopPropagation();
  199. dropOverlay.classList.remove('hidden');
  200. });
  201. editor.addEventListener('dragleave', (e) => {
  202. e.preventDefault();
  203. e.stopPropagation();
  204. if (!container.contains(e.relatedTarget)) {
  205. dropOverlay.classList.add('hidden');
  206. }
  207. });
  208. dropOverlay.addEventListener('dragleave', (e) => {
  209. e.preventDefault();
  210. e.stopPropagation();
  211. if (!container.contains(e.relatedTarget)) {
  212. dropOverlay.classList.add('hidden');
  213. }
  214. });
  215. dropOverlay.addEventListener('dragover', (e) => {
  216. e.preventDefault();
  217. e.stopPropagation();
  218. });
  219. dropOverlay.addEventListener('drop', (e) => {
  220. e.preventDefault();
  221. e.stopPropagation();
  222. dropOverlay.classList.add('hidden');
  223. handleFileDrop(e, type);
  224. });
  225. editor.addEventListener('drop', (e) => {
  226. e.preventDefault();
  227. e.stopPropagation();
  228. dropOverlay.classList.add('hidden');
  229. handleFileDrop(e, type);
  230. });
  231. }
  232. function handleFileDrop(e, type) {
  233. const files = e.dataTransfer.files;
  234. if (files.length === 0) return;
  235. const file = files[0];
  236. const validExtensions = type === 'config'
  237. ? ['.yaml', '.yml', '.txt']
  238. : ['.txt', '.yaml', '.yml'];
  239. const fileName = file.name.toLowerCase();
  240. const isValid = validExtensions.some(ext => fileName.endsWith(ext));
  241. if (!isValid) {
  242. showToast(`请拖入 ${type === 'config' ? 'YAML' : 'TXT'} 文件`, 'error');
  243. return;
  244. }
  245. const reader = new FileReader();
  246. reader.onload = (event) => {
  247. const content = event.target.result;
  248. if (type === 'config') {
  249. try {
  250. jsyaml.load(content);
  251. document.getElementById('yaml-editor').value = content;
  252. currentYaml = content;
  253. syncYamlToUI();
  254. showToast(`已加载: ${file.name}`, 'success');
  255. } catch (err) {
  256. showToast(`YAML 语法错误: ${err.message}`, 'error');
  257. // 仍然加载,让用户修复
  258. document.getElementById('yaml-editor').value = content;
  259. currentYaml = content;
  260. }
  261. } else {
  262. document.getElementById('frequency-editor').value = content;
  263. currentFrequency = content;
  264. syncFrequencyToUI();
  265. showToast(`已加载: ${file.name}`, 'success');
  266. }
  267. };
  268. reader.onerror = () => {
  269. showToast('文件读取失败', 'error');
  270. };
  271. reader.readAsText(file);
  272. }
  273. // ==========================================
  274. // 2.2 LocalStorage 保存与恢复
  275. // ==========================================
  276. // 保存 config.yaml
  277. function saveConfigToLocalStorage() {
  278. try {
  279. if (currentYaml && currentYaml.trim().length > 10) {
  280. const now = new Date().toISOString();
  281. localStorage.setItem(STORAGE_KEY_CONFIG, currentYaml);
  282. localStorage.setItem(STORAGE_KEY_CONFIG_TIME, now);
  283. updateSaveTimeDisplay();
  284. }
  285. } catch (e) {
  286. console.warn('LocalStorage 保存 config 失败:', e);
  287. }
  288. }
  289. // 保存 frequency_words.txt
  290. function saveFrequencyToLocalStorage() {
  291. try {
  292. if (currentFrequency && currentFrequency.trim().length > 10) {
  293. const now = new Date().toISOString();
  294. localStorage.setItem(STORAGE_KEY_FREQUENCY, currentFrequency);
  295. localStorage.setItem(STORAGE_KEY_FREQUENCY_TIME, now);
  296. updateSaveTimeDisplay();
  297. }
  298. } catch (e) {
  299. console.warn('LocalStorage 保存 frequency 失败:', e);
  300. }
  301. }
  302. // 保存全部(页面关闭时调用)
  303. function saveAllToLocalStorage() {
  304. saveConfigToLocalStorage();
  305. saveFrequencyToLocalStorage();
  306. }
  307. // 兼容旧调用
  308. function saveToLocalStorage() {
  309. saveAllToLocalStorage();
  310. }
  311. // 格式化时间显示
  312. function formatSaveTime(isoString) {
  313. if (!isoString) return '未保存';
  314. const date = new Date(isoString);
  315. const now = new Date();
  316. const diffMs = now - date;
  317. const diffMins = Math.floor(diffMs / 60000);
  318. const diffHours = Math.floor(diffMs / 3600000);
  319. const diffDays = Math.floor(diffMs / 86400000);
  320. if (diffMins < 1) return '刚刚';
  321. if (diffMins < 60) return `${diffMins} 分钟前`;
  322. if (diffHours < 24) return `${diffHours} 小时前`;
  323. if (diffDays < 7) return `${diffDays} 天前`;
  324. return date.toLocaleDateString('zh-CN', { month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
  325. }
  326. // 更新保存时间显示
  327. function updateSaveTimeDisplay() {
  328. const configTime = localStorage.getItem(STORAGE_KEY_CONFIG_TIME);
  329. const frequencyTime = localStorage.getItem(STORAGE_KEY_FREQUENCY_TIME);
  330. // 更新 config.yaml 的时间显示
  331. const configTimeEl = document.getElementById('config-save-time');
  332. const configLabelEl = document.getElementById('config-save-label');
  333. if (configTimeEl) {
  334. configTimeEl.textContent = formatSaveTime(configTime);
  335. configTimeEl.title = configTime ? new Date(configTime).toLocaleString('zh-CN') : '未保存';
  336. if (configLabelEl) {
  337. if (configTime) {
  338. configLabelEl.classList.remove('hidden');
  339. } else {
  340. configLabelEl.classList.add('hidden');
  341. }
  342. }
  343. }
  344. // 更新 frequency_words.txt 的时间显示
  345. const frequencyTimeEl = document.getElementById('frequency-save-time');
  346. const frequencyLabelEl = document.getElementById('frequency-save-label');
  347. if (frequencyTimeEl) {
  348. frequencyTimeEl.textContent = formatSaveTime(frequencyTime);
  349. frequencyTimeEl.title = frequencyTime ? new Date(frequencyTime).toLocaleString('zh-CN') : '未保存';
  350. if (frequencyLabelEl) {
  351. if (frequencyTime) {
  352. frequencyLabelEl.classList.remove('hidden');
  353. } else {
  354. frequencyLabelEl.classList.add('hidden');
  355. }
  356. }
  357. }
  358. }
  359. // ==========================================
  360. // 2.3 加载官网最新配置
  361. // ==========================================
  362. window.openLoadConfigModal = function() {
  363. // 创建选择弹窗
  364. const modal = document.createElement('div');
  365. modal.id = 'load-config-modal';
  366. modal.className = 'modal-overlay';
  367. modal.innerHTML = `
  368. <div class="modal-content" style="max-width: 420px;">
  369. <div class="flex items-center justify-between mb-4">
  370. <h3 class="text-lg font-bold text-gray-800"><i class="fa-solid fa-cloud-arrow-down mr-2 text-blue-500"></i>加载官网最新配置</h3>
  371. <button onclick="closeLoadConfigModal()" class="text-gray-400 hover:text-gray-600"><i class="fa-solid fa-times text-xl"></i></button>
  372. </div>
  373. <div class="text-sm text-gray-600 mb-4">
  374. 选择要从 GitHub 加载的配置文件:
  375. </div>
  376. <div class="space-y-3">
  377. <label class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 hover:bg-blue-50 hover:border-blue-300 cursor-pointer transition-colors">
  378. <input type="checkbox" id="load-config-yaml" checked class="w-4 h-4 text-blue-600 rounded">
  379. <div class="flex-1">
  380. <div class="font-medium text-gray-800">config.yaml</div>
  381. <div class="text-xs text-gray-500">系统配置、平台、AI、通知等</div>
  382. </div>
  383. <i class="fa-solid fa-file-code text-blue-400"></i>
  384. </label>
  385. <label class="flex items-center gap-3 p-3 rounded-lg border border-gray-200 hover:bg-blue-50 hover:border-blue-300 cursor-pointer transition-colors">
  386. <input type="checkbox" id="load-frequency-txt" checked class="w-4 h-4 text-blue-600 rounded">
  387. <div class="flex-1">
  388. <div class="font-medium text-gray-800">frequency_words.txt</div>
  389. <div class="text-xs text-gray-500">关键词组、过滤规则、正则逻辑</div>
  390. </div>
  391. <i class="fa-solid fa-filter text-orange-400"></i>
  392. </label>
  393. </div>
  394. <div class="text-xs text-gray-400 mt-3 p-2 bg-gray-50 rounded">
  395. <i class="fa-solid fa-info-circle mr-1"></i>
  396. 数据来源:<a href="https://github.com/sansan0/TrendRadar" target="_blank" class="text-blue-500 hover:underline">sansan0/TrendRadar</a>
  397. </div>
  398. <div class="flex justify-end gap-2 mt-4">
  399. <button onclick="closeLoadConfigModal()" class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">取消</button>
  400. <button onclick="confirmLoadConfig()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
  401. <i class="fa-solid fa-download mr-1"></i>加载选中
  402. </button>
  403. </div>
  404. </div>
  405. `;
  406. document.body.appendChild(modal);
  407. }
  408. window.closeLoadConfigModal = function() {
  409. const modal = document.getElementById('load-config-modal');
  410. if (modal) modal.remove();
  411. }
  412. window.confirmLoadConfig = async function() {
  413. const loadConfig = document.getElementById('load-config-yaml')?.checked;
  414. const loadFrequency = document.getElementById('load-frequency-txt')?.checked;
  415. if (!loadConfig && !loadFrequency) {
  416. showToast('请至少选择一个文件', 'warning');
  417. return;
  418. }
  419. closeLoadConfigModal();
  420. showToast('正在从 GitHub 加载...', 'info');
  421. try {
  422. const promises = [];
  423. if (loadConfig) promises.push(fetch(REMOTE_CONFIG_URL).then(r => ({ type: 'config', res: r })));
  424. if (loadFrequency) promises.push(fetch(REMOTE_FREQUENCY_URL).then(r => ({ type: 'frequency', res: r })));
  425. const results = await Promise.all(promises);
  426. for (const { type, res } of results) {
  427. if (!res.ok) {
  428. throw new Error(`${type === 'config' ? 'config.yaml' : 'frequency_words.txt'} 加载失败: ${res.status}`);
  429. }
  430. const text = await res.text();
  431. if (type === 'config') {
  432. // 验证 YAML 语法
  433. try {
  434. jsyaml.load(text);
  435. } catch (yamlErr) {
  436. showToast(`YAML 语法错误: ${yamlErr.message}`, 'error');
  437. continue;
  438. }
  439. document.getElementById('yaml-editor').value = text;
  440. currentYaml = text;
  441. updateBackdrop('yaml-editor', 'yaml-backdrop');
  442. syncYamlToUI();
  443. } else {
  444. document.getElementById('frequency-editor').value = text;
  445. currentFrequency = text;
  446. currentFrequencyData = null;
  447. updateBackdrop('frequency-editor', 'frequency-backdrop');
  448. syncFrequencyToUI();
  449. }
  450. }
  451. saveToLocalStorage();
  452. const loadedFiles = [];
  453. if (loadConfig) loadedFiles.push('config.yaml');
  454. if (loadFrequency) loadedFiles.push('frequency_words.txt');
  455. showToast(`已加载: ${loadedFiles.join(', ')}`, 'success');
  456. } catch (err) {
  457. console.error('加载远程配置失败:', err);
  458. showToast(`加载失败: ${err.message}`, 'error');
  459. }
  460. }
  461. // ==========================================
  462. // 2.4 Toast 提示
  463. // ==========================================
  464. function showToast(message, type = 'info') {
  465. // 移除已有的 toast
  466. const existingToast = document.querySelector('.toast-notification');
  467. if (existingToast) existingToast.remove();
  468. const toast = document.createElement('div');
  469. toast.className = `toast-notification toast-${type}`;
  470. const icons = {
  471. success: 'fa-check-circle',
  472. error: 'fa-times-circle',
  473. info: 'fa-info-circle',
  474. warning: 'fa-exclamation-triangle'
  475. };
  476. toast.innerHTML = `
  477. <i class="fa-solid ${icons[type] || icons.info}"></i>
  478. <span>${message}</span>
  479. `;
  480. document.body.appendChild(toast);
  481. // 动画入场
  482. requestAnimationFrame(() => {
  483. toast.classList.add('show');
  484. });
  485. // 自动消失
  486. setTimeout(() => {
  487. toast.classList.remove('show');
  488. setTimeout(() => toast.remove(), 300);
  489. }, 3000);
  490. }
  491. // ==========================================
  492. // 3. 渲染逻辑
  493. // ==========================================
  494. function renderModules() {
  495. const container = document.getElementById('config-panel');
  496. container.innerHTML = '';
  497. renderModuleNav();
  498. MODULE_DEFS.forEach(mod => {
  499. const card = document.createElement('div');
  500. card.className = `module-card ${mod.editable ? 'active' : 'disabled'}`;
  501. card.id = `module-${mod.key}`;
  502. const header = `
  503. <div class="module-header px-4 py-3 flex items-center justify-between cursor-pointer" onclick="scrollToModuleInEditor('${mod.key}')">
  504. <div class="flex items-center">
  505. <span class="text-sm font-bold">${mod.name}</span>
  506. <i class="fa-solid fa-arrow-up-right-from-square text-blue-400 text-[10px] ml-2 opacity-0 group-hover:opacity-100" title="跳转到左侧编辑器"></i>
  507. </div>
  508. ${!mod.editable ?
  509. '<span class="locked-badge text-[10px] text-gray-400 border border-gray-200 px-1.5 py-0.5 rounded">只读 (请在左侧编辑)</span>' :
  510. '<i class="fa-solid fa-chevron-down text-gray-400 text-xs"></i>'}
  511. </div>
  512. `;
  513. const body = mod.editable ? `<div class="module-body p-5 border-t border-gray-50 space-y-4" id="controls-${mod.key}"></div>` : '';
  514. card.innerHTML = header + body;
  515. container.appendChild(card);
  516. if (mod.editable) {
  517. renderControls(mod);
  518. }
  519. });
  520. }
  521. // 渲染模块导航栏
  522. function renderModuleNav() {
  523. const nav = document.getElementById('module-nav');
  524. if (!nav) return;
  525. nav.innerHTML = MODULE_DEFS.map(mod => `
  526. <button onclick="scrollToModuleInEditor('${mod.key}')"
  527. class="module-nav-btn text-[10px] px-2 py-1 rounded ${mod.editable ? 'bg-blue-100 text-blue-700 hover:bg-blue-200' : 'bg-gray-100 text-gray-500 hover:bg-gray-200'} transition-colors"
  528. title="跳转到模块 ${mod.id}">
  529. ${mod.id}
  530. </button>
  531. `).join('');
  532. }
  533. // 切换组名编辑状态
  534. window.toggleGroupNameEdit = function(btn) {
  535. const container = btn.parentNode;
  536. const span = container.querySelector('span.text-sm');
  537. const input = container.querySelector('input[type="text"]');
  538. if (input.classList.contains('hidden')) {
  539. // 进入编辑模式
  540. span.classList.add('hidden');
  541. input.classList.remove('hidden');
  542. input.focus();
  543. btn.innerHTML = '<i class="fa-solid fa-check text-green-600"></i>';
  544. } else {
  545. // 退出编辑模式
  546. span.classList.remove('hidden');
  547. input.classList.add('hidden');
  548. btn.innerHTML = '<i class="fa-solid fa-pen"></i>';
  549. // 如果内容变化,已经通过 onchange 触发更新
  550. span.textContent = input.value;
  551. }
  552. }
  553. // 跳转到左侧编辑器中对应词组的位置
  554. window.scrollToWordGroupInEditor = function(groupIndex) {
  555. const editor = document.getElementById('frequency-editor');
  556. // 重新解析以确保行号准确
  557. const data = parseFrequencyText(editor.value);
  558. if (!data.wordGroups[groupIndex]) return;
  559. const targetLineIndex = data.wordGroups[groupIndex].startLine;
  560. if (targetLineIndex === undefined || targetLineIndex === -1) return;
  561. const lines = editor.value.split('\n');
  562. const lineHeight = 19.5;
  563. const scrollPosition = targetLineIndex * lineHeight;
  564. // 设置光标选区
  565. let charCount = 0;
  566. for (let i = 0; i < targetLineIndex; i++) {
  567. charCount += lines[i].length + 1; // +1 for newline
  568. }
  569. editor.focus();
  570. editor.setSelectionRange(charCount, charCount + lines[targetLineIndex].length);
  571. editor.scrollTop = scrollPosition - 50;
  572. // 高亮效果
  573. editor.style.transition = 'background-color 0.3s';
  574. const originalBg = editor.style.backgroundColor;
  575. editor.style.backgroundColor = '#2d4a7c';
  576. setTimeout(() => {
  577. editor.style.backgroundColor = originalBg;
  578. }, 300);
  579. }
  580. // 跳转到左侧编辑器中对应模块的位置
  581. window.scrollToModuleInEditor = function(modKey) {
  582. const editor = document.getElementById('yaml-editor');
  583. const yaml = editor.value;
  584. const lines = yaml.split('\n');
  585. // 查找模块标题注释行(# N. 模块名)
  586. let targetLineIndex = -1;
  587. const mod = MODULE_DEFS.find(m => m.key === modKey);
  588. if (!mod) return;
  589. // 直接匹配包含模块编号的标题行,如:# 5. 推送内容控制
  590. const moduleTitlePattern = new RegExp(`^#\\s*${mod.id}\\.\\s+`, 'i');
  591. for (let i = 0; i < lines.length; i++) {
  592. const line = lines[i];
  593. // 匹配模块标题行(包含编号的注释行)
  594. if (moduleTitlePattern.test(line)) {
  595. targetLineIndex = i;
  596. break;
  597. }
  598. }
  599. // 如果没找到标题行,尝试查找模块键名(如 platforms:)
  600. if (targetLineIndex === -1) {
  601. for (let i = 0; i < lines.length; i++) {
  602. if (lines[i].match(new RegExp(`^${modKey}:\\s*`))) {
  603. targetLineIndex = i;
  604. break;
  605. }
  606. }
  607. }
  608. if (targetLineIndex === -1) return;
  609. // 计算目标位置并滚动
  610. const lineHeight = 19.5;
  611. const scrollPosition = targetLineIndex * lineHeight;
  612. // 设置光标位置
  613. const textBeforeTarget = lines.slice(0, targetLineIndex).join('\n').length + (targetLineIndex > 0 ? 1 : 0);
  614. editor.focus();
  615. editor.setSelectionRange(textBeforeTarget, textBeforeTarget + lines[targetLineIndex].length);
  616. editor.scrollTop = scrollPosition - 5;
  617. // 高亮提示(闪烁效果)
  618. editor.style.transition = 'background-color 0.3s';
  619. const originalBg = editor.style.backgroundColor;
  620. editor.style.backgroundColor = '#2d4a7c';
  621. setTimeout(() => {
  622. editor.style.backgroundColor = originalBg;
  623. }, 300);
  624. }
  625. function renderControls(mod) {
  626. const body = document.getElementById(`controls-${mod.key}`);
  627. // 根据模块 key 定义不同的 UI 控件
  628. let html = "";
  629. switch(mod.key) {
  630. case "platforms":
  631. html = createToggleControl(mod.key, "enabled", "启用热榜抓取");
  632. html += `<div class="mt-4 mb-2 text-xs font-bold text-gray-700">平台列表 <span class="text-gray-400 font-normal">(可拖拽排序)</span></div>`;
  633. html += `<div id="platforms-list" class="space-y-2"></div>`;
  634. html += `<div class="flex items-center gap-2 mt-3">
  635. <button onclick="openPlatformModal()" class="text-xs bg-green-600 text-white px-3 py-1.5 rounded hover:bg-green-700 transition-colors">
  636. <i class="fa-solid fa-plus mr-1"></i>添加平台
  637. </button>
  638. <a href="https://github.com/sansan0/TrendRadar?tab=readme-ov-file#%E9%85%8D%E7%BD%AE%E8%AF%A6%E8%A7%A3" target="_blank" class="text-xs bg-gray-100 text-gray-600 px-3 py-1.5 rounded hover:bg-gray-200 transition-colors border border-gray-200 flex items-center gap-1 no-underline">
  639. <i class="fa-solid fa-circle-question text-gray-400"></i>添加其它平台
  640. </a>
  641. </div>`;
  642. break;
  643. case "rss":
  644. html = createToggleControl(mod.key, "enabled", "启用 RSS 抓取");
  645. html += `<div class="mt-3 mb-2 text-xs font-bold text-gray-700">新鲜度过滤</div>`;
  646. html += createToggleControl(mod.key, "freshness_filter.enabled", "启用新鲜度过滤");
  647. html += createNumberControl(mod.key, "freshness_filter.max_age_days", "最大文章年龄 (天)");
  648. html += `<div class="mt-4 mb-2 text-xs font-bold text-gray-700">RSS 源列表</div>`;
  649. html += `<div id="rss-feeds-list" class="space-y-2"></div>`;
  650. html += `<div class="flex items-center gap-2 mt-3">
  651. <button onclick="openRssModal()" class="text-xs bg-green-600 text-white px-3 py-1.5 rounded hover:bg-green-700 transition-colors">
  652. <i class="fa-solid fa-plus mr-1"></i>添加 RSS 源
  653. </button>
  654. <div class="text-xs text-gray-500 italic">
  655. (内附 RSS 源参考库)
  656. </div>
  657. </div>`;
  658. html += `<div class="text-xs text-orange-600 mt-2 p-2 bg-orange-50 rounded border border-orange-200">
  659. <i class="fa-solid fa-triangle-exclamation mr-1"></i>
  660. <strong>注意:</strong>部分海外媒体内容可能涉及敏感话题,AI 模型可能拒绝翻译或分析,建议根据实际需求筛选订阅源。
  661. </div>`;
  662. break;
  663. case "report":
  664. html = createSelectControl(mod.key, "mode", "报告模式", ["current", "daily", "incremental"]);
  665. html += createSelectControl(mod.key, "display_mode", "分组维度", ["keyword", "platform"]);
  666. html += createToggleControl(mod.key, "sort_by_position_first", "按定义顺序排序");
  667. html += createNumberControl(mod.key, "rank_threshold", "排名高亮阈值");
  668. html += createNumberControl(mod.key, "max_news_per_keyword", "每个关键词最大显示数量");
  669. break;
  670. case "display":
  671. html = `<div class="text-xs font-bold text-gray-700 mb-2">推送内容控制 <span class="text-gray-400 font-normal">(可拖拽排序)</span></div>`;
  672. html += `<div id="display-regions-list" class="space-y-2"></div>`;
  673. html += `<div class="text-xs text-gray-500 mt-2 mb-6">
  674. <i class="fa-solid fa-lightbulb mr-1"></i>
  675. 提示:列表顺序决定了报告中的显示顺序
  676. </div>`;
  677. // Standalone Configuration Section
  678. html += `<div class="border-t border-gray-200 pt-4 mt-4">`;
  679. html += `<div class="text-xs font-bold text-gray-700 mb-3">独立展示区配置 <span class="text-gray-400 font-normal">(仅在上方开启"独立展示区"时生效)</span></div>`;
  680. html += createNumberControl(mod.key, "standalone.max_items", "每个源最多展示条数");
  681. html += `<div class="mt-3 mb-2 text-xs font-medium text-gray-700">选择要展示的热榜平台</div>`;
  682. html += `<div id="standalone-platforms-list" class="max-h-40 overflow-y-auto border border-gray-200 rounded p-2 bg-gray-50 grid grid-cols-2 gap-2"></div>`;
  683. html += `<div class="mt-3 mb-2 text-xs font-medium text-gray-700">选择要展示的 RSS 源</div>`;
  684. html += `<div id="standalone-rss-list" class="max-h-40 overflow-y-auto border border-gray-200 rounded p-2 bg-gray-50 grid grid-cols-1 gap-2"></div>`;
  685. html += `</div>`;
  686. setTimeout(() => {
  687. renderDisplayRegionsList();
  688. renderStandaloneLists();
  689. }, 0);
  690. break;
  691. case "notification":
  692. // 只有推送窗口可见
  693. html = `<div class="text-xs font-bold text-blue-600 mb-2">推送时间窗口设置</div>`;
  694. html += createToggleControl(mod.key, "push_window.enabled", "开启时间窗口");
  695. html += `<div class="grid grid-cols-2 gap-4">
  696. ${createInputControl(mod.key, "push_window.start", "开始时间 (HH:MM)")}
  697. ${createInputControl(mod.key, "push_window.end", "结束时间 (HH:MM)")}
  698. </div>`;
  699. html += createToggleControl(mod.key, "push_window.once_per_day", "窗口内仅推送一次");
  700. html += `<div class="text-xs text-gray-500 mt-2">通知渠道配置请在左侧编辑器中修改</div>`;
  701. break;
  702. case "ai":
  703. html = createInputControl(mod.key, "model", "模型名称");
  704. html += createInputControl(mod.key, "api_key", "API Key", "password");
  705. html += createInputControl(mod.key, "api_base", "API Base URL (可选)");
  706. html += createNumberControl(mod.key, "timeout", "请求超时 (秒)");
  707. html += createNumberControl(mod.key, "temperature", "采样温度 (0.0-2.0)");
  708. html += createNumberControl(mod.key, "max_tokens", "最大生成 Token 数");
  709. break;
  710. case "ai_analysis":
  711. html = createToggleControl(mod.key, "enabled", "开启 AI 分析报告");
  712. // AI 分析时间窗口设置
  713. html += `<div class="text-xs font-bold text-blue-600 mb-2 mt-4">AI 分析时间窗口设置</div>`;
  714. html += createToggleControl(mod.key, "analysis_window.enabled", "开启时间窗口");
  715. html += `<div class="grid grid-cols-2 gap-4">
  716. ${createInputControl(mod.key, "analysis_window.start", "开始时间 (HH:MM)")}
  717. ${createInputControl(mod.key, "analysis_window.end", "结束时间 (HH:MM)")}
  718. </div>`;
  719. html += createToggleControl(mod.key, "analysis_window.once_per_day", "窗口内仅分析一次");
  720. // 其他 AI 分析配置
  721. html += `<div class="text-xs font-bold text-blue-600 mb-2 mt-4">分析内容配置</div>`;
  722. html += createInputControl(mod.key, "language", "输出语言");
  723. html += createInputControl(mod.key, "prompt_file", "提示词配置文件");
  724. html += createSelectControl(mod.key, "mode", "AI 分析模式", ["follow_report", "daily", "current", "incremental"]);
  725. html += createNumberControl(mod.key, "max_news_for_analysis", "最大分析条数");
  726. html += createToggleControl(mod.key, "include_rss", "包含 RSS 内容");
  727. html += createToggleControl(mod.key, "include_rank_timeline", "传递完整排名时间线");
  728. break;
  729. case "ai_translation":
  730. html = createToggleControl(mod.key, "enabled", "开启 AI 自动翻译");
  731. html += createInputControl(mod.key, "language", "目标语言");
  732. html += createInputControl(mod.key, "prompt_file", "提示词配置文件");
  733. break;
  734. }
  735. body.innerHTML = html;
  736. // 绑定事件
  737. body.querySelectorAll('input, select').forEach(el => {
  738. el.addEventListener('change', (e) => {
  739. updateYamlFromUI(mod.key, e.target.dataset.path, e.target);
  740. });
  741. });
  742. }
  743. // ==========================================
  744. // 4. 同步逻辑 (YAML -> UI)
  745. // ==========================================
  746. function syncYamlToUI() {
  747. try {
  748. const doc = jsyaml.load(currentYaml);
  749. if (!doc) return;
  750. MODULE_DEFS.filter(m => m.editable).forEach(mod => {
  751. const modData = doc[mod.key];
  752. if (!modData) return;
  753. const controls = document.querySelectorAll(`#controls-${mod.key} [data-path]`);
  754. controls.forEach(ctrl => {
  755. const path = ctrl.dataset.path.split('.');
  756. let val = modData;
  757. for (const part of path) {
  758. val = val ? val[part] : undefined;
  759. }
  760. if (ctrl.type === 'checkbox') {
  761. ctrl.checked = !!val;
  762. } else {
  763. ctrl.value = val !== undefined ? val : "";
  764. }
  765. });
  766. });
  767. renderPlatformsList();
  768. renderRssFeedsList();
  769. renderStandaloneLists();
  770. } catch (e) {
  771. // 解析失败时不更新 UI,保持原有状态
  772. }
  773. }
  774. // ==========================================
  775. // 5. 更新逻辑 (UI -> YAML) - 核心难点:正则保留注释
  776. // ==========================================
  777. function updateYamlFromUI(modKey, path, el) {
  778. let newVal = el.type === 'checkbox' ? el.checked : el.value;
  779. // 如果是数字类型
  780. if (el.type === 'number') {
  781. newVal = parseFloat(newVal);
  782. if (isNaN(newVal)) newVal = 0;
  783. }
  784. const editor = document.getElementById('yaml-editor');
  785. let yaml = editor.value;
  786. const lines = yaml.split('\n');
  787. const pathParts = path.split('.');
  788. // 找到模块的起始行
  789. let moduleStartLine = -1;
  790. let moduleEndLine = lines.length;
  791. for (let i = 0; i < lines.length; i++) {
  792. const line = lines[i];
  793. // 匹配模块开始(非缩进的 key:)
  794. const moduleMatch = line.match(/^([a-z_]+):/);
  795. if (moduleMatch) {
  796. if (moduleMatch[1] === modKey) {
  797. moduleStartLine = i;
  798. } else if (moduleStartLine >= 0) {
  799. // 找到下一个模块,记录当前模块结束位置
  800. moduleEndLine = i;
  801. break;
  802. }
  803. }
  804. }
  805. if (moduleStartLine < 0) return;
  806. // 在模块内查找目标路径
  807. let targetLine = -1;
  808. let currentIndent = 0;
  809. let searchKey = pathParts[pathParts.length - 1];
  810. for (let i = moduleStartLine + 1; i < moduleEndLine; i++) {
  811. const line = lines[i];
  812. if (line.trim() === '' || line.trim().startsWith('#')) continue;
  813. // 检查是否匹配目标键
  814. const indent = line.search(/\S/);
  815. const keyMatch = line.match(/^\s*([a-z_]+):\s*(.*)/i);
  816. if (keyMatch && keyMatch[1] === searchKey) {
  817. // 如果是嵌套路径,需要检查缩进层级是否正确
  818. if (pathParts.length > 1) {
  819. // 简化处理:对于嵌套路径,确保在正确的父级下
  820. let valid = true;
  821. for (let j = 0; j < pathParts.length - 1; j++) {
  822. let found = false;
  823. for (let k = moduleStartLine + 1; k < i; k++) {
  824. const parentMatch = lines[k].match(/^\s*([a-z_]+):/i);
  825. if (parentMatch && parentMatch[1] === pathParts[j]) {
  826. found = true;
  827. break;
  828. }
  829. }
  830. if (!found) {
  831. valid = false;
  832. break;
  833. }
  834. }
  835. if (!valid) continue;
  836. }
  837. targetLine = i;
  838. break;
  839. }
  840. }
  841. if (targetLine < 0) return;
  842. // 更新该行,保留注释
  843. const originalLine = lines[targetLine];
  844. const match = originalLine.match(/^(\s*[a-z_]+:\s*)(.*)$/i);
  845. if (match) {
  846. const prefix = match[1];
  847. const rest = match[2];
  848. // 提取原有注释
  849. const commentMatch = rest.match(/(\s*#.*)$/);
  850. const comment = commentMatch ? commentMatch[1] : '';
  851. // 格式化新值
  852. let formattedVal = newVal;
  853. if (typeof newVal === 'string') {
  854. // 获取原值部分(去除注释后的部分)
  855. const valPart = rest.slice(0, rest.length - comment.length).trim();
  856. // 检查原值是否带有引号
  857. const isOriginalQuoted = (valPart.startsWith('"') && valPart.endsWith('"')) ||
  858. (valPart.startsWith("'") && valPart.endsWith("'"));
  859. // 如果原值有引号,或者新值包含特殊字符(空格、冒号、井号、引号)或者是空字符串,则添加双引号
  860. if (isOriginalQuoted || newVal.includes(':') || newVal.includes('#') ||
  861. newVal.includes('"') || newVal.includes(' ') || newVal === "") {
  862. formattedVal = `"${newVal.replace(/"/g, '\\"')}"`;
  863. }
  864. }
  865. // 构建新行
  866. lines[targetLine] = `${prefix}${formattedVal}${comment}`;
  867. }
  868. // 更新编辑器
  869. editor.value = lines.join('\n');
  870. currentYaml = editor.value;
  871. updateBackdrop('yaml-editor', 'yaml-backdrop');
  872. debounceSaveConfig();
  873. }
  874. // ==========================================
  875. // 6. UI 组件工厂
  876. // ==========================================
  877. function createToggleControl(mod, path, label) {
  878. const id = `toggle-${mod}-${path.replace('.', '-')}`;
  879. return `
  880. <div class="flex items-center justify-between">
  881. <label for="${id}" class="text-xs font-medium text-gray-700">${label}</label>
  882. <div class="relative inline-block w-10 mr-2 align-middle select-none">
  883. <input type="checkbox" id="${id}" data-path="${path}" class="toggle-checkbox absolute block w-5 h-5 rounded-full bg-white border-4 appearance-none cursor-pointer transition-all duration-200 ease-in-out"/>
  884. <label for="${id}" class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer"></label>
  885. </div>
  886. </div>
  887. `;
  888. }
  889. function createInputControl(mod, path, label, type = "text") {
  890. return `
  891. <div>
  892. <label class="block text-[10px] uppercase tracking-wider font-bold text-gray-400 mb-1">${label}</label>
  893. <input type="${type}" data-path="${path}" class="bg-white border-gray-300 focus:border-blue-500" placeholder="未设置">
  894. </div>
  895. `;
  896. }
  897. function createNumberControl(mod, path, label) {
  898. return `
  899. <div class="flex items-center justify-between">
  900. <label class="text-xs font-medium text-gray-700">${label}</label>
  901. <input type="number" data-path="${path}" class="w-20 text-right bg-white border-gray-300" style="width: 80px">
  902. </div>
  903. `;
  904. }
  905. function createSelectControl(mod, path, label, options) {
  906. const optionsHtml = options.map(opt => `<option value="${opt}">${opt}</option>`).join('');
  907. return `
  908. <div>
  909. <label class="block text-[10px] uppercase tracking-wider font-bold text-gray-400 mb-1">${label}</label>
  910. <select data-path="${path}" class="bg-white border-gray-300">
  911. ${optionsHtml}
  912. </select>
  913. </div>
  914. `;
  915. }
  916. // ==========================================
  917. // 7. 工具函数
  918. // ==========================================
  919. window.copyResult = function() {
  920. const yamlEditor = document.getElementById('yaml-editor');
  921. const frequencyEditor = document.getElementById('frequency-editor');
  922. const editor = currentTab === 'config' ? yamlEditor : frequencyEditor;
  923. editor.select();
  924. document.execCommand('copy');
  925. const btn = document.querySelector('button[onclick="copyResult()"]');
  926. const original = btn.innerHTML;
  927. btn.innerHTML = '<i class="fa-solid fa-check mr-1.5"></i>已复制!';
  928. setTimeout(() => btn.innerHTML = original, 2000);
  929. }
  930. window.resetToDefault = function() {
  931. if (confirm('确定要重置为初始状态吗?未保存的修改将丢失。')) {
  932. const yamlEditor = document.getElementById('yaml-editor');
  933. const frequencyEditor = document.getElementById('frequency-editor');
  934. if (currentTab === 'config') {
  935. yamlEditor.value = INITIAL_YAML;
  936. currentYaml = INITIAL_YAML;
  937. updateBackdrop('yaml-editor', 'yaml-backdrop');
  938. // 清除 LocalStorage 中的 config 数据
  939. localStorage.removeItem(STORAGE_KEY_CONFIG);
  940. localStorage.removeItem(STORAGE_KEY_CONFIG_TIME);
  941. // 重置 UI:重新渲染模块以清空输入框,因为 INITIAL_YAML 可能为空导致 syncYamlToUI 不执行更新
  942. renderModules();
  943. syncYamlToUI();
  944. updateSaveTimeDisplay();
  945. } else {
  946. frequencyEditor.value = "# 在此粘贴你的 frequency_words.txt 内容...\n\n[GLOBAL_FILTER]\n\n[WORD_GROUPS]\n";
  947. currentFrequency = frequencyEditor.value;
  948. updateBackdrop('frequency-editor', 'frequency-backdrop');
  949. // 清除 LocalStorage 中的 frequency 数据
  950. localStorage.removeItem(STORAGE_KEY_FREQUENCY);
  951. localStorage.removeItem(STORAGE_KEY_FREQUENCY_TIME);
  952. syncFrequencyToUI();
  953. updateSaveTimeDisplay();
  954. }
  955. showToast('已重置为初始状态', 'success');
  956. }
  957. }
  958. // ==========================================
  959. // 8. Tab 切换功能
  960. // ==========================================
  961. window.switchTab = function(tab) {
  962. currentTab = tab;
  963. // 更新 Tab 按钮状态
  964. document.getElementById('tab-config').classList.toggle('active', tab === 'config');
  965. document.getElementById('tab-frequency').classList.toggle('active', tab === 'frequency');
  966. const configBtn = document.getElementById('tab-config');
  967. const freqBtn = document.getElementById('tab-frequency');
  968. if (tab === 'config') {
  969. configBtn.className = "tab-button active px-4 py-2 text-xs font-bold text-gray-300 hover:bg-[#2d2d30] transition-colors border-b-2 border-blue-500";
  970. freqBtn.className = "tab-button px-4 py-2 text-xs font-bold text-gray-500 hover:bg-[#2d2d30] transition-colors border-b-2 border-transparent";
  971. } else {
  972. configBtn.className = "tab-button px-4 py-2 text-xs font-bold text-gray-500 hover:bg-[#2d2d30] transition-colors border-b-2 border-transparent";
  973. freqBtn.className = "tab-button active px-4 py-2 text-xs font-bold text-gray-300 hover:bg-[#2d2d30] transition-colors border-b-2 border-blue-500";
  974. }
  975. // 更新编辑器显示
  976. document.getElementById('yaml-editor-wrap').classList.toggle('hidden', tab !== 'config');
  977. document.getElementById('frequency-editor-wrap').classList.toggle('hidden', tab !== 'frequency');
  978. // 更新右侧面板
  979. document.getElementById('config-panel').classList.toggle('hidden', tab !== 'config');
  980. document.getElementById('frequency-panel').classList.toggle('hidden', tab !== 'frequency');
  981. // 更新模块导航栏显示状态:只在 config 模式下显示
  982. const moduleNav = document.getElementById('module-nav');
  983. if (moduleNav) {
  984. moduleNav.classList.toggle('hidden', tab !== 'config');
  985. }
  986. // 更新保存时间显示
  987. const saveTimeConfig = document.getElementById('save-time-config');
  988. const saveTimeFrequency = document.getElementById('save-time-frequency');
  989. if (saveTimeConfig) saveTimeConfig.classList.toggle('hidden', tab !== 'config');
  990. if (saveTimeFrequency) saveTimeFrequency.classList.toggle('hidden', tab !== 'frequency');
  991. // 更新右侧标题
  992. const versionBtn = document.getElementById('version-check-btn');
  993. if (tab === 'config') {
  994. document.getElementById('right-panel-title').textContent = '配置模块';
  995. if (versionBtn) versionBtn.title = "检测 config.yaml 版本";
  996. } else {
  997. document.getElementById('right-panel-title').textContent = '频率词编辑';
  998. if (versionBtn) versionBtn.title = "检测 frequency_words.txt 版本";
  999. }
  1000. if (tab === 'frequency') {
  1001. renderFrequencyPanel();
  1002. }
  1003. }
  1004. // ==========================================
  1005. // 9. Frequency 编辑器功能
  1006. // ==========================================
  1007. function parseFrequencyText(text) {
  1008. const result = {
  1009. globalFilter: [],
  1010. wordGroups: [],
  1011. originalText: text // 保存原始文本
  1012. };
  1013. const lines = text.split('\n');
  1014. let currentSection = null;
  1015. let currentGroup = null;
  1016. let lastLineWasAlias = false; // 追踪上一行是否为别名行
  1017. let relatedGroupsBuffer = []; // 缓存连续的相关组
  1018. let pendingComments = []; // 缓存待分配的注释行
  1019. // 辅助函数:保存缓存的相关组
  1020. function flushRelatedGroups() {
  1021. if (relatedGroupsBuffer.length > 0) {
  1022. // 如果有多个连续的组,标记它们为相关组
  1023. if (relatedGroupsBuffer.length > 1) {
  1024. relatedGroupsBuffer.forEach((group, idx) => {
  1025. group.isRelatedGroup = true;
  1026. group.relatedGroupIndex = idx;
  1027. group.relatedGroupTotal = relatedGroupsBuffer.length;
  1028. });
  1029. }
  1030. result.wordGroups.push(...relatedGroupsBuffer);
  1031. relatedGroupsBuffer = [];
  1032. }
  1033. }
  1034. for (let i = 0; i < lines.length; i++) {
  1035. const line = lines[i];
  1036. const trimmed = line.trim();
  1037. // 收集注释行(在 [WORD_GROUPS] 区域内)
  1038. if (trimmed.startsWith('#') && currentSection === 'groups') {
  1039. pendingComments.push(line);
  1040. continue;
  1041. }
  1042. // 跳过注释(非 [WORD_GROUPS] 区域)
  1043. if (trimmed.startsWith('#')) continue;
  1044. // 空行:结束当前词组和相关组缓存
  1045. if (!trimmed) {
  1046. if (currentGroup) {
  1047. // 保存当前词组到缓存
  1048. relatedGroupsBuffer.push(currentGroup);
  1049. currentGroup = null;
  1050. }
  1051. // 空行表示相关组结束,刷新缓存
  1052. flushRelatedGroups();
  1053. lastLineWasAlias = false;
  1054. // 在 [WORD_GROUPS] 区域内,空行加入待分配注释(保留空行结构)
  1055. if (currentSection === 'groups') {
  1056. pendingComments.push('');
  1057. }
  1058. continue;
  1059. }
  1060. // 检测区域标记
  1061. if (trimmed === '[GLOBAL_FILTER]') {
  1062. currentSection = 'global';
  1063. continue;
  1064. }
  1065. if (trimmed === '[WORD_GROUPS]') {
  1066. currentSection = 'groups';
  1067. continue;
  1068. }
  1069. // 处理内容
  1070. if (currentSection === 'global') {
  1071. result.globalFilter.push(trimmed);
  1072. } else if (currentSection === 'groups') {
  1073. // 检测组别名 [组名]
  1074. const groupNameMatch = trimmed.match(/^\[([^\]]+)\]$/);
  1075. if (groupNameMatch && !['GLOBAL_FILTER', 'WORD_GROUPS'].includes(groupNameMatch[1])) {
  1076. // 保存当前词组到缓存
  1077. if (currentGroup) {
  1078. relatedGroupsBuffer.push(currentGroup);
  1079. }
  1080. // 刷新缓存(组别名独立成组)
  1081. flushRelatedGroups();
  1082. // 创建组别名类型
  1083. currentGroup = {
  1084. type: 'group-name',
  1085. name: groupNameMatch[1],
  1086. keywords: [],
  1087. startLine: i,
  1088. precedingComments: pendingComments.length > 0 ? [...pendingComments] : []
  1089. };
  1090. pendingComments = [];
  1091. lastLineWasAlias = false;
  1092. } else {
  1093. // 检测 => 别名语法(允许右侧为空)
  1094. const aliasMatch = trimmed.match(/^(.+?)\s*=>\s*(.*)$/);
  1095. if (aliasMatch) {
  1096. const keyword = aliasMatch[1].trim();
  1097. const alias = aliasMatch[2].trim();
  1098. // 关键逻辑:如果上一行也是别名行(无空行分隔),则归入连续别名组
  1099. if (lastLineWasAlias && currentGroup && (currentGroup.type === 'alias' || currentGroup.type === 'alias-group')) {
  1100. // 如果当前是单个别名,升级为别名组
  1101. if (currentGroup.type === 'alias') {
  1102. currentGroup.type = 'alias-group';
  1103. }
  1104. // 添加到别名组
  1105. currentGroup.items.push({ keyword, alias });
  1106. } else {
  1107. // 新的单个别名(可能会升级为别名组)
  1108. if (currentGroup) {
  1109. // 保存当前词组到缓存(而不是直接添加到结果)
  1110. relatedGroupsBuffer.push(currentGroup);
  1111. }
  1112. currentGroup = {
  1113. type: 'alias',
  1114. items: [{ keyword, alias }],
  1115. startLine: i,
  1116. precedingComments: pendingComments.length > 0 ? [...pendingComments] : []
  1117. };
  1118. pendingComments = [];
  1119. }
  1120. lastLineWasAlias = true;
  1121. } else {
  1122. // 普通关键词
  1123. if (!currentGroup || currentGroup.type === 'alias' || currentGroup.type === 'alias-group') {
  1124. // 如果当前是别名类型,需要先保存到缓存
  1125. if (currentGroup) {
  1126. relatedGroupsBuffer.push(currentGroup);
  1127. }
  1128. // 创建新的普通词组
  1129. currentGroup = {
  1130. type: 'plain',
  1131. keywords: [],
  1132. startLine: i,
  1133. precedingComments: pendingComments.length > 0 ? [...pendingComments] : []
  1134. };
  1135. pendingComments = [];
  1136. }
  1137. currentGroup.keywords.push(trimmed);
  1138. lastLineWasAlias = false;
  1139. }
  1140. }
  1141. }
  1142. }
  1143. // 添加最后一个组
  1144. if (currentGroup) {
  1145. relatedGroupsBuffer.push(currentGroup);
  1146. }
  1147. flushRelatedGroups();
  1148. return result;
  1149. }
  1150. function buildFrequencyText(data) {
  1151. // 如果有原始文本,尝试保留注释
  1152. if (data.originalText) {
  1153. const lines = data.originalText.split('\n');
  1154. let result = [];
  1155. // 第一步:保留文件头部的注释
  1156. let i = 0;
  1157. while (i < lines.length) {
  1158. const line = lines[i];
  1159. const trimmed = line.trim();
  1160. if (trimmed === '[GLOBAL_FILTER]') {
  1161. break;
  1162. }
  1163. result.push(line);
  1164. i++;
  1165. }
  1166. // 第二步:重建 [GLOBAL_FILTER] 区域
  1167. result.push('[GLOBAL_FILTER]');
  1168. // 保留 [GLOBAL_FILTER] 后面的注释(直到第一个非注释非空行)
  1169. i++;
  1170. while (i < lines.length) {
  1171. const line = lines[i];
  1172. const trimmed = line.trim();
  1173. if (trimmed.startsWith('#') || trimmed === '') {
  1174. result.push(line);
  1175. i++;
  1176. } else {
  1177. break;
  1178. }
  1179. }
  1180. // 添加全局过滤词
  1181. data.globalFilter.forEach(filter => {
  1182. result.push(filter);
  1183. });
  1184. // 跳过原始文件中的 [GLOBAL_FILTER] 内容(非注释行),保留空行和注释直到 [WORD_GROUPS]
  1185. while (i < lines.length) {
  1186. const line = lines[i];
  1187. const trimmed = line.trim();
  1188. if (trimmed === '[WORD_GROUPS]') {
  1189. break;
  1190. }
  1191. // 保留注释和空行
  1192. if (trimmed.startsWith('#') || trimmed === '') {
  1193. result.push(line);
  1194. }
  1195. i++;
  1196. }
  1197. // 第三步:重建 [WORD_GROUPS] 区域
  1198. result.push('[WORD_GROUPS]');
  1199. // 添加词组(注释已保存在每个词组的 precedingComments 中)
  1200. data.wordGroups.forEach((group, index) => {
  1201. // 先输出词组前的注释
  1202. if (group.precedingComments && group.precedingComments.length > 0) {
  1203. group.precedingComments.forEach(comment => {
  1204. result.push(comment);
  1205. });
  1206. }
  1207. if (group.type === 'group-name') {
  1208. // 组别名类型:[组名] + 关键词
  1209. if (group.name) {
  1210. result.push(`[${group.name}]`);
  1211. }
  1212. group.keywords.forEach(kw => {
  1213. result.push(kw);
  1214. });
  1215. } else if (group.type === 'alias' || group.type === 'alias-group') {
  1216. // 别名类型:keyword => alias
  1217. group.items.forEach(item => {
  1218. result.push(`${item.keyword} => ${item.alias}`);
  1219. });
  1220. } else if (group.type === 'plain') {
  1221. // 普通词组
  1222. group.keywords.forEach(kw => {
  1223. result.push(kw);
  1224. });
  1225. }
  1226. // 空行处理逻辑:
  1227. // 1. 如果当前词组和下一个词组都是相关组,则不添加空行
  1228. // 2. 否则,在词组之间添加空行
  1229. const isLastGroup = index === data.wordGroups.length - 1;
  1230. const nextGroup = !isLastGroup ? data.wordGroups[index + 1] : null;
  1231. // 简化判断:只要当前和下一个都是相关组,就不添加空行
  1232. const bothAreRelatedGroups = group.isRelatedGroup && nextGroup && nextGroup.isRelatedGroup;
  1233. // 如果下一个词组有前置注释,不需要额外添加空行(注释中已包含空行)
  1234. const nextHasComments = nextGroup && nextGroup.precedingComments && nextGroup.precedingComments.length > 0;
  1235. if (bothAreRelatedGroups) {
  1236. // 相关组内部不添加空行
  1237. // 不添加任何内容
  1238. } else if (!isLastGroup && !nextHasComments) {
  1239. // 词组之间添加空行(如果下一个没有前置注释)
  1240. result.push('');
  1241. } else if (isLastGroup) {
  1242. // 最后一个词组后也保留一个空行
  1243. result.push('');
  1244. }
  1245. });
  1246. return result.join('\n');
  1247. }
  1248. // 如果没有原始文本,使用默认模板
  1249. let text = '# ═══════════════════════════════════════════════════════════════\n';
  1250. text += '# TrendRadar 频率词配置文件\n';
  1251. text += '# ═══════════════════════════════════════════════════════════════\n\n';
  1252. text += '[GLOBAL_FILTER]\n';
  1253. data.globalFilter.forEach(filter => {
  1254. text += filter + '\n';
  1255. });
  1256. text += '\n\n';
  1257. text += '[WORD_GROUPS]\n\n';
  1258. data.wordGroups.forEach((group, index) => {
  1259. // 先输出词组前的注释
  1260. if (group.precedingComments && group.precedingComments.length > 0) {
  1261. group.precedingComments.forEach(comment => {
  1262. text += comment + '\n';
  1263. });
  1264. }
  1265. if (group.type === 'group-name') {
  1266. if (group.name) {
  1267. text += `[${group.name}]\n`;
  1268. }
  1269. group.keywords.forEach(kw => {
  1270. text += kw + '\n';
  1271. });
  1272. } else if (group.type === 'alias' || group.type === 'alias-group') {
  1273. group.items.forEach(item => {
  1274. text += `${item.keyword} => ${item.alias}\n`;
  1275. });
  1276. } else if (group.type === 'plain') {
  1277. group.keywords.forEach(kw => {
  1278. text += kw + '\n';
  1279. });
  1280. }
  1281. // 空行处理逻辑:与上面保持一致
  1282. const isLastGroup = index === data.wordGroups.length - 1;
  1283. const nextGroup = !isLastGroup ? data.wordGroups[index + 1] : null;
  1284. const bothAreRelatedGroups = group.isRelatedGroup && nextGroup && nextGroup.isRelatedGroup;
  1285. // 如果下一个词组有前置注释,不需要额外添加空行
  1286. const nextHasComments = nextGroup && nextGroup.precedingComments && nextGroup.precedingComments.length > 0;
  1287. if (bothAreRelatedGroups) {
  1288. // 相关组内部不添加空行
  1289. } else if (!isLastGroup && !nextHasComments) {
  1290. text += '\n'; // 词组之间用空行分隔
  1291. } else if (isLastGroup) {
  1292. text += '\n'; // 最后一个词组后也保留一个空行
  1293. }
  1294. });
  1295. return text;
  1296. }
  1297. function syncFrequencyToUI() {
  1298. const data = parseFrequencyText(currentFrequency);
  1299. currentFrequencyData = data;
  1300. renderFrequencyPanel(data);
  1301. }
  1302. function renderFrequencyPanel(data) {
  1303. if (!data) {
  1304. data = parseFrequencyText(currentFrequency);
  1305. }
  1306. const panel = document.getElementById('frequency-panel');
  1307. // 辅助函数:根据关键词类型返回样式类
  1308. function getKeywordClass(keyword) {
  1309. if (keyword.startsWith('+')) return 'bg-green-500';
  1310. if (keyword.startsWith('!')) return 'bg-red-500';
  1311. if (keyword.startsWith('@')) return 'bg-purple-500';
  1312. if (keyword.startsWith('/') || keyword.includes('=>')) return 'bg-indigo-500';
  1313. return 'bg-blue-500';
  1314. }
  1315. // 辅助函数:为关键词添加标签
  1316. function getKeywordLabel(keyword) {
  1317. if (keyword.startsWith('+')) return '必须';
  1318. if (keyword.startsWith('!')) return '排除';
  1319. if (keyword.startsWith('@')) return '限制';
  1320. if (keyword.startsWith('/')) return '正则';
  1321. if (keyword.includes('=>')) return '别名';
  1322. return '';
  1323. }
  1324. // 渲染词组卡片
  1325. function renderGroupCard(group, idx) {
  1326. const jumpIcon = `<i class="fa-solid fa-grip-vertical text-gray-400 text-xs mr-2" title="拖动调整顺序"></i>`;
  1327. // 序号标记
  1328. const indexBadge = `<span class="text-xs bg-gray-700 text-white px-2.5 py-1 rounded-full font-bold mr-2" title="词组序号">#${idx + 1}</span>`;
  1329. // 相关组标记
  1330. const relatedGroupBadge = group.isRelatedGroup
  1331. ? `<span class="text-[10px] bg-gradient-to-r from-blue-500 to-indigo-500 text-white px-2 py-0.5 rounded font-bold ml-2" title="此组与相邻组相关(无空行分隔)">
  1332. <i class="fa-solid fa-link mr-1"></i>相关组 ${group.relatedGroupIndex + 1}/${group.relatedGroupTotal}
  1333. </span>`
  1334. : '';
  1335. // 相关组边框样式
  1336. const relatedGroupStyle = group.isRelatedGroup
  1337. ? 'border-l-4 border-l-blue-500 shadow-lg'
  1338. : '';
  1339. if (group.type === 'group-name') {
  1340. // 组别名类型
  1341. return `
  1342. <div class="word-group-card border-2 border-orange-200 bg-orange-50 group ${relatedGroupStyle} cursor-move" data-group-index="${idx}" onclick="scrollToWordGroupInEditor(${idx})">
  1343. <div class="flex items-center justify-between mb-3">
  1344. <div class="flex items-center flex-1 gap-2">
  1345. ${jumpIcon}
  1346. ${indexBadge}
  1347. <span class="text-[10px] bg-orange-500 text-white px-2 py-0.5 rounded font-bold">组别名</span>
  1348. ${relatedGroupBadge}
  1349. <input type="text" value="${group.name || ''}" placeholder="组别名(如:东亚)"
  1350. class="text-sm font-bold border-0 border-b-2 border-orange-300 focus:border-orange-500 outline-none px-2 py-1 flex-1 bg-transparent"
  1351. onclick="event.stopPropagation()"
  1352. onchange="updateGroupName(${idx}, this.value)">
  1353. </div>
  1354. <button onclick="event.stopPropagation(); removeWordGroup(${idx})" class="text-red-500 hover:text-red-700 text-xs ml-2">
  1355. <i class="fa-solid fa-trash"></i>
  1356. </button>
  1357. </div>
  1358. <div class="bg-white rounded p-3 border border-orange-200 editable-area" onclick="event.stopPropagation()">
  1359. <div class="text-xs text-gray-600 mb-2 font-bold">关键词列表:</div>
  1360. <div class="tag-input-container">
  1361. ${group.keywords.map(kw => {
  1362. const label = getKeywordLabel(kw);
  1363. const escapedKw = kw.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  1364. return `
  1365. <span class="tag-item ${getKeywordClass(kw)} relative break-all cursor-pointer" data-keyword="${escapedKw}" onclick="editKeyword(${idx}, this.dataset.keyword, this)">
  1366. ${label ? `<span class="text-[9px] opacity-75 mr-1">[${label}]</span>` : ''}
  1367. ${escapedKw}
  1368. <button data-keyword="${escapedKw}" onclick="event.stopPropagation(); removeKeyword(${idx}, this.dataset.keyword)">×</button>
  1369. </span>
  1370. `;
  1371. }).join('')}
  1372. <input type="text" class="tag-input" placeholder="输入关键词后按回车..."
  1373. onkeydown="handleKeywordInput(event, ${idx})">
  1374. </div>
  1375. <div class="flex items-center justify-between mt-2">
  1376. <button onclick="openDeepSeekAI('group', ${idx})" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1377. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1378. </button>
  1379. <div class="text-[10px] text-gray-400">${group.keywords.length} 个关键词</div>
  1380. </div>
  1381. </div>
  1382. </div>
  1383. `;
  1384. } else if (group.type === 'alias') {
  1385. // 单个别名类型
  1386. const item = group.items[0];
  1387. return `
  1388. <div class="word-group-card border-2 border-teal-200 bg-teal-50 group ${relatedGroupStyle} cursor-move" data-group-index="${idx}" onclick="scrollToWordGroupInEditor(${idx})">
  1389. <div class="flex items-center justify-between mb-3">
  1390. <div class="flex items-center flex-1 gap-2">
  1391. ${jumpIcon}
  1392. ${indexBadge}
  1393. <span class="text-[10px] bg-teal-500 text-white px-2 py-0.5 rounded font-bold">单个别名</span>
  1394. ${relatedGroupBadge}
  1395. </div>
  1396. <button onclick="event.stopPropagation(); removeWordGroup(${idx})" class="text-red-500 hover:text-red-700 text-xs">
  1397. <i class="fa-solid fa-trash"></i>
  1398. </button>
  1399. </div>
  1400. <div class="bg-white rounded p-3 border border-teal-200 editable-area" onclick="event.stopPropagation()">
  1401. <div class="flex items-center gap-2">
  1402. <input type="text" value="${item.keyword || ''}" placeholder="/正则/ 或 关键词"
  1403. class="flex-1 px-3 py-2 border border-gray-300 rounded focus:border-teal-500 outline-none text-sm font-mono"
  1404. onblur="updateAliasItem(${idx}, 0, 'keyword', this.value)">
  1405. <span class="text-teal-600 font-bold">=></span>
  1406. <input type="text" value="${item.alias || ''}" placeholder="别名"
  1407. class="flex-1 px-3 py-2 border border-gray-300 rounded focus:border-teal-500 outline-none text-sm"
  1408. onblur="updateAliasItem(${idx}, 0, 'alias', this.value)">
  1409. </div>
  1410. <div class="flex items-center justify-between mt-2">
  1411. <button onclick="openDeepSeekAI('group', ${idx})" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1412. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1413. </button>
  1414. <div class="text-[10px] text-gray-500">
  1415. <i class="fa-solid fa-lightbulb mr-1"></i>示例:/胖东来|于东来/ => 胖东来
  1416. </div>
  1417. </div>
  1418. </div>
  1419. </div>
  1420. `;
  1421. } else if (group.type === 'alias-group') {
  1422. // 连续别名组类型
  1423. return `
  1424. <div class="word-group-card border-2 border-purple-200 bg-purple-50 group ${relatedGroupStyle} cursor-move" data-group-index="${idx}" onclick="scrollToWordGroupInEditor(${idx})">
  1425. <div class="flex items-center justify-between mb-3">
  1426. <div class="flex items-center flex-1 gap-2">
  1427. ${jumpIcon}
  1428. ${indexBadge}
  1429. <span class="text-[10px] bg-purple-500 text-white px-2 py-0.5 rounded font-bold">连续别名组</span>
  1430. ${relatedGroupBadge}
  1431. </div>
  1432. <button onclick="event.stopPropagation(); removeWordGroup(${idx})" class="text-red-500 hover:text-red-700 text-xs">
  1433. <i class="fa-solid fa-trash"></i>
  1434. </button>
  1435. </div>
  1436. <div class="bg-white rounded p-3 border border-purple-200 space-y-2 editable-area" onclick="event.stopPropagation()">
  1437. <div class="text-xs text-gray-600 mb-2 font-bold">
  1438. 别名列表(无空行分隔):
  1439. </div>
  1440. ${group.items.map((item, itemIdx) => `
  1441. <div class="flex items-center gap-2">
  1442. <input type="text" value="${item.keyword || ''}" placeholder="/正则/ 或 关键词"
  1443. class="flex-1 px-3 py-2 border border-gray-300 rounded focus:border-purple-500 outline-none text-sm font-mono"
  1444. onblur="updateAliasItem(${idx}, ${itemIdx}, 'keyword', this.value)">
  1445. <span class="text-purple-600 font-bold">=></span>
  1446. <input type="text" value="${item.alias || ''}" placeholder="别名"
  1447. class="flex-1 px-3 py-2 border border-gray-300 rounded focus:border-purple-500 outline-none text-sm"
  1448. onblur="updateAliasItem(${idx}, ${itemIdx}, 'alias', this.value)">
  1449. <button onclick="removeAliasItem(${idx}, ${itemIdx})" class="text-red-500 hover:text-red-700 text-xs">
  1450. <i class="fa-solid fa-trash"></i>
  1451. </button>
  1452. </div>
  1453. `).join('')}
  1454. <div class="flex items-center justify-between mt-2">
  1455. <button onclick="openDeepSeekAI('group', ${idx})" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1456. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1457. </button>
  1458. <div class="text-[10px] text-gray-500">
  1459. <i class="fa-solid fa-info-circle mr-1"></i>这些别名行在配置文件中无空行分隔,属于同一组
  1460. </div>
  1461. </div>
  1462. </div>
  1463. </div>
  1464. `;
  1465. } else if (group.type === 'plain') {
  1466. // 普通词组类型
  1467. return `
  1468. <div class="word-group-card border-2 border-gray-200 bg-gray-50 group ${relatedGroupStyle} cursor-move" data-group-index="${idx}" onclick="scrollToWordGroupInEditor(${idx})">
  1469. <div class="flex items-center justify-between mb-3">
  1470. <div class="flex items-center flex-1 gap-2">
  1471. ${jumpIcon}
  1472. ${indexBadge}
  1473. <span class="text-[10px] bg-gray-500 text-white px-2 py-0.5 rounded font-bold">普通词组</span>
  1474. ${relatedGroupBadge}
  1475. </div>
  1476. <button onclick="event.stopPropagation(); removeWordGroup(${idx})" class="text-red-500 hover:text-red-700 text-xs">
  1477. <i class="fa-solid fa-trash"></i>
  1478. </button>
  1479. </div>
  1480. <div class="bg-white rounded p-3 border border-gray-200 editable-area" onclick="event.stopPropagation()">
  1481. <div class="tag-input-container">
  1482. ${group.keywords.map(kw => {
  1483. const label = getKeywordLabel(kw);
  1484. const escapedKw = kw.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
  1485. return `
  1486. <span class="tag-item ${getKeywordClass(kw)} relative break-all cursor-pointer" data-keyword="${escapedKw}" onclick="editKeyword(${idx}, this.dataset.keyword, this)">
  1487. ${label ? `<span class="text-[9px] opacity-75 mr-1">[${label}]</span>` : ''}
  1488. ${escapedKw}
  1489. <button data-keyword="${escapedKw}" onclick="event.stopPropagation(); removeKeyword(${idx}, this.dataset.keyword)">×</button>
  1490. </span>
  1491. `;
  1492. }).join('')}
  1493. <input type="text" class="tag-input" placeholder="输入关键词后按回车..."
  1494. onkeydown="handleKeywordInput(event, ${idx})">
  1495. </div>
  1496. <div class="flex items-center justify-between mt-2">
  1497. <button onclick="openDeepSeekAI('group', ${idx})" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1498. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1499. </button>
  1500. <div class="text-[10px] text-gray-400">${group.keywords.length} 个关键词</div>
  1501. </div>
  1502. </div>
  1503. </div>
  1504. `;
  1505. }
  1506. return '';
  1507. }
  1508. panel.innerHTML = `
  1509. <!-- 规则说明区域 -->
  1510. <div class="bg-gradient-to-r from-blue-50 to-indigo-50 rounded-lg border border-blue-200 p-4 mb-4">
  1511. <div class="flex items-start gap-3">
  1512. <i class="fa-solid fa-book text-blue-600 text-lg mt-0.5"></i>
  1513. <div class="flex-1">
  1514. <h3 class="text-sm font-bold text-gray-800 mb-2">四种词组类型说明</h3>
  1515. <div class="grid grid-cols-2 gap-3 text-xs">
  1516. <div class="bg-white rounded p-2 border-l-4 border-orange-500">
  1517. <div class="font-bold text-orange-700 mb-1">组别名</div>
  1518. <div class="text-gray-600 font-mono text-[10px] mb-1">[东亚]<br>日本<br>韩国</div>
  1519. <div class="text-gray-500 text-[10px]">多个关键词,统一显示为组名</div>
  1520. </div>
  1521. <div class="bg-white rounded p-2 border-l-4 border-teal-500">
  1522. <div class="font-bold text-teal-700 mb-1">单个别名</div>
  1523. <div class="text-gray-600 font-mono text-[10px] mb-1">/胖东来|于东来/ => 胖东来</div>
  1524. <div class="text-gray-500 text-[10px]">正则匹配,显示为别名</div>
  1525. </div>
  1526. <div class="bg-white rounded p-2 border-l-4 border-purple-500">
  1527. <div class="font-bold text-purple-700 mb-1">连续别名组</div>
  1528. <div class="text-gray-600 font-mono text-[10px] mb-1">/智元|稚晖君/ => 智元<br>/众擎|EngineAI/ => 众擎</div>
  1529. <div class="text-gray-500 text-[10px]">多个别名无空行分隔</div>
  1530. </div>
  1531. <div class="bg-white rounded p-2 border-l-4 border-gray-500">
  1532. <div class="font-bold text-gray-700 mb-1">普通词组</div>
  1533. <div class="text-gray-600 font-mono text-[10px] mb-1">申奥</div>
  1534. <div class="text-gray-500 text-[10px]">普通关键词</div>
  1535. </div>
  1536. </div>
  1537. </div>
  1538. </div>
  1539. </div>
  1540. <!-- Global Filter 区域 -->
  1541. <div class="bg-white rounded-lg border border-gray-200 p-5">
  1542. <div class="flex items-center justify-between mb-3">
  1543. <h3 class="text-sm font-bold text-gray-700">
  1544. <i class="fa-solid fa-filter mr-2"></i>全局过滤词
  1545. </h3>
  1546. <button onclick="openDeepSeekAI('global')" class="text-xs text-blue-600 hover:text-blue-700 flex items-center gap-1">
  1547. <i class="fa-solid fa-wand-magic-sparkles"></i>AI 写正则
  1548. </button>
  1549. </div>
  1550. <div id="global-filter-tags" class="tag-input-container">
  1551. ${data.globalFilter.map(f => `
  1552. <span class="tag-item ${getKeywordClass(f)}">
  1553. ${f}
  1554. <button onclick="removeGlobalFilter('${f.replace(/'/g, "\\'")}')">×</button>
  1555. </span>
  1556. `).join('')}
  1557. <input type="text" class="tag-input" placeholder="输入过滤词后按回车..." onkeydown="handleGlobalFilterInput(event)">
  1558. </div>
  1559. <div class="text-xs text-gray-500 mt-2">
  1560. <i class="fa-solid fa-lightbulb mr-1"></i>提示:支持正则表达式(用 /.../ 包裹)
  1561. </div>
  1562. </div>
  1563. <!-- Word Groups 区域 -->
  1564. <div class="bg-white rounded-lg border border-gray-200 p-5">
  1565. <div class="flex items-center justify-between mb-3">
  1566. <h3 class="text-sm font-bold text-gray-700">
  1567. <i class="fa-solid fa-layer-group mr-2"></i>关键词组 <span class="text-xs text-gray-400 font-normal">(${data.wordGroups.length} 个词组)</span>
  1568. </h3>
  1569. <button onclick="addWordGroup('top')" class="text-xs bg-blue-600 text-white px-3 py-1 rounded hover:bg-blue-700">
  1570. <i class="fa-solid fa-plus mr-1"></i>添加词组
  1571. </button>
  1572. </div>
  1573. <div id="word-groups-container" class="space-y-3">
  1574. ${data.wordGroups.map((group, idx) => {
  1575. const card = renderGroupCard(group, idx);
  1576. // 在每个词组后添加插入区域(最后一个除外)
  1577. if (idx < data.wordGroups.length - 1) {
  1578. return card + `
  1579. <div class="insert-zone group/insert" data-insert-index="${idx + 1}">
  1580. <button onclick="insertWordGroupAt(${idx + 1})" class="insert-button">
  1581. <i class="fa-solid fa-plus"></i>
  1582. </button>
  1583. </div>
  1584. `;
  1585. }
  1586. return card;
  1587. }).join('')}
  1588. </div>
  1589. <!-- 底部添加按钮 -->
  1590. <div class="mt-4 flex justify-center">
  1591. <button onclick="addWordGroup('bottom')" class="text-sm bg-gradient-to-r from-blue-500 to-blue-600 text-white px-6 py-2 rounded-lg hover:from-blue-600 hover:to-blue-700 shadow-sm transition-all flex items-center gap-2">
  1592. <i class="fa-solid fa-plus-circle"></i>
  1593. <span>在底部添加词组</span>
  1594. </button>
  1595. </div>
  1596. </div>
  1597. `;
  1598. // 初始化拖拽排序功能
  1599. setTimeout(() => {
  1600. const container = document.getElementById('word-groups-container');
  1601. if (container && typeof Sortable !== 'undefined') {
  1602. // 销毁之前的实例(如果存在)
  1603. if (container.sortableInstance) {
  1604. container.sortableInstance.destroy();
  1605. }
  1606. // 创建新的 Sortable 实例
  1607. container.sortableInstance = new Sortable(container, {
  1608. animation: 150,
  1609. filter: '.editable-area, input, button, select, textarea', // 排除编辑区域
  1610. preventOnFilter: false, // 允许在过滤区域正常交互
  1611. ghostClass: 'sortable-ghost',
  1612. chosenClass: 'sortable-chosen',
  1613. dragClass: 'sortable-drag',
  1614. onEnd: function(evt) {
  1615. // 获取所有词组卡片的当前顺序
  1616. const cards = Array.from(container.querySelectorAll('.word-group-card'));
  1617. const newOrder = cards.map(card => parseInt(card.getAttribute('data-group-index')));
  1618. // 检查顺序是否改变
  1619. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1620. const oldOrder = data.wordGroups.map((_, idx) => idx);
  1621. if (JSON.stringify(newOrder) !== JSON.stringify(oldOrder)) {
  1622. // 根据新顺序重新排列数据
  1623. const reorderedGroups = newOrder.map(idx => data.wordGroups[idx]);
  1624. data.wordGroups = reorderedGroups;
  1625. // 重新构建文本
  1626. currentFrequency = buildFrequencyText(data);
  1627. currentFrequencyData = parseFrequencyText(currentFrequency);
  1628. document.getElementById('frequency-editor').value = currentFrequency;
  1629. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1630. // 重新渲染
  1631. renderFrequencyPanel(currentFrequencyData);
  1632. }
  1633. }
  1634. });
  1635. }
  1636. }, 0);
  1637. }
  1638. // Global Filter 操作
  1639. window.handleGlobalFilterInput = function(event) {
  1640. if (event.key === 'Enter' && event.target.value.trim()) {
  1641. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1642. data.globalFilter.push(event.target.value.trim());
  1643. currentFrequency = buildFrequencyText(data);
  1644. currentFrequencyData = data;
  1645. document.getElementById('frequency-editor').value = currentFrequency;
  1646. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1647. renderFrequencyPanel(data);
  1648. }
  1649. }
  1650. window.removeGlobalFilter = function(filter) {
  1651. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1652. data.globalFilter = data.globalFilter.filter(f => f !== filter);
  1653. currentFrequency = buildFrequencyText(data);
  1654. currentFrequencyData = data;
  1655. document.getElementById('frequency-editor').value = currentFrequency;
  1656. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1657. renderFrequencyPanel(data);
  1658. }
  1659. // Word Groups 操作
  1660. let pendingWordGroupPosition = 'top'; // 记录添加位置:'top', 'bottom', 或数字索引
  1661. window.addWordGroup = function(position = 'top') {
  1662. pendingWordGroupPosition = position;
  1663. document.getElementById('wordgroup-type-modal').classList.remove('hidden');
  1664. }
  1665. // 在指定位置插入词组
  1666. window.insertWordGroupAt = function(index) {
  1667. pendingWordGroupPosition = index; // 记录插入位置(数字索引)
  1668. document.getElementById('wordgroup-type-modal').classList.remove('hidden');
  1669. }
  1670. window.closeWordGroupTypeModal = function() {
  1671. document.getElementById('wordgroup-type-modal').classList.add('hidden');
  1672. }
  1673. window.confirmAddWordGroup = function(type) {
  1674. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1675. let newGroup;
  1676. if (type === 'group') {
  1677. // 组别名类型
  1678. newGroup = { type: 'group-name', name: '', keywords: [] };
  1679. } else if (type === 'alias') {
  1680. // 单个别名类型
  1681. newGroup = { type: 'alias', items: [{ keyword: '', alias: '' }] };
  1682. } else if (type === 'multi-alias') {
  1683. // 连续别名类型(多个别名行)
  1684. newGroup = { type: 'alias-group', items: [{ keyword: '', alias: '' }, { keyword: '', alias: '' }] };
  1685. } else if (type === 'plain') {
  1686. // 普通词组类型
  1687. newGroup = { type: 'plain', keywords: [] };
  1688. }
  1689. // 根据位置插入
  1690. if (pendingWordGroupPosition === 'bottom') {
  1691. data.wordGroups.push(newGroup);
  1692. } else if (pendingWordGroupPosition === 'top') {
  1693. data.wordGroups.unshift(newGroup);
  1694. } else if (typeof pendingWordGroupPosition === 'number') {
  1695. // 在指定索引位置插入
  1696. data.wordGroups.splice(pendingWordGroupPosition, 0, newGroup);
  1697. }
  1698. currentFrequency = buildFrequencyText(data);
  1699. currentFrequencyData = data;
  1700. document.getElementById('frequency-editor').value = currentFrequency;
  1701. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1702. renderFrequencyPanel(data);
  1703. closeWordGroupTypeModal();
  1704. // 滚动到新添加的词组
  1705. setTimeout(() => {
  1706. const container = document.getElementById('word-groups-container');
  1707. if (pendingWordGroupPosition === 'bottom') {
  1708. container.scrollTop = container.scrollHeight;
  1709. } else if (pendingWordGroupPosition === 'top') {
  1710. container.scrollTop = 0;
  1711. } else if (typeof pendingWordGroupPosition === 'number') {
  1712. // 滚动到插入的位置
  1713. const cards = container.querySelectorAll('.word-group-card');
  1714. if (cards[pendingWordGroupPosition]) {
  1715. cards[pendingWordGroupPosition].scrollIntoView({ behavior: 'smooth', block: 'center' });
  1716. }
  1717. }
  1718. }, 100);
  1719. }
  1720. window.removeWordGroup = function(index) {
  1721. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1722. data.wordGroups.splice(index, 1);
  1723. currentFrequency = buildFrequencyText(data);
  1724. // 重新解析以更新相关组信息
  1725. currentFrequencyData = parseFrequencyText(currentFrequency);
  1726. document.getElementById('frequency-editor').value = currentFrequency;
  1727. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1728. renderFrequencyPanel(currentFrequencyData);
  1729. }
  1730. window.updateGroupName = function(index, name) {
  1731. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1732. const group = data.wordGroups[index];
  1733. // 只有 group-name 类型才有 name 字段
  1734. if (group.type === 'group-name') {
  1735. group.name = name;
  1736. }
  1737. currentFrequency = buildFrequencyText(data);
  1738. // 重新解析以更新相关组信息
  1739. currentFrequencyData = parseFrequencyText(currentFrequency);
  1740. document.getElementById('frequency-editor').value = currentFrequency;
  1741. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1742. renderFrequencyPanel(currentFrequencyData);
  1743. }
  1744. window.editKeyword = function(groupIndex, oldKeyword, spanElement) {
  1745. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1746. const group = data.wordGroups[groupIndex];
  1747. // 只有 group-name 和 plain 类型才有 keywords 字段
  1748. if (group.type !== 'group-name' && group.type !== 'plain') {
  1749. return;
  1750. }
  1751. const originalKeyword = group.keywords.find(kw => kw === oldKeyword) || oldKeyword;
  1752. const input = document.createElement('input');
  1753. input.type = 'text';
  1754. input.value = originalKeyword;
  1755. input.className = 'tag-input inline-block px-2 py-1 text-xs border border-blue-500 rounded';
  1756. input.style.minWidth = '100px';
  1757. const saveEdit = () => {
  1758. const newKeyword = input.value.trim();
  1759. if (newKeyword && newKeyword !== originalKeyword) {
  1760. const kwIndex = group.keywords.indexOf(originalKeyword);
  1761. if (kwIndex !== -1) {
  1762. group.keywords[kwIndex] = newKeyword;
  1763. }
  1764. currentFrequency = buildFrequencyText(data);
  1765. // 重新解析以更新相关组信息
  1766. currentFrequencyData = parseFrequencyText(currentFrequency);
  1767. document.getElementById('frequency-editor').value = currentFrequency;
  1768. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1769. renderFrequencyPanel(currentFrequencyData);
  1770. } else {
  1771. spanElement.style.display = '';
  1772. input.remove();
  1773. }
  1774. };
  1775. input.onblur = saveEdit;
  1776. input.onkeydown = (e) => {
  1777. if (e.key === 'Enter') {
  1778. saveEdit();
  1779. } else if (e.key === 'Escape') {
  1780. spanElement.style.display = '';
  1781. input.remove();
  1782. }
  1783. };
  1784. spanElement.style.display = 'none';
  1785. spanElement.parentNode.insertBefore(input, spanElement);
  1786. input.focus();
  1787. input.select();
  1788. }
  1789. window.handleKeywordInput = function(event, groupIndex) {
  1790. if (event.key === 'Enter' && event.target.value.trim()) {
  1791. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1792. const group = data.wordGroups[groupIndex];
  1793. // 只有 group-name 和 plain 类型才能添加关键词
  1794. if (group.type === 'group-name' || group.type === 'plain') {
  1795. group.keywords.push(event.target.value.trim());
  1796. event.target.value = '';
  1797. currentFrequency = buildFrequencyText(data);
  1798. // 重新解析以更新相关组信息
  1799. currentFrequencyData = parseFrequencyText(currentFrequency);
  1800. document.getElementById('frequency-editor').value = currentFrequency;
  1801. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1802. renderFrequencyPanel(currentFrequencyData);
  1803. }
  1804. }
  1805. }
  1806. window.removeKeyword = function(groupIndex, keyword) {
  1807. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1808. const group = data.wordGroups[groupIndex];
  1809. // 只有 group-name 和 plain 类型才能删除关键词
  1810. if (group.type === 'group-name' || group.type === 'plain') {
  1811. group.keywords = group.keywords.filter(k => k !== keyword);
  1812. // 如果词组变空,删除整个词组
  1813. if (group.keywords.length === 0) {
  1814. data.wordGroups.splice(groupIndex, 1);
  1815. }
  1816. currentFrequency = buildFrequencyText(data);
  1817. // 重新解析以更新相关组信息
  1818. currentFrequencyData = parseFrequencyText(currentFrequency);
  1819. document.getElementById('frequency-editor').value = currentFrequency;
  1820. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1821. renderFrequencyPanel(currentFrequencyData);
  1822. }
  1823. }
  1824. // 更新别名项
  1825. window.updateAliasItem = function(groupIndex, itemIndex, field, value) {
  1826. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1827. const group = data.wordGroups[groupIndex];
  1828. // 只有 alias 和 alias-group 类型才有 items 字段
  1829. if (group.type === 'alias' || group.type === 'alias-group') {
  1830. if (group.items[itemIndex]) {
  1831. group.items[itemIndex][field] = value;
  1832. currentFrequency = buildFrequencyText(data);
  1833. currentFrequencyData = parseFrequencyText(currentFrequency);
  1834. document.getElementById('frequency-editor').value = currentFrequency;
  1835. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1836. renderFrequencyPanel(currentFrequencyData);
  1837. }
  1838. }
  1839. }
  1840. // 添加别名项
  1841. window.addAliasItem = function(groupIndex) {
  1842. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1843. const group = data.wordGroups[groupIndex];
  1844. // 只有 alias-group 类型才能添加别名项
  1845. if (group.type === 'alias-group') {
  1846. group.items.push({ keyword: '', alias: '' });
  1847. currentFrequency = buildFrequencyText(data);
  1848. // 重新解析以更新相关组信息
  1849. currentFrequencyData = parseFrequencyText(currentFrequency);
  1850. document.getElementById('frequency-editor').value = currentFrequency;
  1851. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1852. renderFrequencyPanel(currentFrequencyData);
  1853. } else if (group.type === 'alias') {
  1854. // 如果是单个别名,升级为别名组
  1855. group.type = 'alias-group';
  1856. group.items.push({ keyword: '', alias: '' });
  1857. currentFrequency = buildFrequencyText(data);
  1858. // 重新解析以更新相关组信息
  1859. currentFrequencyData = parseFrequencyText(currentFrequency);
  1860. document.getElementById('frequency-editor').value = currentFrequency;
  1861. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1862. renderFrequencyPanel(currentFrequencyData);
  1863. }
  1864. }
  1865. // 删除别名项
  1866. window.removeAliasItem = function(groupIndex, itemIndex) {
  1867. const data = currentFrequencyData || parseFrequencyText(currentFrequency);
  1868. const group = data.wordGroups[groupIndex];
  1869. // 只有 alias-group 类型才能删除别名项
  1870. if (group.type === 'alias-group') {
  1871. group.items.splice(itemIndex, 1);
  1872. // 如果没有别名项了,删除整个词组
  1873. if (group.items.length === 0) {
  1874. data.wordGroups.splice(groupIndex, 1);
  1875. }
  1876. // 如果只剩一个别名项,降级为单个别名
  1877. else if (group.items.length === 1) {
  1878. group.type = 'alias';
  1879. }
  1880. currentFrequency = buildFrequencyText(data);
  1881. currentFrequencyData = parseFrequencyText(currentFrequency);
  1882. document.getElementById('frequency-editor').value = currentFrequency;
  1883. updateBackdrop('frequency-editor', 'frequency-backdrop');
  1884. renderFrequencyPanel(currentFrequencyData);
  1885. }
  1886. }
  1887. // DeepSeek AI 辅助
  1888. window.openDeepSeekAI = function(type, groupIndex) {
  1889. const userInput = window.prompt('请输入核心关键词(例如:华为):');
  1890. if (!userInput) return;
  1891. const promptText = `我正在配置一个新闻聚合系统,需要通过 Python 正则表达式 抓取关于【${userInput}】的新闻。
  1892. 请帮我完成以下步骤,并最终只输出一个正则表达式字符串:
  1893. 第一步:【精准关键词筛选】
  1894. 请列出与【${userInput}】强绑定的核心词汇:
  1895. 1. 核心品牌:包括中文全称、简称、股票代码、别名。
  1896. 2. 核心人物:仅限最高决策层或极具代表性的创始人。
  1897. 3. 独家产品:必须是具有极高辨识度的独家产品名。
  1898. 4. 核心工作室/子品牌:强相关的下属机构。
  1899. 第二步:【严格清洗与过滤】(请严格执行)
  1900. 1. 包含关系去重(最短匹配原则):
  1901. - 中文:如果列表里已经有了核心短词(如“腾讯”),请删除所有包含该短词的长词(如“腾讯云”、“腾讯视频”统统不要,因为它们会被短词命中)。
  1902. - 英文:如果有了 \\bKeyword\\b,就不要再出现 Keyword。
  1903. 2. 彻底排除无关公司:
  1904. - 绝对不要包含:该品牌的竞争对手、合作伙伴(如京东、美团、字节跳动等非隶属公司)。
  1905. 3. 彻底排除通用黑话:
  1906. - 绝对不要包含:行业通用词(如“互联网”、“大厂”、“新质生产力”、“人工智能”、“元宇宙”、“金融科技”等)。
  1907. 第三步:【构建 Python 正则】
  1908. 将清洗后的词汇合并,格式要求如下:
  1909. 1. 英文处理:所有英文单词必须前后加 \\b(例如 \\bWord\\b),严禁出现没有边界符的英文单词。
  1910. 2. 连接符:用 | 连接。
  1911. 最终输出示例格式:
  1912. /词A|词B|\\bEnglishWord\\b/ => ${userInput}
  1913. 输出要求:
  1914. - 只要这一行正则表达式,不要任何解释,不要代码块。`;
  1915. const textArea = document.createElement("textarea");
  1916. textArea.value = promptText;
  1917. textArea.style.position = "fixed";
  1918. textArea.style.left = "-9999px";
  1919. textArea.style.top = "0";
  1920. document.body.appendChild(textArea);
  1921. textArea.focus();
  1922. textArea.select();
  1923. let copySuccess = false;
  1924. try {
  1925. copySuccess = document.execCommand('copy');
  1926. } catch (err) {
  1927. console.error('复制失败:', err);
  1928. }
  1929. document.body.removeChild(textArea);
  1930. if (copySuccess) {
  1931. if (confirm(`提示词已复制到剪贴板!\n\n关键词:${userInput}\n\n点击【确定】跳转 DeepSeek 官网,直接粘贴 (Ctrl+V) 即可。`)) {
  1932. window.open('https://chat.deepseek.com/', '_blank');
  1933. }
  1934. } else {
  1935. prompt('自动复制失败,请手动复制以下内容,然后自行打开 DeepSeek:', promptText);
  1936. window.open('https://chat.deepseek.com/', '_blank');
  1937. }
  1938. }
  1939. // ==========================================
  1940. // 10. 平台管理功能
  1941. // ==========================================
  1942. // 解析当前配置中的平台列表
  1943. function parsePlatformsFromYaml() {
  1944. try {
  1945. const doc = jsyaml.load(currentYaml);
  1946. if (doc && doc.platforms && doc.platforms.sources) {
  1947. return doc.platforms.sources;
  1948. }
  1949. } catch (e) {}
  1950. return [];
  1951. }
  1952. // 渲染平台列表
  1953. function renderPlatformsList() {
  1954. const container = document.getElementById('platforms-list');
  1955. if (!container) return;
  1956. const platforms = parsePlatformsFromYaml();
  1957. if (platforms.length === 0) {
  1958. container.innerHTML = `<div class="text-xs text-gray-400 italic">暂无平台,请添加</div>`;
  1959. return;
  1960. }
  1961. container.innerHTML = platforms.map((p, idx) => `
  1962. <div class="platform-item flex items-center justify-between bg-gray-50 rounded-lg px-3 py-2 border border-gray-200 hover:border-blue-300 transition-colors" data-index="${idx}">
  1963. <div class="flex items-center gap-2">
  1964. <i class="fa-solid fa-grip-vertical text-gray-300 cursor-move"></i>
  1965. <span class="text-xs font-medium text-gray-700">${p.name}</span>
  1966. <span class="text-[10px] text-gray-400">(${p.id})</span>
  1967. </div>
  1968. <button onclick="removePlatform(${idx})" class="text-red-400 hover:text-red-600 text-xs" title="删除">
  1969. <i class="fa-solid fa-trash"></i>
  1970. </button>
  1971. </div>
  1972. `).join('');
  1973. // 初始化拖拽排序
  1974. if (typeof Sortable !== 'undefined') {
  1975. new Sortable(container, {
  1976. animation: 150,
  1977. handle: '.fa-grip-vertical',
  1978. onEnd: function(evt) {
  1979. reorderPlatforms(evt.oldIndex, evt.newIndex);
  1980. }
  1981. });
  1982. }
  1983. }
  1984. // 删除平台
  1985. window.removePlatform = function(index) {
  1986. const platforms = parsePlatformsFromYaml();
  1987. if (index < 0 || index >= platforms.length) return;
  1988. const platformName = platforms[index].name;
  1989. if (!confirm(`确定要删除平台 "${platformName}" 吗?`)) return;
  1990. platforms.splice(index, 1);
  1991. updatePlatformsInYaml(platforms);
  1992. }
  1993. // 重新排序平台
  1994. function reorderPlatforms(oldIndex, newIndex) {
  1995. const platforms = parsePlatformsFromYaml();
  1996. const [removed] = platforms.splice(oldIndex, 1);
  1997. platforms.splice(newIndex, 0, removed);
  1998. updatePlatformsInYaml(platforms);
  1999. }
  2000. // 更新 YAML 中的平台配置(保留注释)
  2001. function updatePlatformsInYaml(platforms) {
  2002. const editor = document.getElementById('yaml-editor');
  2003. let yaml = editor.value;
  2004. const lines = yaml.split('\n');
  2005. // 找到 platforms.sources 的位置
  2006. let sourcesStart = -1;
  2007. let sourcesEnd = -1;
  2008. let inPlatforms = false;
  2009. let inSources = false;
  2010. let baseIndent = 0;
  2011. let lastDataLineIndex = -1; // 记录最后一个数据行的位置
  2012. for (let i = 0; i < lines.length; i++) {
  2013. const line = lines[i];
  2014. const trimmed = line.trim();
  2015. if (line.match(/^platforms:/)) {
  2016. inPlatforms = true;
  2017. continue;
  2018. }
  2019. if (inPlatforms && !inSources && trimmed.startsWith('sources:')) {
  2020. sourcesStart = i + 1;
  2021. inSources = true;
  2022. baseIndent = line.search(/\S/) + 2; // sources 下一级的缩进
  2023. continue;
  2024. }
  2025. if (inSources) {
  2026. const currentIndent = line.search(/\S/);
  2027. // 如果是数据行(以 - 开头或是数据项的属性)
  2028. if (trimmed.startsWith('-')) {
  2029. lastDataLineIndex = i;
  2030. } else if (trimmed && !trimmed.startsWith('#') && currentIndent >= baseIndent) {
  2031. // 数据项的属性行(如 name:, id:)
  2032. lastDataLineIndex = i;
  2033. } else if (trimmed && !trimmed.startsWith('#') && currentIndent < baseIndent) {
  2034. // 遇到缩进更小的非注释行,说明离开了 sources 区域
  2035. sourcesEnd = lastDataLineIndex + 1;
  2036. break;
  2037. }
  2038. }
  2039. // 检查是否进入下一个顶级模块
  2040. if (inPlatforms && line.match(/^[a-z_]+:/) && !line.match(/^platforms:/)) {
  2041. if (lastDataLineIndex >= 0) {
  2042. sourcesEnd = lastDataLineIndex + 1;
  2043. } else {
  2044. sourcesEnd = i;
  2045. }
  2046. break;
  2047. }
  2048. }
  2049. // 如果没有找到结束位置,使用最后一个数据行的下一行
  2050. if (sourcesEnd === -1) {
  2051. sourcesEnd = lastDataLineIndex >= 0 ? lastDataLineIndex + 1 : lines.length;
  2052. }
  2053. // 提取区域内的注释(保留在开头的注释)
  2054. const regionLines = lines.slice(sourcesStart, sourcesEnd);
  2055. const leadingComments = [];
  2056. for (const line of regionLines) {
  2057. const trimmed = line.trim();
  2058. if (trimmed.startsWith('#')) {
  2059. leadingComments.push(line);
  2060. } else if (trimmed.startsWith('-') || (trimmed && !trimmed.startsWith('#'))) {
  2061. // 遇到第一个数据项,停止收集注释
  2062. break;
  2063. } else if (trimmed === '') {
  2064. // 空行也保留
  2065. leadingComments.push(line);
  2066. }
  2067. }
  2068. const indent = ' '; // 4 空格缩进
  2069. const newSourcesLines = platforms.map(p =>
  2070. `${indent}- id: "${p.id}"\n${indent} name: "${p.name}"`
  2071. ).join('\n');
  2072. const beforeSources = lines.slice(0, sourcesStart);
  2073. const afterSources = lines.slice(sourcesEnd);
  2074. // 组合:前面内容 + 开头注释 + 新数据 + 后面内容
  2075. const newYaml = [
  2076. ...beforeSources,
  2077. ...(leadingComments.length > 0 ? leadingComments : []),
  2078. newSourcesLines,
  2079. ...afterSources
  2080. ].join('\n');
  2081. editor.value = newYaml;
  2082. currentYaml = newYaml;
  2083. updateBackdrop('yaml-editor', 'yaml-backdrop');
  2084. debounceSaveConfig();
  2085. renderPlatformsList();
  2086. renderStandaloneLists(); // 同步更新独立展示区的平台选择列表
  2087. }
  2088. // ==========================================
  2089. // 12. Display Regions 排序与管理功能
  2090. // ==========================================
  2091. const DISPLAY_REGIONS_DEF = [
  2092. { key: "hotlist", label: "热榜区域" },
  2093. { key: "new_items", label: "新增热点区域" },
  2094. { key: "rss", label: "RSS 订阅区域" },
  2095. { key: "standalone", label: "独立展示区" },
  2096. { key: "ai_analysis", label: "AI 分析区域" }
  2097. ];
  2098. // 从 YAML 解析 display.regions,严格按照 region_order 定义顺序
  2099. function parseDisplayRegionsFromYaml() {
  2100. try {
  2101. const doc = jsyaml.load(currentYaml);
  2102. if (doc && doc.display) {
  2103. const regionOrder = doc.display.region_order || [];
  2104. const regionStates = doc.display.regions || {};
  2105. // 严格按 region_order 顺序构建列表
  2106. if (regionOrder.length > 0) {
  2107. return regionOrder.map(key => {
  2108. const normalizedKey = key === 'new_item' ? 'new_items' : key;
  2109. const def = DISPLAY_REGIONS_DEF.find(d => d.key === normalizedKey);
  2110. return {
  2111. key: normalizedKey,
  2112. label: def ? def.label : normalizedKey,
  2113. enabled: regionStates[normalizedKey] !== undefined ? regionStates[normalizedKey] : false
  2114. };
  2115. });
  2116. }
  2117. // 后备方案:如果没有 region_order,使用 regions 对象的顺序
  2118. const regions = [];
  2119. for (const key in regionStates) {
  2120. const normalizedKey = key === 'new_item' ? 'new_items' : key;
  2121. const def = DISPLAY_REGIONS_DEF.find(d => d.key === normalizedKey);
  2122. if (def) {
  2123. regions.push({
  2124. key: normalizedKey,
  2125. label: def.label,
  2126. enabled: regionStates[key]
  2127. });
  2128. }
  2129. }
  2130. return regions;
  2131. }
  2132. } catch (e) {}
  2133. // 默认返回所有区域(禁用状态)
  2134. return DISPLAY_REGIONS_DEF.map(def => ({
  2135. key: def.key,
  2136. label: def.label,
  2137. enabled: false
  2138. }));
  2139. }
  2140. // 渲染 Display Regions 列表
  2141. function renderDisplayRegionsList() {
  2142. const container = document.getElementById('display-regions-list');
  2143. if (!container) return;
  2144. const regions = parseDisplayRegionsFromYaml();
  2145. container.innerHTML = regions.map((r, idx) => `
  2146. <div class="display-region-item flex items-center justify-between bg-gray-50 rounded-lg px-3 py-2 border border-gray-200 hover:border-blue-300 transition-colors" data-key="${r.key}">
  2147. <div class="flex items-center gap-2">
  2148. <i class="fa-solid fa-grip-vertical text-gray-300 cursor-move"></i>
  2149. <span class="text-xs font-medium ${r.enabled ? 'text-gray-700' : 'text-gray-400'}">${r.label}</span>
  2150. <span class="text-[10px] text-gray-400">(${r.key})</span>
  2151. </div>
  2152. <div class="relative inline-block w-10 align-middle select-none">
  2153. <input type="checkbox" id="toggle-region-${r.key}"
  2154. ${r.enabled ? 'checked' : ''}
  2155. onchange="toggleDisplayRegion('${r.key}')"
  2156. class="toggle-checkbox absolute block w-4 h-4 mt-0.5 ml-0.5 rounded-full bg-white border-4 appearance-none cursor-pointer transition-all duration-200 ease-in-out"/>
  2157. <label for="toggle-region-${r.key}" class="toggle-label block overflow-hidden h-5 rounded-full bg-gray-300 cursor-pointer"></label>
  2158. </div>
  2159. </div>
  2160. `).join('');
  2161. // 初始化拖拽排序
  2162. if (typeof Sortable !== 'undefined') {
  2163. new Sortable(container, {
  2164. animation: 150,
  2165. handle: '.fa-grip-vertical',
  2166. onEnd: function(evt) {
  2167. reorderDisplayRegions();
  2168. }
  2169. });
  2170. }
  2171. }
  2172. // 切换区域启用状态
  2173. window.toggleDisplayRegion = function(key) {
  2174. const regions = parseDisplayRegionsFromYaml();
  2175. const target = regions.find(r => r.key === key);
  2176. if (target) {
  2177. target.enabled = !target.enabled;
  2178. updateDisplayRegionsInYaml(regions);
  2179. }
  2180. }
  2181. // 重新排序区域
  2182. window.reorderDisplayRegions = function() {
  2183. const container = document.getElementById('display-regions-list');
  2184. const items = container.querySelectorAll('.display-region-item');
  2185. const newOrderKeys = Array.from(items).map(item => item.dataset.key);
  2186. const currentRegions = parseDisplayRegionsFromYaml();
  2187. const newRegions = newOrderKeys.map(key => {
  2188. return currentRegions.find(r => r.key === key);
  2189. }).filter(r => r); // 过滤掉可能的 undefined
  2190. updateDisplayRegionsInYaml(newRegions);
  2191. }
  2192. // 更新 YAML 中的 display.regions 和 display.region_order
  2193. function updateDisplayRegionsInYaml(regions) {
  2194. const editor = document.getElementById('yaml-editor');
  2195. let yaml = editor.value;
  2196. const lines = yaml.split('\n');
  2197. let regionOrderStart = -1;
  2198. let regionOrderEnd = -1;
  2199. let regionsStart = -1;
  2200. let regionsEnd = -1;
  2201. let inDisplay = false;
  2202. let regionOrderIndent = 0;
  2203. let regionsIndent = 0;
  2204. for (let i = 0; i < lines.length; i++) {
  2205. const line = lines[i];
  2206. const trimmed = line.trim();
  2207. if (line.match(/^display:/)) {
  2208. inDisplay = true;
  2209. continue;
  2210. }
  2211. if (!inDisplay) continue;
  2212. // 查找 region_order 数组
  2213. if (trimmed.startsWith('region_order:')) {
  2214. regionOrderStart = i + 1;
  2215. regionOrderIndent = line.search(/\S/) + 2;
  2216. // 找到 region_order 的结束位置
  2217. for (let j = i + 1; j < lines.length; j++) {
  2218. const nextLine = lines[j];
  2219. const nextTrimmed = nextLine.trim();
  2220. if (nextTrimmed && !nextTrimmed.startsWith('#') && !nextTrimmed.startsWith('-')) {
  2221. const nextIndent = nextLine.search(/\S/);
  2222. if (nextIndent < regionOrderIndent) {
  2223. regionOrderEnd = j;
  2224. break;
  2225. }
  2226. }
  2227. }
  2228. if (regionOrderEnd === -1) regionOrderEnd = lines.length;
  2229. continue;
  2230. }
  2231. // 查找 regions 对象
  2232. if (trimmed.startsWith('regions:')) {
  2233. regionsStart = i + 1;
  2234. regionsIndent = line.search(/\S/) + 2;
  2235. // 找到 regions 的结束位置(遇到同级或更高级的键)
  2236. for (let j = i + 1; j < lines.length; j++) {
  2237. const nextLine = lines[j];
  2238. const nextTrimmed = nextLine.trim();
  2239. if (nextTrimmed && !nextTrimmed.startsWith('#')) {
  2240. const nextIndent = nextLine.search(/\S/);
  2241. // 检查是否是同级或更高级的键(如 standalone:)
  2242. if (nextIndent <= line.search(/\S/)) {
  2243. regionsEnd = j;
  2244. break;
  2245. }
  2246. }
  2247. }
  2248. if (regionsEnd === -1) regionsEnd = lines.length;
  2249. break;
  2250. }
  2251. // 检查是否离开 display 模块
  2252. if (line.match(/^[a-z_]+:/) && !line.match(/^display:/)) {
  2253. break;
  2254. }
  2255. }
  2256. // 更新 region_order 数组(保留注释)
  2257. if (regionOrderStart > 0 && regionOrderEnd > regionOrderStart) {
  2258. const indentStr = ' '.repeat(regionOrderIndent);
  2259. // 提取原有行的注释映射
  2260. const originalRegionOrderBlock = lines.slice(regionOrderStart, regionOrderEnd);
  2261. const commentMap = {};
  2262. originalRegionOrderBlock.forEach(line => {
  2263. // 匹配 "- key # 注释" 格式
  2264. const match = line.match(/^\s*-\s*([a-z_]+)\s*(#.*)?$/);
  2265. if (match) {
  2266. const key = match[1];
  2267. const comment = match[2] || '';
  2268. if (key) commentMap[key] = comment;
  2269. }
  2270. });
  2271. // 生成新的行,保留注释
  2272. const newRegionOrderLines = regions.map(r => {
  2273. const comment = commentMap[r.key] || '';
  2274. return `${indentStr}- ${r.key}${comment ? ' ' + comment : ''}`;
  2275. });
  2276. lines.splice(regionOrderStart, regionOrderEnd - regionOrderStart, ...newRegionOrderLines);
  2277. // 调整 regionsStart 和 regionsEnd
  2278. const lineDiff = newRegionOrderLines.length - (regionOrderEnd - regionOrderStart);
  2279. if (regionsStart > regionOrderEnd) {
  2280. regionsStart += lineDiff;
  2281. regionsEnd += lineDiff;
  2282. }
  2283. }
  2284. // 更新 regions 对象
  2285. if (regionsStart > 0 && regionsEnd > regionsStart) {
  2286. const originalRegionsBlock = lines.slice(regionsStart, regionsEnd);
  2287. const commentMap = {};
  2288. originalRegionsBlock.forEach(line => {
  2289. const match = line.match(/^\s*([a-z_]+):\s*[^#]*(#.*)?$/);
  2290. if (match) {
  2291. const key = match[1];
  2292. const comment = match[2] || '';
  2293. if (key) commentMap[key] = comment;
  2294. }
  2295. });
  2296. const indentStr = ' '.repeat(regionsIndent);
  2297. const newRegionsLines = regions.map(r => {
  2298. const comment = commentMap[r.key] || '';
  2299. return `${indentStr}${r.key}: ${r.enabled}${comment ? ' ' + comment.trim() : ''}`;
  2300. });
  2301. lines.splice(regionsStart, regionsEnd - regionsStart, ...newRegionsLines);
  2302. }
  2303. editor.value = lines.join('\n');
  2304. currentYaml = lines.join('\n');
  2305. updateBackdrop('yaml-editor', 'yaml-backdrop');
  2306. debounceSaveConfig();
  2307. renderDisplayRegionsList();
  2308. }
  2309. // 解析当前配置中的 RSS 源列表
  2310. function parseRssFeedsFromYaml() {
  2311. try {
  2312. const doc = jsyaml.load(currentYaml);
  2313. if (doc && doc.rss && doc.rss.feeds) {
  2314. return doc.rss.feeds;
  2315. }
  2316. } catch (e) {}
  2317. return [];
  2318. }
  2319. // 渲染 RSS 源列表
  2320. function renderRssFeedsList() {
  2321. const container = document.getElementById('rss-feeds-list');
  2322. if (!container) return;
  2323. const feeds = parseRssFeedsFromYaml();
  2324. if (feeds.length === 0) {
  2325. container.innerHTML = `<div class="text-xs text-gray-400 italic">暂无 RSS 源,请添加</div>`;
  2326. return;
  2327. }
  2328. container.innerHTML = feeds.map((f, idx) => `
  2329. <div class="rss-feed-item bg-gray-50 rounded-lg px-3 py-2 border border-gray-200 hover:border-blue-300 transition-colors" data-index="${idx}">
  2330. <div class="flex items-center justify-between">
  2331. <div class="flex items-center gap-2 flex-1 min-w-0">
  2332. <i class="fa-solid fa-rss text-orange-400"></i>
  2333. <span class="text-xs font-medium text-gray-700 truncate">${f.name}</span>
  2334. <span class="text-[10px] text-gray-400">(${f.id})</span>
  2335. ${f.enabled === false ? '<span class="text-[9px] bg-gray-200 text-gray-500 px-1 rounded">已禁用</span>' : ''}
  2336. </div>
  2337. <div class="flex items-center gap-1">
  2338. <button onclick="editRssFeed(${idx})" class="text-blue-400 hover:text-blue-600 text-xs px-1" title="编辑">
  2339. <i class="fa-solid fa-pen"></i>
  2340. </button>
  2341. <button onclick="toggleRssFeed(${idx})" class="text-gray-400 hover:text-gray-600 text-xs px-1" title="${f.enabled === false ? '启用' : '禁用'}">
  2342. <i class="fa-solid fa-${f.enabled === false ? 'eye' : 'eye-slash'}"></i>
  2343. </button>
  2344. <button onclick="removeRssFeed(${idx})" class="text-red-400 hover:text-red-600 text-xs px-1" title="删除">
  2345. <i class="fa-solid fa-trash"></i>
  2346. </button>
  2347. </div>
  2348. </div>
  2349. <div class="text-[10px] text-gray-400 mt-1 truncate" title="${f.url}">${f.url}</div>
  2350. </div>
  2351. `).join('');
  2352. }
  2353. // 删除 RSS 源
  2354. window.removeRssFeed = function(index) {
  2355. const feeds = parseRssFeedsFromYaml();
  2356. if (index < 0 || index >= feeds.length) return;
  2357. const feedName = feeds[index].name;
  2358. if (!confirm(`确定要删除 RSS 源 "${feedName}" 吗?`)) return;
  2359. feeds.splice(index, 1);
  2360. updateRssFeedsInYaml(feeds);
  2361. }
  2362. // 切换 RSS 源启用状态
  2363. window.toggleRssFeed = function(index) {
  2364. const feeds = parseRssFeedsFromYaml();
  2365. if (index < 0 || index >= feeds.length) return;
  2366. feeds[index].enabled = feeds[index].enabled === false ? true : false;
  2367. updateRssFeedsInYaml(feeds);
  2368. }
  2369. // 编辑 RSS 源
  2370. window.editRssFeed = function(index) {
  2371. const feeds = parseRssFeedsFromYaml();
  2372. if (index < 0 || index >= feeds.length) return;
  2373. const feed = feeds[index];
  2374. openRssModalWithData(feed, index);
  2375. }
  2376. // 更新 YAML 中的 RSS 配置(保留注释)
  2377. function updateRssFeedsInYaml(feeds) {
  2378. const editor = document.getElementById('yaml-editor');
  2379. let yaml = editor.value;
  2380. const lines = yaml.split('\n');
  2381. // 找到 rss.feeds 的位置
  2382. let feedsStart = -1;
  2383. let feedsEnd = -1;
  2384. let inRss = false;
  2385. let inFeeds = false;
  2386. let lastDataLineIndex = -1; // 记录最后一个数据行的位置
  2387. for (let i = 0; i < lines.length; i++) {
  2388. const line = lines[i];
  2389. const trimmed = line.trim();
  2390. if (line.match(/^rss:/)) {
  2391. inRss = true;
  2392. continue;
  2393. }
  2394. if (inRss && !inFeeds && trimmed.startsWith('feeds:')) {
  2395. feedsStart = i + 1;
  2396. inFeeds = true;
  2397. continue;
  2398. }
  2399. if (inFeeds) {
  2400. const indent = line.search(/\S/);
  2401. // 如果是数据行(以 - 开头或是数据项的属性)
  2402. if (trimmed.startsWith('-')) {
  2403. lastDataLineIndex = i;
  2404. } else if (trimmed && !trimmed.startsWith('#') && indent > 2) {
  2405. // 数据项的属性行(如 name:, id:, url:)
  2406. lastDataLineIndex = i;
  2407. } else if (trimmed && !trimmed.startsWith('#') && indent <= 2 && indent >= 0) {
  2408. // 遇到缩进更小的非注释行,说明离开了 feeds 区域
  2409. feedsEnd = lastDataLineIndex + 1;
  2410. break;
  2411. }
  2412. }
  2413. // 检查是否进入下一个顶级模块
  2414. if (inRss && line.match(/^[a-z_]+:/) && !line.match(/^rss:/)) {
  2415. if (lastDataLineIndex >= 0) {
  2416. feedsEnd = lastDataLineIndex + 1;
  2417. } else {
  2418. feedsEnd = i;
  2419. }
  2420. break;
  2421. }
  2422. }
  2423. // 如果没有找到结束位置,使用最后一个数据行的下一行
  2424. if (feedsEnd === -1) {
  2425. feedsEnd = lastDataLineIndex >= 0 ? lastDataLineIndex + 1 : lines.length;
  2426. }
  2427. // 提取区域内的注释(保留在开头的注释)
  2428. const regionLines = lines.slice(feedsStart, feedsEnd);
  2429. const leadingComments = [];
  2430. for (const line of regionLines) {
  2431. const trimmed = line.trim();
  2432. if (trimmed.startsWith('#')) {
  2433. leadingComments.push(line);
  2434. } else if (trimmed.startsWith('-') || (trimmed && !trimmed.startsWith('#'))) {
  2435. // 遇到第一个数据项,停止收集注释
  2436. break;
  2437. } else if (trimmed === '') {
  2438. // 空行也保留
  2439. leadingComments.push(line);
  2440. }
  2441. }
  2442. // 构建新的 feeds 内容
  2443. const indent = ' '; // 4 空格缩进
  2444. const newFeedsLines = feeds.map(f => {
  2445. let feedYaml = `${indent}- id: "${f.id}"\n${indent} name: "${f.name}"\n${indent} url: "${f.url}"`;
  2446. if (f.enabled === false) {
  2447. feedYaml += `\n${indent} enabled: false`;
  2448. }
  2449. if (f.max_age_days !== undefined && f.max_age_days !== '') {
  2450. feedYaml += `\n${indent} max_age_days: ${f.max_age_days}`;
  2451. }
  2452. return feedYaml;
  2453. }).join('\n\n');
  2454. const beforeFeeds = lines.slice(0, feedsStart);
  2455. const afterFeeds = lines.slice(feedsEnd);
  2456. // 组合:前面内容 + 开头注释 + 新数据 + 空行 + 后面内容
  2457. const newYaml = [
  2458. ...beforeFeeds,
  2459. ...(leadingComments.length > 0 ? leadingComments : []),
  2460. newFeedsLines,
  2461. '',
  2462. ...afterFeeds
  2463. ].join('\n');
  2464. editor.value = newYaml;
  2465. currentYaml = newYaml;
  2466. updateBackdrop('yaml-editor', 'yaml-backdrop');
  2467. debounceSaveConfig();
  2468. renderRssFeedsList();
  2469. renderStandaloneLists(); // 同步更新独立展示区的 RSS 选择列表
  2470. }
  2471. // 打开 RSS 添加/编辑弹窗
  2472. window.openRssModal = function() {
  2473. openRssModalWithData(null, -1);
  2474. }
  2475. function openRssModalWithData(feed, editIndex) {
  2476. const modal = document.getElementById('rss-modal');
  2477. document.getElementById('rss-id').value = feed ? feed.id : '';
  2478. document.getElementById('rss-name').value = feed ? feed.name : '';
  2479. document.getElementById('rss-url').value = feed ? feed.url : '';
  2480. document.getElementById('rss-max-age').value = feed && feed.max_age_days !== undefined ? feed.max_age_days : '';
  2481. modal.dataset.editIndex = editIndex;
  2482. const title = modal.querySelector('h3');
  2483. if (title) {
  2484. title.innerHTML = editIndex >= 0 ?
  2485. '<i class="fa-solid fa-rss mr-2 text-orange-500"></i>编辑 RSS 源' :
  2486. '<i class="fa-solid fa-rss mr-2 text-orange-500"></i>添加 RSS 源';
  2487. }
  2488. modal.classList.remove('hidden');
  2489. }
  2490. // 关闭 RSS 弹窗
  2491. window.closeRssModal = function() {
  2492. const modal = document.getElementById('rss-modal');
  2493. modal.classList.add('hidden');
  2494. modal.dataset.editIndex = '-1';
  2495. document.getElementById('rss-id').value = '';
  2496. document.getElementById('rss-name').value = '';
  2497. document.getElementById('rss-url').value = '';
  2498. document.getElementById('rss-max-age').value = '';
  2499. }
  2500. // 确认添加/编辑 RSS
  2501. window.confirmAddRss = function() {
  2502. const modal = document.getElementById('rss-modal');
  2503. const editIndex = parseInt(modal.dataset.editIndex || '-1');
  2504. const id = document.getElementById('rss-id').value.trim();
  2505. const name = document.getElementById('rss-name').value.trim();
  2506. const url = document.getElementById('rss-url').value.trim();
  2507. const maxAge = document.getElementById('rss-max-age').value.trim();
  2508. if (!id || !name || !url) {
  2509. alert('请填写完整信息:ID、名称和 URL 都是必填项');
  2510. return;
  2511. }
  2512. const feeds = parseRssFeedsFromYaml();
  2513. const newFeed = { id, name, url };
  2514. if (maxAge) {
  2515. newFeed.max_age_days = parseInt(maxAge);
  2516. }
  2517. if (editIndex >= 0) {
  2518. feeds[editIndex] = newFeed;
  2519. } else {
  2520. feeds.push(newFeed);
  2521. }
  2522. updateRssFeedsInYaml(feeds);
  2523. closeRssModal();
  2524. }
  2525. // ==========================================
  2526. // 14. 独立展示区 (Standalone) 管理功能
  2527. // ==========================================
  2528. function parseStandaloneConfigFromYaml() {
  2529. try {
  2530. const doc = jsyaml.load(currentYaml);
  2531. if (doc && doc.display && doc.display.standalone) {
  2532. return {
  2533. platforms: doc.display.standalone.platforms || [],
  2534. rss_feeds: doc.display.standalone.rss_feeds || []
  2535. };
  2536. }
  2537. } catch (e) {}
  2538. return { platforms: [], rss_feeds: [] };
  2539. }
  2540. function renderStandaloneLists() {
  2541. const platformsContainer = document.getElementById('standalone-platforms-list');
  2542. const rssContainer = document.getElementById('standalone-rss-list');
  2543. if (!platformsContainer || !rssContainer) return;
  2544. const standaloneConfig = parseStandaloneConfigFromYaml();
  2545. const availablePlatforms = parsePlatformsFromYaml();
  2546. const availableRss = parseRssFeedsFromYaml();
  2547. // Render Platforms
  2548. if (availablePlatforms.length === 0) {
  2549. platformsContainer.innerHTML = `<div class="col-span-2 text-xs text-gray-400 italic">暂无可用平台</div>`;
  2550. } else {
  2551. platformsContainer.innerHTML = availablePlatforms.map(p => {
  2552. const isChecked = standaloneConfig.platforms.includes(p.id);
  2553. return `
  2554. <label class="flex items-center gap-2 p-1.5 rounded hover:bg-white transition-colors cursor-pointer">
  2555. <input type="checkbox" onchange="toggleStandaloneItem('platforms', '${p.id}')"
  2556. ${isChecked ? 'checked' : ''} class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
  2557. <div class="min-w-0">
  2558. <div class="text-xs font-medium text-gray-700 truncate">${p.name}</div>
  2559. <div class="text-[9px] text-gray-400 truncate">${p.id}</div>
  2560. </div>
  2561. </label>
  2562. `;
  2563. }).join('');
  2564. }
  2565. // Render RSS
  2566. if (availableRss.length === 0) {
  2567. rssContainer.innerHTML = `<div class="text-xs text-gray-400 italic">暂无可用 RSS 源</div>`;
  2568. } else {
  2569. rssContainer.innerHTML = availableRss.map(f => {
  2570. const isChecked = standaloneConfig.rss_feeds.includes(f.id);
  2571. return `
  2572. <label class="flex items-center gap-2 p-1.5 rounded hover:bg-white transition-colors cursor-pointer">
  2573. <input type="checkbox" onchange="toggleStandaloneItem('rss_feeds', '${f.id}')"
  2574. ${isChecked ? 'checked' : ''} class="rounded border-gray-300 text-blue-600 focus:ring-blue-500">
  2575. <div class="min-w-0 flex-1">
  2576. <div class="flex items-center justify-between">
  2577. <span class="text-xs font-medium text-gray-700 truncate">${f.name}</span>
  2578. <span class="text-[9px] text-gray-400 ml-2">${f.id}</span>
  2579. </div>
  2580. <div class="text-[9px] text-gray-400 truncate">${f.url}</div>
  2581. </div>
  2582. </label>
  2583. `;
  2584. }).join('');
  2585. }
  2586. }
  2587. window.toggleStandaloneItem = function(type, id) {
  2588. const config = parseStandaloneConfigFromYaml();
  2589. const list = config[type];
  2590. const index = list.indexOf(id);
  2591. if (index === -1) {
  2592. list.push(id);
  2593. } else {
  2594. list.splice(index, 1);
  2595. }
  2596. updateStandaloneConfigInYaml(type, list);
  2597. }
  2598. function updateStandaloneConfigInYaml(type, list) {
  2599. const editor = document.getElementById('yaml-editor');
  2600. let yaml = editor.value;
  2601. const lines = yaml.split('\n');
  2602. // 找到 display -> standalone -> [type]
  2603. let inDisplay = false;
  2604. let inStandalone = false;
  2605. let targetLineIndex = -1;
  2606. let indent = '';
  2607. for (let i = 0; i < lines.length; i++) {
  2608. const line = lines[i];
  2609. if (line.match(/^display:/)) {
  2610. inDisplay = true;
  2611. continue;
  2612. }
  2613. if (inDisplay && line.trim().startsWith('standalone:')) {
  2614. inStandalone = true;
  2615. continue;
  2616. }
  2617. if (inStandalone) {
  2618. // 检查是否离开 standalone (遇到缩进更少或相同的非注释行)
  2619. const currentIndent = line.search(/\S/);
  2620. // standalone 下一级的缩进
  2621. if (line.match(new RegExp(`^\\s*${type}:`))) {
  2622. targetLineIndex = i;
  2623. indent = line.substring(0, line.indexOf(type));
  2624. break;
  2625. }
  2626. // 如果遇到下一个模块,停止
  2627. if (line.match(/^[a-z_]+:/) && !line.match(/^display:/)) break;
  2628. }
  2629. }
  2630. if (targetLineIndex !== -1) {
  2631. // 构建新的数组字符串 ["item1", "item2"]
  2632. const jsonStr = JSON.stringify(list);
  2633. // 保留原有注释
  2634. const originalLine = lines[targetLineIndex];
  2635. const commentMatch = originalLine.match(/#.*$/);
  2636. const comment = commentMatch ? commentMatch[0] : '';
  2637. lines[targetLineIndex] = `${indent}${type}: ${jsonStr}${comment ? ' ' + comment : ''}`;
  2638. const newYaml = lines.join('\n');
  2639. editor.value = newYaml;
  2640. currentYaml = newYaml;
  2641. updateBackdrop('yaml-editor', 'yaml-backdrop');
  2642. debounceSaveConfig();
  2643. // 不需要重新渲染整个列表,因为是 checkbox 点击触发的
  2644. // 但如果需要保持一致性,可以重新渲染
  2645. }
  2646. }
  2647. // 从文本中提取版本号
  2648. function extractVersion(text) {
  2649. // 匹配 Version: v5.3.0 或 Version: 5.3.0 格式
  2650. const versionMatch = text.match(/Version:\s*v?(\d+\.\d+\.\d+)/i);
  2651. if (versionMatch) {
  2652. return versionMatch[1]; // 返回不带 v 的版本号
  2653. }
  2654. return null;
  2655. }
  2656. // 比较版本号 (返回 1: v1 > v2, -1: v1 < v2, 0: v1 == v2)
  2657. function compareVersions(v1, v2) {
  2658. if (!v1 || !v2) return 0;
  2659. const parts1 = v1.split('.').map(Number);
  2660. const parts2 = v2.split('.').map(Number);
  2661. for (let i = 0; i < Math.max(parts1.length, parts2.length); i++) {
  2662. const num1 = parts1[i] || 0;
  2663. const num2 = parts2[i] || 0;
  2664. if (num1 > num2) return 1;
  2665. if (num1 < num2) return -1;
  2666. }
  2667. return 0;
  2668. }
  2669. // 版本检测主函数
  2670. window.checkVersion = async function() {
  2671. const btn = document.getElementById('version-check-btn');
  2672. const originalHTML = btn.innerHTML;
  2673. btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i><span>检测中...</span>';
  2674. btn.disabled = true;
  2675. try {
  2676. const versionRes = await fetch(REMOTE_VERSION_URL);
  2677. if (!versionRes.ok) {
  2678. throw new Error(`版本信息获取失败: ${versionRes.status}`);
  2679. }
  2680. const versionConfigText = await versionRes.text();
  2681. const versionMap = {};
  2682. versionConfigText.split('\n').forEach(line => {
  2683. const parts = line.trim().split('=');
  2684. if (parts.length >= 2) {
  2685. versionMap[parts[0].trim()] = parts[1].trim();
  2686. }
  2687. });
  2688. const currentTab = getCurrentTab();
  2689. let currentVersion = null;
  2690. let fileName = '';
  2691. if (currentTab === 'config') {
  2692. currentVersion = extractVersion(currentYaml);
  2693. fileName = 'config.yaml';
  2694. } else {
  2695. currentVersion = extractVersion(currentFrequency);
  2696. fileName = 'frequency_words.txt';
  2697. }
  2698. const latestVersion = versionMap[fileName];
  2699. if (!latestVersion) {
  2700. throw new Error(`未在远程版本清单中找到 ${fileName}`);
  2701. }
  2702. showVersionComparisonModal(fileName, currentVersion, latestVersion);
  2703. } catch (err) {
  2704. console.error('版本检测失败:', err);
  2705. showToast(`版本检测失败: ${err.message}`, 'error');
  2706. } finally {
  2707. btn.innerHTML = originalHTML;
  2708. btn.disabled = false;
  2709. }
  2710. }
  2711. // 获取当前 Tab
  2712. function getCurrentTab() {
  2713. return currentTab;
  2714. }
  2715. // 显示版本对比弹窗
  2716. function showVersionComparisonModal(fileName, currentVersion, latestVersion) {
  2717. const existingModal = document.getElementById('version-comparison-modal');
  2718. if (existingModal) existingModal.remove();
  2719. const comparison = compareVersions(currentVersion, latestVersion);
  2720. let statusIcon = '';
  2721. let statusText = '';
  2722. let statusColor = '';
  2723. let actionButtons = '';
  2724. if (!currentVersion) {
  2725. statusIcon = '<i class="fa-solid fa-question-circle text-gray-500 text-3xl"></i>';
  2726. statusText = '未检测到版本信息';
  2727. statusColor = 'text-gray-600';
  2728. actionButtons = `
  2729. <button onclick="closeVersionModal()" class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">关闭</button>
  2730. <button onclick="updateToLatest()" class="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
  2731. <i class="fa-solid fa-download mr-1"></i>更新到最新版本
  2732. </button>
  2733. `;
  2734. } else if (comparison < 0) {
  2735. statusIcon = '<i class="fa-solid fa-arrow-up text-orange-500 text-3xl"></i>';
  2736. statusText = '发现新版本';
  2737. statusColor = 'text-orange-600';
  2738. actionButtons = `
  2739. <button onclick="closeVersionModal()" class="px-4 py-2 text-gray-600 hover:bg-gray-100 rounded-lg">稍后更新</button>
  2740. <button onclick="updateToLatest()" class="px-4 py-2 bg-orange-600 text-white rounded-lg hover:bg-orange-700">
  2741. <i class="fa-solid fa-download mr-1"></i>立即更新
  2742. </button>
  2743. `;
  2744. } else if (comparison > 0) {
  2745. statusIcon = '<i class="fa-solid fa-flask text-purple-500 text-3xl"></i>';
  2746. statusText = '当前版本较新(开发版本?)';
  2747. statusColor = 'text-purple-600';
  2748. actionButtons = `
  2749. <button onclick="closeVersionModal()" class="px-4 py-2 bg-gray-100 text-gray-600 hover:bg-gray-200 rounded-lg">关闭</button>
  2750. `;
  2751. } else {
  2752. statusIcon = '<i class="fa-solid fa-check-circle text-green-500 text-3xl"></i>';
  2753. statusText = '已是最新版本';
  2754. statusColor = 'text-green-600';
  2755. actionButtons = `
  2756. <button onclick="closeVersionModal()" class="px-4 py-2 bg-gray-100 text-gray-600 hover:bg-gray-200 rounded-lg">关闭</button>
  2757. `;
  2758. }
  2759. const modal = document.createElement('div');
  2760. modal.id = 'version-comparison-modal';
  2761. modal.className = 'modal-overlay';
  2762. modal.innerHTML = `
  2763. <div class="modal-content" style="max-width: 480px;">
  2764. <div class="flex items-center justify-between mb-4">
  2765. <h3 class="text-lg font-bold text-gray-800">
  2766. <i class="fa-solid fa-code-compare mr-2 text-blue-500"></i>版本检测结果
  2767. </h3>
  2768. <button onclick="closeVersionModal()" class="text-gray-400 hover:text-gray-600">
  2769. <i class="fa-solid fa-times text-xl"></i>
  2770. </button>
  2771. </div>
  2772. <div class="text-center py-6">
  2773. ${statusIcon}
  2774. <div class="text-xl font-bold ${statusColor} mt-3">${statusText}</div>
  2775. </div>
  2776. <div class="bg-gray-50 rounded-lg p-4 space-y-3 mb-4">
  2777. <div class="flex items-center justify-between text-sm">
  2778. <span class="text-gray-600">配置文件</span>
  2779. <span class="font-mono font-bold text-gray-800">${fileName}</span>
  2780. </div>
  2781. <div class="border-t border-gray-200"></div>
  2782. <div class="flex items-center justify-between text-sm">
  2783. <span class="text-gray-600">当前版本</span>
  2784. <span class="font-mono font-bold ${currentVersion ? 'text-blue-600' : 'text-gray-400'}">
  2785. ${currentVersion ? 'v' + currentVersion : '未知'}
  2786. </span>
  2787. </div>
  2788. <div class="flex items-center justify-between text-sm">
  2789. <span class="text-gray-600">最新版本</span>
  2790. <span class="font-mono font-bold text-green-600">v${latestVersion}</span>
  2791. </div>
  2792. </div>
  2793. ${comparison < 0 || !currentVersion ? `
  2794. <div class="text-xs text-gray-500 bg-yellow-50 border border-yellow-200 rounded p-3 mb-4">
  2795. <i class="fa-solid fa-lightbulb mr-1 text-yellow-600"></i>
  2796. <strong>提示:</strong>更新将从 GitHub 加载最新的 ${fileName},你当前的修改将被覆盖。建议先复制保存你的自定义配置。
  2797. </div>
  2798. ` : ''}
  2799. <div class="flex justify-end gap-2">
  2800. ${actionButtons}
  2801. </div>
  2802. </div>
  2803. `;
  2804. document.body.appendChild(modal);
  2805. }
  2806. window.closeVersionModal = function() {
  2807. const modal = document.getElementById('version-comparison-modal');
  2808. if (modal) modal.remove();
  2809. }
  2810. // ==========================================
  2811. // 13. 平台添加弹窗逻辑
  2812. // ==========================================
  2813. // 预定义可用平台列表 (仅包含官方默认支持的平台)
  2814. const PRESET_PLATFORMS = [
  2815. { key: 'toutiao', name: '今日头条' },
  2816. { key: 'baidu', name: '百度热搜' },
  2817. { key: 'wallstreetcn-hot', name: '华尔街见闻' },
  2818. { key: 'thepaper', name: '澎湃新闻' },
  2819. { key: 'bilibili-hot-search', name: 'bilibili 热搜' },
  2820. { key: 'cls-hot', name: '财联社热门' },
  2821. { key: 'ifeng', name: '凤凰网' },
  2822. { key: 'tieba', name: '贴吧' },
  2823. { key: 'weibo', name: '微博' },
  2824. { key: 'douyin', name: '抖音' },
  2825. { key: 'zhihu', name: '知乎' }
  2826. ];
  2827. /**
  2828. * 打开平台添加弹窗
  2829. */
  2830. window.openPlatformModal = function() {
  2831. const modal = document.getElementById('platform-modal');
  2832. if (modal) {
  2833. modal.classList.remove('hidden');
  2834. if (typeof switchPlatformTab === 'function') {
  2835. switchPlatformTab('select');
  2836. }
  2837. renderAvailablePlatforms();
  2838. }
  2839. }
  2840. /**
  2841. * 关闭平台添加弹窗
  2842. */
  2843. window.closePlatformModal = function() {
  2844. const modal = document.getElementById('platform-modal');
  2845. if (modal) {
  2846. modal.classList.add('hidden');
  2847. }
  2848. }
  2849. /**
  2850. * 切换平台添加标签页
  2851. */
  2852. window.switchPlatformTab = function(tab) {
  2853. currentPlatformTab = tab;
  2854. // 更新 Tab 样式
  2855. const tabSelect = document.getElementById('tab-platform-select');
  2856. const tabCustom = document.getElementById('tab-platform-custom');
  2857. if (tab === 'select') {
  2858. if (tabSelect) {
  2859. tabSelect.classList.add('text-blue-600', 'border-blue-600');
  2860. tabSelect.classList.remove('text-gray-500', 'border-transparent');
  2861. }
  2862. if (tabCustom) {
  2863. tabCustom.classList.remove('text-blue-600', 'border-blue-600');
  2864. tabCustom.classList.add('text-gray-500', 'border-transparent');
  2865. }
  2866. const selectPanel = document.getElementById('platform-select-panel');
  2867. const customPanel = document.getElementById('platform-custom-panel');
  2868. if (selectPanel) selectPanel.classList.remove('hidden');
  2869. if (customPanel) customPanel.classList.add('hidden');
  2870. } else {
  2871. if (tabCustom) {
  2872. tabCustom.classList.add('text-blue-600', 'border-blue-600');
  2873. tabCustom.classList.remove('text-gray-500', 'border-transparent');
  2874. }
  2875. if (tabSelect) {
  2876. tabSelect.classList.remove('text-blue-600', 'border-blue-600');
  2877. tabSelect.classList.add('text-gray-500', 'border-transparent');
  2878. }
  2879. const selectPanel = document.getElementById('platform-select-panel');
  2880. const customPanel = document.getElementById('platform-custom-panel');
  2881. if (selectPanel) selectPanel.classList.add('hidden');
  2882. if (customPanel) customPanel.classList.remove('hidden');
  2883. }
  2884. }
  2885. /**
  2886. * 渲染可用平台列表(排除已添加的)
  2887. */
  2888. function renderAvailablePlatforms() {
  2889. const container = document.getElementById('available-platforms-list');
  2890. const tip = document.getElementById('no-platforms-tip');
  2891. if (!container) return;
  2892. container.innerHTML = '';
  2893. const currentPlatforms = parsePlatformsFromYaml();
  2894. const existingKeys = currentPlatforms.map(p => p.id);
  2895. const available = PRESET_PLATFORMS.filter(p => !existingKeys.includes(p.key));
  2896. if (available.length === 0) {
  2897. if (tip) {
  2898. tip.classList.remove('hidden');
  2899. tip.innerHTML = `<i class="fa-solid fa-check-circle text-green-500 mr-2"></i>所有预设平台已添加`;
  2900. }
  2901. } else {
  2902. if (tip) tip.classList.add('hidden');
  2903. available.forEach(p => {
  2904. const div = document.createElement('div');
  2905. div.className = 'flex items-center justify-between p-3 border border-gray-100 rounded hover:bg-blue-50 cursor-pointer transition-colors group';
  2906. div.onclick = () => confirmAddPlatform(p.key, p.name);
  2907. div.innerHTML = `
  2908. <div class="flex items-center gap-3">
  2909. <div class="w-8 h-8 rounded bg-gray-100 flex items-center justify-center text-gray-500 group-hover:bg-white group-hover:text-blue-600">
  2910. <i class="fa-solid fa-cube"></i>
  2911. </div>
  2912. <div>
  2913. <div class="font-bold text-gray-800 text-sm">${p.name}</div>
  2914. <div class="text-xs text-gray-400 font-mono">${p.key}</div>
  2915. </div>
  2916. </div>
  2917. <button class="text-gray-300 group-hover:text-blue-600">
  2918. <i class="fa-solid fa-plus-circle text-lg"></i>
  2919. </button>
  2920. `;
  2921. container.appendChild(div);
  2922. });
  2923. }
  2924. }
  2925. /**
  2926. * 确认添加平台
  2927. */
  2928. window.confirmAddPlatform = function(key, name) {
  2929. let platformKey = key;
  2930. let platformName = name;
  2931. // 如果是手动输入模式 (且未传入 key)
  2932. if (currentPlatformTab === 'custom' && !key) {
  2933. const keyInput = document.getElementById('custom-platform-key');
  2934. const nameInput = document.getElementById('custom-platform-name');
  2935. if (keyInput) platformKey = keyInput.value.trim();
  2936. if (nameInput) platformName = nameInput.value.trim();
  2937. if (!platformKey) {
  2938. alert('请输入平台 Key');
  2939. return;
  2940. }
  2941. if (!platformName) {
  2942. platformName = platformKey;
  2943. }
  2944. } else if (currentPlatformTab === 'select' && !key) {
  2945. alert('请直接点击上方列表中的平台进行添加');
  2946. return;
  2947. }
  2948. // 检查是否已存在
  2949. const currentPlatforms = parsePlatformsFromYaml();
  2950. if (currentPlatforms.find(p => p.id === platformKey)) {
  2951. alert(`平台 ${platformKey} 已存在!`);
  2952. return;
  2953. }
  2954. // 添加到 YAML (注意字段是 id 和 name)
  2955. const newPlatform = {
  2956. id: platformKey,
  2957. name: platformName,
  2958. enabled: true
  2959. };
  2960. // 重新构建 YAML
  2961. currentPlatforms.push(newPlatform);
  2962. updatePlatformsInYaml(currentPlatforms);
  2963. closePlatformModal();
  2964. const keyInput = document.getElementById('custom-platform-key');
  2965. const nameInput = document.getElementById('custom-platform-name');
  2966. if (keyInput) keyInput.value = '';
  2967. if (nameInput) nameInput.value = '';
  2968. renderPlatformsList();
  2969. showToast(`平台 ${platformName} 已添加`, 'success');
  2970. }
  2971. // 绑定到全局
  2972. window.updateToLatest = async function() {
  2973. closeVersionModal();
  2974. const currentTab = getCurrentTab();
  2975. const fileName = currentTab === 'config' ? 'config.yaml' : 'frequency_words.txt';
  2976. if (!confirm(`确定要从 GitHub 更新 ${fileName} 到最新版本吗?\n\n你当前的自定义配置将被覆盖,建议先复制保存。`)) {
  2977. return;
  2978. }
  2979. showToast('正在从 GitHub 加载最新版本...', 'info');
  2980. try {
  2981. const url = currentTab === 'config' ? REMOTE_CONFIG_URL : REMOTE_FREQUENCY_URL;
  2982. const res = await fetch(url);
  2983. if (!res.ok) {
  2984. throw new Error(`加载失败: ${res.status}`);
  2985. }
  2986. const text = await res.text();
  2987. if (currentTab === 'config') {
  2988. try {
  2989. jsyaml.load(text);
  2990. } catch (yamlErr) {
  2991. showToast(`YAML 语法错误: ${yamlErr.message}`, 'error');
  2992. return;
  2993. }
  2994. document.getElementById('yaml-editor').value = text;
  2995. currentYaml = text;
  2996. syncYamlToUI();
  2997. } else {
  2998. document.getElementById('frequency-editor').value = text;
  2999. currentFrequency = text;
  3000. syncFrequencyToUI();
  3001. }
  3002. saveToLocalStorage();
  3003. showToast(`已更新到最新版本`, 'success');
  3004. } catch (err) {
  3005. console.error('更新失败:', err);
  3006. showToast(`更新失败: ${err.message}`, 'error');
  3007. }
  3008. }
  3009. // ==========================================
  3010. // RSS 辅助功能
  3011. // ==========================================
  3012. function toggleRssTips() {
  3013. const panel = document.getElementById('rss-tips-panel');
  3014. const icon = document.getElementById('rss-tips-icon');
  3015. if (panel) {
  3016. panel.classList.toggle('hidden');
  3017. if (icon) {
  3018. icon.style.transform = panel.classList.contains('hidden') ? 'rotate(0deg)' : 'rotate(180deg)';
  3019. }
  3020. }
  3021. }
  3022. function fillRssUrl(url) {
  3023. const input = document.getElementById('rss-url');
  3024. if (input) {
  3025. input.value = url;
  3026. // 视觉反馈
  3027. input.classList.add('ring-2', 'ring-blue-500', 'bg-blue-50');
  3028. setTimeout(() => {
  3029. input.classList.remove('ring-2', 'ring-blue-500', 'bg-blue-50');
  3030. }, 500);
  3031. }
  3032. }