Google Search Custom Sidebar

Customizable Google Search sidebar: quick filters (lang, time, filetype, country, date), site search, Verbatim & Personalization tools.

当前为 2025-05-21 提交的版本,查看 最新版本

  1. // ==UserScript==
  2. // @name Google Search Custom Sidebar
  3. // @name:zh-TW Google 搜尋自訂側邊欄
  4. // @name:ja Google検索カスタムサイドバー
  5. // @namespace https://gf.qytechs.cn/en/users/1467948-stonedkhajiit
  6. // @version 0.1.0
  7. // @description Customizable Google Search sidebar: quick filters (lang, time, filetype, country, date), site search, Verbatim & Personalization tools.
  8. // @description:zh-TW Google 搜尋自訂側邊欄:快速篩選(語言、時間、檔案類型、國家、日期)、站內搜尋、一字不差與個人化工具。
  9. // @description:ja Google検索カスタムサイドバー:高速フィルター(言語,期間,ファイル形式,国,日付)、サイト検索、完全一致検索とパーソナライズツール。
  10. // @match https://www.google.com/search*
  11. // @include /^https:\/\/(?:ipv4|ipv6|www)\.google\.(?:[a-z\.]+)\/search\?(?:.+&)?q=[^&]+(?:&.+)?$/
  12. // @exclude /^https:\/\/(?:ipv4|ipv6|www)\.google\.(?:[a-z\.]+)\/search\?(?:.+&)?(?:tbm=(?:isch|shop|bks|flm|fin|lcl)|udm=(?:2|28))(?:&.+)?$/
  13. // @icon https://www.google.com/favicon.ico
  14. // @grant GM_addStyle
  15. // @grant GM_getValue
  16. // @grant GM_setValue
  17. // @grant GM_registerMenuCommand
  18. // @grant GM_deleteValue
  19. // @run-at document-idle
  20. // @author StonedKhajiit
  21. // @license MIT
  22. // @require https://update.gf.qytechs.cn/scripts/535624/1592845/Google%20Search%20Custom%20Sidebar%20-%20i18n.js
  23. // @require https://update.gf.qytechs.cn/scripts/535625/1592847/Google%20Search%20Custom%20Sidebar%20-%20Styles.js
  24. // ==/UserScript==
  25.  
  26. (function() {
  27. 'use strict';
  28.  
  29. // --- Constants and Configuration ---
  30. const SCRIPT_INTERNAL_NAME = 'GoogleSearchCustomSidebar';
  31. const SCRIPT_VERSION = '0.1.0';
  32. const LOG_PREFIX = `[${SCRIPT_INTERNAL_NAME} v${SCRIPT_VERSION}]`;
  33.  
  34. const DEFAULT_SECTION_ORDER = [
  35. 'sidebar-section-language', 'sidebar-section-time', 'sidebar-section-filetype',
  36. 'sidebar-section-occurrence',
  37. 'sidebar-section-country', 'sidebar-section-date-range', 'sidebar-section-site-search', 'sidebar-section-tools'
  38. ];
  39.  
  40. const defaultSettings = {
  41. sidebarPosition: { left: 0, top: 80 },
  42. sectionStates: {},
  43. theme: 'system',
  44. hoverMode: false,
  45. idleOpacity: 0.8,
  46. sidebarWidth: 135,
  47. fontSize: 12.5,
  48. headerIconSize: 16,
  49. verticalSpacingMultiplier: 0.5,
  50. interfaceLanguage: 'auto',
  51. visibleSections: {
  52. 'sidebar-section-language': true, 'sidebar-section-time': true, 'sidebar-section-filetype': true,
  53. 'sidebar-section-occurrence': true,
  54. 'sidebar-section-country': true, 'sidebar-section-date-range': true,
  55. 'sidebar-section-site-search': true, 'sidebar-section-tools': true
  56. },
  57. sectionDisplayMode: 'remember',
  58. accordionMode: false,
  59. resetButtonLocation: 'topBlock',
  60. verbatimButtonLocation: 'header',
  61. advancedSearchLinkLocation: 'header',
  62. personalizationButtonLocation: 'tools',
  63. countryDisplayMode: 'iconAndText',
  64. customLanguages: [],
  65. customTimeRanges: [],
  66. customFiletypes: [
  67. { text: "📄Documents", value: "pdf OR docx OR doc OR odt OR rtf OR txt" },
  68. { text: "💹Spreadsheets", value: "xlsx OR xls OR ods OR csv" },
  69. { text: "📊Presentations", value: "pptx OR ppt OR odp OR key" },
  70. ],
  71. customCountries: [],
  72. displayLanguages: [],
  73. displayCountries: [],
  74. favoriteSites: [
  75. // == SINGLE SITES: GENERAL KNOWLEDGE & REFERENCE ==
  76. { text: 'Wikipedia (EN)', url: 'en.wikipedia.org' },
  77. { text: 'Wiktionary', url: 'wiktionary.org' },
  78. { text: 'Internet Archive', url: 'archive.org' },
  79.  
  80. // == SINGLE SITES: DEVELOPER & TECH ==
  81. { text: 'GitHub', url: 'github.com' },
  82. { text: 'GitLab', url: 'gitlab.com' },
  83. { text: 'Stack Overflow', url: 'stackoverflow.com' },
  84. { text: 'Hacker News', url: 'news.ycombinator.com' },
  85. { text: 'Greasy Fork镜像', url: 'gf.qytechs.cn' },
  86.  
  87. // == SINGLE SITES: SOCIAL, FORUMS & COMMUNITIES ==
  88. { text: 'Reddit', url: 'reddit.com' },
  89. { text: 'X', url: 'x.com' },
  90. { text: 'Mastodon', url: 'mastodon.social' },
  91. { text: 'Bluesky', url: 'bsky.app' },
  92. { text: 'Lemmy', url: 'lemmy.world' },
  93.  
  94. // == SINGLE SITES: ENTERTAINMENT, ARTS & HOBBIES ==
  95. { text: 'IMDb', url: 'imdb.com' },
  96. { text: 'TMDb', url: 'themoviedb.org' },
  97. { text: 'Letterboxd', url: 'letterboxd.com' },
  98. { text: 'Metacritic', url: 'metacritic.com' },
  99. { text: 'OpenCritic', url: 'opencritic.com' },
  100. { text: 'Steam', url: 'store.steampowered.com' },
  101. { text: 'Bandcamp', url: 'bandcamp.com' },
  102. { text: 'Last.fm', url: 'last.fm' },
  103.  
  104. // == COMBINED SITE GROUPS ==
  105. {
  106. text: '💬Social',
  107. url: 'x.com OR facebook.com OR instagram.com OR threads.net OR bluesky.social OR mastodon.social OR reddit.com OR tumblr.com OR linkedin.com OR lemmy.world'
  108. },
  109. {
  110. text: '📦Repositories',
  111. url: 'github.com OR gitlab.com OR bitbucket.org OR codeberg.org OR sourceforge.net'
  112. },
  113. {
  114. text: '🎓Academics',
  115. url: 'scholar.google.com OR arxiv.org OR researchgate.net OR jstor.org OR academia.edu OR pubmed.ncbi.nlm.nih.gov OR semanticscholar.org OR core.ac.uk'
  116. },
  117. {
  118. text: '📰News',
  119. url: 'bbc.com/news OR reuters.com OR apnews.com OR nytimes.com OR theguardian.com OR cnn.com OR wsj.com'
  120. },
  121. {
  122. text: '🎨Creative',
  123. url: 'behance.net OR dribbble.com OR artstation.com OR deviantart.com'
  124. }
  125. ],
  126. enableSiteSearchCheckboxMode: true,
  127. enableFiletypeCheckboxMode: true,
  128. sidebarCollapsed: false,
  129. draggableHandleEnabled: true,
  130. enabledPredefinedOptions: {
  131. language: ['lang_en'],
  132. country: ['countryUS'],
  133. time: ['d', 'w', 'm', 'y', 'h'],
  134. filetype: ['pdf', 'docx', 'doc', 'pptx', 'ppt', 'xlsx', 'xls', 'txt']
  135. },
  136. sidebarSectionOrder: [...DEFAULT_SECTION_ORDER]
  137. };
  138.  
  139. let sidebar = null, systemThemeMediaQuery = null;
  140. const MIN_SIDEBAR_TOP_POSITION = 5;
  141. let debouncedSaveSettings;
  142. let globalMessageTimeout = null;
  143.  
  144. const IDS = {
  145. SIDEBAR: 'customizable-search-sidebar', SETTINGS_OVERLAY: 'settings-overlay', SETTINGS_WINDOW: 'settings-window',
  146. COLLAPSE_BUTTON: 'sidebar-collapse-button', SETTINGS_BUTTON: 'open-settings-button',
  147. TOOL_RESET_BUTTON: 'tool-reset-button', TOOL_VERBATIM: 'tool-verbatim', TOOL_PERSONALIZE: 'tool-personalize-search',
  148. APPLY_SELECTED_SITES_BUTTON: 'apply-selected-sites-button',
  149. APPLY_SELECTED_FILETYPES_BUTTON: 'apply-selected-filetypes-button',
  150. FIXED_TOP_BUTTONS: 'sidebar-fixed-top-buttons',
  151. SETTINGS_MESSAGE_BAR: 'gscs-settings-message-bar',
  152. SETTING_WIDTH: 'setting-sidebar-width', SETTING_FONT_SIZE: 'setting-font-size', SETTING_HEADER_ICON_SIZE: 'setting-header-icon-size',
  153. SETTING_VERTICAL_SPACING: 'setting-vertical-spacing', SETTING_INTERFACE_LANGUAGE: 'setting-interface-language',
  154. SETTING_SECTION_MODE: 'setting-section-display-mode', SETTING_ACCORDION: 'setting-accordion-mode',
  155. SETTING_DRAGGABLE: 'setting-draggable-handle', SETTING_RESET_LOCATION: 'setting-reset-button-location',
  156. SETTING_VERBATIM_LOCATION: 'setting-verbatim-button-location', SETTING_ADV_SEARCH_LOCATION: 'setting-adv-search-link-location',
  157. SETTING_PERSONALIZE_LOCATION: 'setting-personalize-button-location',
  158. SETTING_SITE_SEARCH_CHECKBOX_MODE: 'setting-site-search-checkbox-mode',
  159. SETTING_FILETYPE_SEARCH_CHECKBOX_MODE: 'setting-filetype-search-checkbox-mode',
  160. SETTING_COUNTRY_DISPLAY_MODE: 'setting-country-display-mode', SETTING_THEME: 'setting-theme',
  161. SETTING_HOVER: 'setting-hover-mode', SETTING_OPACITY: 'setting-idle-opacity',
  162. TAB_PANE_GENERAL: 'tab-pane-general', TAB_PANE_APPEARANCE: 'tab-pane-appearance', TAB_PANE_FEATURES: 'tab-pane-features', TAB_PANE_CUSTOM: 'tab-pane-custom',
  163. SITES_LIST: 'custom-sites-list', LANG_LIST: 'custom-languages-list', TIME_LIST: 'custom-time-ranges-list',
  164. FT_LIST: 'custom-filetypes-list', COUNTRIES_LIST: 'custom-countries-list',
  165. NEW_SITE_NAME: 'new-site-name', NEW_SITE_URL: 'new-site-url', ADD_SITE_BTN: 'add-site-button',
  166. NEW_LANG_TEXT: 'new-lang-text', NEW_LANG_VALUE: 'new-lang-value', ADD_LANG_BTN: 'add-lang-button',
  167. NEW_TIME_TEXT: 'new-timerange-text', NEW_TIME_VALUE: 'new-timerange-value', ADD_TIME_BTN: 'add-timerange-button',
  168. NEW_FT_TEXT: 'new-ft-text', NEW_FT_VALUE: 'new-ft-value', ADD_FT_BTN: 'add-ft-button',
  169. NEW_COUNTRY_TEXT: 'new-country-text', NEW_COUNTRY_VALUE: 'new-country-value', ADD_COUNTRY_BTN: 'add-country-button',
  170. DATE_MIN: 'date-min', DATE_MAX: 'date-max', DATE_RANGE_ERROR_MSG: 'date-range-error-msg',
  171. SIDEBAR_SECTION_ORDER_LIST: 'sidebar-section-order-list',
  172. NOTIFICATION_CONTAINER: 'gscs-notification-container',
  173. MODAL_ADD_NEW_OPTION_BTN: 'gscs-modal-add-new-option-btn',
  174. MODAL_PREDEFINED_CHOOSER_CONTAINER: 'gscs-modal-predefined-chooser-container',
  175. MODAL_PREDEFINED_CHOOSER_LIST: 'gscs-modal-predefined-chooser-list',
  176. MODAL_PREDEFINED_CHOOSER_ADD_BTN: 'gscs-modal-predefined-chooser-add-btn',
  177. MODAL_PREDEFINED_CHOOSER_CANCEL_BTN: 'gscs-modal-predefined-chooser-cancel-btn',
  178. CLEAR_SITE_SEARCH_OPTION: 'clear-site-search-option',
  179. CLEAR_FILETYPE_SEARCH_OPTION: 'clear-filetype-search-option'
  180. };
  181. const CSS = {
  182. SIDEBAR_COLLAPSED: 'sidebar-collapsed', SIDEBAR_HEADER: 'sidebar-header', SIDEBAR_CONTENT_WRAPPER: 'sidebar-content-wrapper',
  183. DRAG_HANDLE: 'sidebar-drag-handle', SETTINGS_BUTTON: 'sidebar-settings-button', HEADER_BUTTON: 'sidebar-header-button',
  184. SIDEBAR_SECTION: 'sidebar-section', FIXED_TOP_BUTTON_ITEM: 'fixed-top-button-item', SECTION_TITLE: 'section-title',
  185. SECTION_CONTENT: 'section-content', COLLAPSED: 'collapsed', FILTER_OPTION: 'filter-option', SELECTED: 'selected',
  186. SITE_SEARCH_ITEM_CHECKBOX: 'site-search-item-checkbox',
  187. FILETYPE_SEARCH_ITEM_CHECKBOX: 'filetype-search-item-checkbox',
  188. APPLY_SITES_BUTTON: 'apply-sites-button',
  189. APPLY_FILETYPES_BUTTON: 'apply-filetypes-button',
  190. DATE_INPUT_LABEL: 'date-input-label', DATE_INPUT: 'date-input', TOOL_BUTTON: 'tool-button', ACTIVE: 'active',
  191. CUSTOM_LIST: 'custom-list', ITEM_CONTROLS: 'item-controls', EDIT_CUSTOM_ITEM: 'edit-custom-item',
  192. DELETE_CUSTOM_ITEM: 'delete-custom-item', CUSTOM_LIST_INPUT_GROUP: 'custom-list-input-group',
  193. ADD_CUSTOM_BUTTON: 'add-custom-button', SETTINGS_HEADER: 'settings-header', SETTINGS_CLOSE_BTN: 'settings-close-button',
  194. SETTINGS_TABS: 'settings-tabs', TAB_BUTTON: 'tab-button', SETTINGS_TAB_CONTENT: 'settings-tab-content',
  195. TAB_PANE: 'tab-pane', SETTING_ITEM: 'setting-item', INLINE_LABEL: 'inline', SETTINGS_FOOTER: 'settings-footer',
  196. SAVE_BUTTON: 'save-button', CANCEL_BUTTON: 'cancel-button', RESET_BUTTON: 'reset-button',
  197. LIGHT_THEME: 'light-theme', DARK_THEME: 'dark-theme',
  198. SIMPLE_ITEM: 'simple', RANGE_VALUE: 'range-value', RANGE_HINT: 'setting-range-hint', SECTION_ORDER_LIST: 'section-order-list',
  199. INPUT_ERROR_MESSAGE: 'input-error-message', ERROR_VISIBLE: 'error-visible', INPUT_HAS_ERROR: 'input-has-error',
  200. DATE_RANGE_ERROR_MSG: 'date-range-error-message',
  201. MESSAGE_BAR: 'gscs-message-bar', MSG_INFO: 'gscs-msg-info', MSG_SUCCESS: 'gscs-msg-success',
  202. MSG_WARNING: 'gscs-msg-warning', MSG_ERROR: 'gscs-msg-error', MANAGE_CUSTOM_BUTTON: 'manage-custom-button',
  203. NOTIFICATION: 'gscs-notification',
  204. NTF_INFO: 'gscs-ntf-info', NTF_SUCCESS: 'gscs-ntf-success',
  205. NTF_WARNING: 'gscs-ntf-warning', NTF_ERROR: 'gscs-ntf-error',
  206. DRAGGING_ITEM: 'gscs-dragging-item',
  207. DRAG_OVER_HIGHLIGHT: 'gscs-drag-over-highlight',
  208. DRAG_ICON: 'gscs-drag-icon',
  209. REMOVE_FROM_LIST_BTN: 'gscs-remove-from-list-btn',
  210. MODAL_ADD_NEW_OPTION_BTN_CLASS: 'gscs-modal-add-new-option-button-class',
  211. MODAL_PREDEFINED_CHOOSER_CLASS: 'gscs-modal-predefined-chooser',
  212. MODAL_PREDEFINED_CHOOSER_ITEM: 'gscs-modal-predefined-chooser-item',
  213. SETTING_VALUE_HINT: 'setting-value-hint'
  214. };
  215. const DATA_ATTR = {
  216. FILTER_TYPE: 'filterType', FILTER_VALUE: 'filterValue', SITE_URL: 'siteUrl', SECTION_ID: 'sectionId',
  217. FILETYPE_VALUE: 'filetypeValue',
  218. LIST_ID: 'listId', INDEX: 'index', LISTENER_ATTACHED: 'listenerAttached', TAB: 'tab', MANAGE_TYPE: 'managetype',
  219. ITEM_TYPE: 'itemType', ITEM_ID: 'itemId'
  220. };
  221. const STORAGE_KEY = 'googleSearchCustomSidebarSettings_v1';
  222. const SVG_ICONS = {
  223. chevronLeft: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="15 18 9 12 15 6"></polyline></svg>`,
  224. chevronRight: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><polyline points="9 18 15 12 9 6"></polyline></svg>`,
  225. settings: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"></circle><path d="M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 0 1 0 2.83 2 2 0 0 1-2.83 0l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-2 2 2 2 0 0 1-2-2v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 0 1-2.83 0 2 2 0 0 1 0-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1-2-2 2 2 0 0 1 2-2h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 0 1 0-2.83 2 2 0 0 1 2.83 0l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 2-2 2 2 0 0 1 2 2v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 0 1 2.83 0 2 2 0 0 1 0 2.83l-.06-.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 2 2 2 2 0 0 1-2 2h-.09a1.65 1.65 0 0 0-1.51 1z"></path></svg>`,
  226. reset: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="23 4 23 10 17 10"></polyline><polyline points="1 20 1 14 7 14"></polyline><path d="M3.51 9a9 9 0 0 1 14.85-3.36L23 10M1 14l4.64 4.36A9 9 0 0 0 20.49 15"></path></svg>`,
  227. verbatim: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><g transform="translate(-4.3875 -3.2375) scale(1.15)"><path d="M6 17.5c0 1.5 1.5 2.5 3 2.5h1.5c1.5 0 3-1 3-2.5V9c0-1.5-1.5-2.5-3-2.5H9C7.5 6.5 6 7.5 6 9v8.5z"/><path d="M15 17.5c0 1.5 1.5 2.5 3 2.5h1.5c1.5 0 3-1 3-2.5V9c0-1.5-1.5-2.5-3-2.5H18c-1.5 0-3 1-3 2.5v8.5z"/></g></svg>`,
  228. magnifyingGlass: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"></circle><line x1="21" y1="21" x2="16.65" y2="16.65"></line></svg>`,
  229. close: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`,
  230. edit: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path><path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path></svg>`,
  231. delete: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><polyline points="3 6 5 6 21 6"></polyline><path d="M19 6v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6m3 0V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v2"></path><line x1="10" y1="11" x2="10" y2="17"></line><line x1="14" y1="11" x2="14" y2="17"></line></svg>`,
  232. add: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="12" y1="5" x2="12" y2="19"></line><line x1="5" y1="12" x2="19" y2="12"></line></svg>`,
  233. update: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round"><polyline points="20 6 9 17 4 12"></polyline></svg>`,
  234. personalization: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path><circle cx="12" cy="7" r="4"></circle></svg>`,
  235. dragGrip: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="1em" height="1em" fill="currentColor"><circle cx="9" cy="6" r="1.5"/><circle cx="15" cy="6" r="1.5"/><circle cx="9" cy="12" r="1.5"/><circle cx="15" cy="12" r="1.5"/><circle cx="9" cy="18" r="1.5"/><circle cx="15" cy="18" r="1.5"/></svg>`,
  236. removeFromList: `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>`
  237. };
  238. const PREDEFINED_OPTIONS = {
  239. language: [ { textKey: 'predefined_lang_en', value: 'lang_en' }, { textKey: 'predefined_lang_ja', value: 'lang_ja' }, { textKey: 'predefined_lang_ko', value: 'lang_ko' }, { textKey: 'predefined_lang_fr', value: 'lang_fr' }, { textKey: 'predefined_lang_de', value: 'lang_de' }, { textKey: 'predefined_lang_es', value: 'lang_es' }, { textKey: 'predefined_lang_it', value: 'lang_it' }, { textKey: 'predefined_lang_pt', value: 'lang_pt' }, { textKey: 'predefined_lang_ru', value: 'lang_ru' }, { textKey: 'predefined_lang_ar', value: 'lang_ar' }, { textKey: 'predefined_lang_hi', value: 'lang_hi' }, { textKey: 'predefined_lang_nl', value: 'lang_nl' }, { textKey: 'predefined_lang_tr', value: 'lang_tr' }, { textKey: 'predefined_lang_vi', value: 'lang_vi' }, { textKey: 'predefined_lang_th', value: 'lang_th' }, { textKey: 'predefined_lang_id', value: 'lang_id' }, { textKey: 'predefined_lang_zh_tw', value: 'lang_zh-TW' }, { textKey: 'predefined_lang_zh_cn', value: 'lang_zh-CN' }, { textKey: 'predefined_lang_zh_all', value: 'lang_zh-TW|lang_zh-CN' }, ],
  240. country: [ { textKey: 'predefined_country_us', value: 'countryUS' }, { textKey: 'predefined_country_gb', value: 'countryGB' }, { textKey: 'predefined_country_ca', value: 'countryCA' }, { textKey: 'predefined_country_au', value: 'countryAU' }, { textKey: 'predefined_country_de', value: 'countryDE' }, { textKey: 'predefined_country_fr', value: 'countryFR' }, { textKey: 'predefined_country_jp', value: 'countryJP' }, { textKey: 'predefined_country_kr', value: 'countryKR' }, { textKey: 'predefined_country_cn', value: 'countryCN' }, { textKey: 'predefined_country_in', value: 'countryIN' }, { textKey: 'predefined_country_br', value: 'countryBR' }, { textKey: 'predefined_country_mx', value: 'countryMX' }, { textKey: 'predefined_country_es', value: 'countryES' }, { textKey: 'predefined_country_it', value: 'countryIT' }, { textKey: 'predefined_country_ru', value: 'countryRU' }, { textKey: 'predefined_country_nl', value: 'countryNL' }, { textKey: 'predefined_country_sg', value: 'countrySG' }, { textKey: 'predefined_country_hk', value: 'countryHK' }, { textKey: 'predefined_country_tw', value: 'countryTW' }, { textKey: 'predefined_country_my', value: 'countryMY' }, { textKey: 'predefined_country_vn', value: 'countryVN' }, { textKey: 'predefined_country_ph', value: 'countryPH' }, { textKey: 'predefined_country_th', value: 'countryTH' }, { textKey: 'predefined_country_za', value: 'countryZA' }, { textKey: 'predefined_country_tr', value: 'countryTR' }, ],
  241. time: [ { textKey: 'predefined_time_h', value: 'h' }, { textKey: 'predefined_time_h2', value: 'h2' }, { textKey: 'predefined_time_h6', value: 'h6' }, { textKey: 'predefined_time_h12', value: 'h12' }, { textKey: 'predefined_time_d', value: 'd' }, { textKey: 'predefined_time_d2', value: 'd2' }, { textKey: 'predefined_time_d3', value: 'd3' }, { textKey: 'predefined_time_w', value: 'w' }, { textKey: 'predefined_time_m', value: 'm' }, { textKey: 'predefined_time_y', value: 'y' }, ],
  242. filetype: [ { textKey: 'predefined_filetype_pdf', value: 'pdf' }, { textKey: 'predefined_filetype_docx', value: 'docx' }, { textKey: 'predefined_filetype_doc', value: 'doc' }, { textKey: 'predefined_filetype_xlsx', value: 'xlsx' }, { textKey: 'predefined_filetype_xls', value: 'xls' }, { textKey: 'predefined_filetype_pptx', value: 'pptx' }, { textKey: 'predefined_filetype_ppt', value: 'ppt' }, { textKey: 'predefined_filetype_txt', value: 'txt' }, { textKey: 'predefined_filetype_rtf', value: 'rtf' }, { textKey: 'predefined_filetype_html', value: 'html' }, { textKey: 'predefined_filetype_htm', value: 'htm' }, { textKey: 'predefined_filetype_xml', value: 'xml' }, { textKey: 'predefined_filetype_jpg', value: 'jpg' }, { textKey: 'predefined_filetype_png', value: 'png' }, { textKey: 'predefined_filetype_gif', value: 'gif' }, { textKey: 'predefined_filetype_svg', value: 'svg' }, { textKey: 'predefined_filetype_bmp', value: 'bmp' }, { textKey: 'predefined_filetype_js', value: 'js' }, { textKey: 'predefined_filetype_css', value: 'css' }, { textKey: 'predefined_filetype_py', value: 'py' }, { textKey: 'predefined_filetype_java', value: 'java' }, { textKey: 'predefined_filetype_cpp', value: 'cpp' }, { textKey: 'predefined_filetype_cs', value: 'cs' }, { textKey: 'predefined_filetype_kml', value: 'kml'}, { textKey: 'predefined_filetype_kmz', value: 'kmz'}, ]
  243. };
  244. const ALL_SECTION_DEFINITIONS = [
  245. { id: 'sidebar-section-language', type: 'filter', titleKey: 'section_language', scriptDefined: [{textKey:'filter_any_language',v:''}], param: 'lr', predefinedOptionsKey: 'language', customItemsKey: 'customLanguages', displayItemsKey: 'displayLanguages' },
  246. { id: 'sidebar-section-time', type: 'filter', titleKey: 'section_time', scriptDefined: [{textKey:'filter_any_time',v:''}], param: 'qdr', predefinedOptionsKey: 'time', customItemsKey: 'customTimeRanges' },
  247. { id: 'sidebar-section-filetype', type: 'filetype', titleKey: 'section_filetype', scriptDefined: [{ textKey: 'filter_any_format', v: '' }], param: 'as_filetype', predefinedOptionsKey: 'filetype', customItemsKey: 'customFiletypes' },
  248. {
  249. id: 'sidebar-section-occurrence',
  250. type: 'filter',
  251. titleKey: 'section_occurrence',
  252. scriptDefined: [
  253. { textKey: 'filter_occurrence_any', v: 'any' },
  254. { textKey: 'filter_occurrence_title', v: 'title' },
  255. { textKey: 'filter_occurrence_text', v: 'text' },
  256. { textKey: 'filter_occurrence_url', v: 'url' },
  257. ],
  258. param: 'as_occt'
  259. },
  260. { id: 'sidebar-section-country', type: 'filter', titleKey: 'section_country', scriptDefined: [{textKey:'filter_any_country',v:''}], param: 'cr', predefinedOptionsKey: 'country', customItemsKey: 'customCountries', displayItemsKey: 'displayCountries' },
  261. { id: 'sidebar-section-date-range', type: 'date', titleKey: 'section_date_range' },
  262. { id: 'sidebar-section-site-search', type: 'site', titleKey: 'section_site_search', scriptDefined: [{ textKey: 'filter_any_site', v:''}] },
  263. { id: 'sidebar-section-tools', type: 'tools', titleKey: 'section_tools' }
  264. ];
  265.  
  266. const LocalizationService = (function() {
  267. const builtInTranslations = {
  268. 'en': {
  269. scriptName: 'Google Search Custom Sidebar', settingsTitle: 'Google Search Custom Sidebar Settings', manageOptionsTitle: 'Manage Options', manageSitesTitle: 'Manage Favorite Sites', manageLanguagesTitle: 'Manage Language Options', manageCountriesTitle: 'Manage Country/Region Options', manageTimeRangesTitle: 'Manage Time Ranges', manageFileTypesTitle: 'Manage File Types', section_language: 'Language', section_time: 'Time', section_filetype: 'File Type', section_country: 'Country/Region', section_date_range: 'Date Range', section_site_search: 'Site Search', section_tools: 'Tools',
  270. section_occurrence: 'Keyword Location',
  271. filter_any_language: 'Any Language', filter_any_time: 'Any Time', filter_any_format: 'Any Format', filter_any_country: 'Any Country/Region', filter_any_site: 'Any Site',
  272. filter_occurrence_any: 'Anywhere in the page', filter_occurrence_title: 'In the title of the page', filter_occurrence_text: 'In the text of the page', filter_occurrence_url: 'In the URL of the page',
  273. filter_clear_site_search: 'Clear Site Search', filter_clear_tooltip_suffix: '(Clear)', predefined_lang_zh_tw: 'Traditional Chinese', predefined_lang_zh_cn: 'Simplified Chinese', predefined_lang_zh_all: 'All Chinese', predefined_lang_en: 'English', predefined_lang_ja: 'Japanese', predefined_lang_ko: 'Korean', predefined_lang_fr: 'French', predefined_lang_de: 'German', predefined_lang_es: 'Spanish', predefined_lang_it: 'Italian', predefined_lang_pt: 'Portuguese', predefined_lang_ru: 'Russian', predefined_lang_ar: 'Arabic', predefined_lang_hi: 'Hindi', predefined_lang_nl: 'Dutch', predefined_lang_tr: 'Turkish', predefined_lang_vi: 'Vietnamese', predefined_lang_th: 'Thai', predefined_lang_id: 'Indonesian', predefined_country_tw: '🇹🇼 Taiwan', predefined_country_jp: '🇯🇵 Japan', predefined_country_kr: '🇰🇷 South Korea', predefined_country_cn: '🇨🇳 China', predefined_country_hk: '🇭🇰 Hong Kong', predefined_country_sg: '🇸🇬 Singapore', predefined_country_my: '🇲🇾 Malaysia', predefined_country_vn: '🇻🇳 Vietnam', predefined_country_ph: '🇵🇭 Philippines', predefined_country_th: '🇹🇭 Thailand', predefined_country_us: '🇺🇸 United States', predefined_country_ca: '🇨🇦 Canada', predefined_country_br: '🇧🇷 Brazil', predefined_country_mx: '🇲🇽 Mexico', predefined_country_gb: '🇬🇧 United Kingdom', predefined_country_de: '🇩🇪 Germany', predefined_country_fr: '🇫🇷 France', predefined_country_it: '🇮🇹 Italy', predefined_country_es: '🇪🇸 Spain', predefined_country_ru: '🇷🇺 Russia', predefined_country_nl: '🇳🇱 Netherlands', predefined_country_au: '🇦🇺 Australia', predefined_country_in: '🇮🇳 India', predefined_country_za: '🇿🇦 South Africa', predefined_country_tr: '🇹🇷 Turkey', predefined_time_h: 'Past hour', predefined_time_h2: 'Past 2 hours', predefined_time_h6: 'Past 6 hours', predefined_time_h12: 'Past 12 hours', predefined_time_d: 'Past 24 hours', predefined_time_d2: 'Past 2 days', predefined_time_d3: 'Past 3 days', predefined_time_w: 'Past week', predefined_time_m: 'Past month', predefined_time_y: 'Past year', predefined_filetype_pdf: 'PDF', predefined_filetype_docx: 'Word (docx)', predefined_filetype_doc: 'Word (doc)', predefined_filetype_xlsx: 'Excel (xlsx)', predefined_filetype_xls: 'Excel (xls)', predefined_filetype_pptx: 'PowerPoint (pptx)', predefined_filetype_ppt: 'PowerPoint (ppt)', predefined_filetype_txt: 'Plain Text', predefined_filetype_rtf: 'Rich Text Format', predefined_filetype_html: 'Web Page (html)', predefined_filetype_htm: 'Web Page (htm)', predefined_filetype_xml: 'XML', predefined_filetype_jpg: 'JPEG Image', predefined_filetype_png: 'PNG Image', predefined_filetype_gif: 'GIF Image', predefined_filetype_svg: 'SVG Image', predefined_filetype_bmp: 'BMP Image', predefined_filetype_js: 'JavaScript', predefined_filetype_css: 'CSS', predefined_filetype_py: 'Python', predefined_filetype_java: 'Java', predefined_filetype_cpp: 'C++', predefined_filetype_cs: 'C#', predefined_filetype_kml: 'Google Earth (kml)', predefined_filetype_kmz: 'Google Earth (kmz)',
  274. tool_reset_filters: 'Reset Filters', tool_verbatim_search: 'Verbatim Search', tool_advanced_search: 'Advanced Search', tool_apply_date: 'Apply Dates',
  275. tool_personalization_toggle: 'Personalization', tool_apply_selected_sites: 'Apply Selected',
  276. tool_apply_selected_filetypes: 'Apply Selected',
  277. link_advanced_search_title: 'Open Google Advanced Search page', tooltip_site_search: 'Search within {siteUrl}', tooltip_clear_site_search: 'Remove site: restriction', tooltip_toggle_personalization_on: 'Click to turn Personalization ON (Results tailored to you)', tooltip_toggle_personalization_off: 'Click to turn Personalization OFF (More generic results)', settings_tab_general: 'General', settings_tab_appearance: 'Appearance', settings_tab_features: 'Features', settings_tab_custom: 'Custom', settings_close_button_title: 'Close', settings_interface_language: 'Interface Language:', settings_language_auto: 'Auto (Browser Default)', settings_section_mode: 'Section Collapse Mode:', settings_section_mode_remember: 'Remember State', settings_section_mode_expand: 'Expand All', settings_section_mode_collapse: 'Collapse All',
  278. settings_accordion_mode: 'Accordion Mode (only when "Remember State" is active)',
  279. settings_accordion_mode_hint_desc: 'When enabled, expanding one section will automatically collapse other open sections.',
  280. settings_enable_drag: 'Enable Dragging', settings_reset_button_location: 'Reset Button Location:', settings_verbatim_button_location: 'Verbatim Button Location:', settings_adv_search_location: '"Advanced Search" Link Location:', settings_personalize_button_location: 'Personalization Button Location:',
  281. settings_enable_site_search_checkbox_mode: 'Enable Checkbox Mode for Site Search',
  282. settings_enable_site_search_checkbox_mode_hint: 'Allows selecting multiple favorite sites for a combined (OR) search.',
  283. settings_enable_filetype_search_checkbox_mode: 'Enable Checkbox Mode for Filetype Search',
  284. settings_enable_filetype_search_checkbox_mode_hint: 'Allows selecting multiple filetypes for a combined (OR) search.',
  285. settings_location_tools: 'Tools Section', settings_location_top: 'Top Block', settings_location_header: 'Sidebar Header', settings_location_hide: 'Hide', settings_sidebar_width: 'Sidebar Width (px)', settings_width_range_hint: '(Range: 90-270, Step: 5)', settings_font_size: 'Base Font Size (px)', settings_font_size_range_hint: '(Range: 8-24, Step: 0.5)', settings_header_icon_size: 'Header Icon Size (px)', settings_header_icon_size_range_hint: '(Range: 8-32, Step: 0.5)', settings_vertical_spacing: 'Vertical Spacing', settings_vertical_spacing_range_hint: '(Multiplier Range: 0.05-1.5, Step: 0.05)', settings_theme: 'Theme:', settings_theme_system: 'Follow System', settings_theme_light: 'Light', settings_theme_dark: 'Dark', settings_theme_minimal_light: 'Minimal (Light)', settings_theme_minimal_dark: 'Minimal (Dark)', settings_hover_mode: 'Hover Mode', settings_idle_opacity: 'Idle Opacity:', settings_opacity_range_hint: '(Range: 0.1-1.0, Step: 0.05)', settings_country_display: 'Country/Region Display:', settings_country_display_icontext: 'Icon & Text', settings_country_display_text: 'Text Only', settings_country_display_icon: 'Icon Only', settings_visible_sections: 'Visible Sections:', settings_section_order: 'Adjust Sidebar Section Order (Drag & Drop):',
  286. settings_section_order_hint: '(Drag items to reorder. Only affects checked sections)',
  287. settings_no_orderable_sections: 'No visible sections to order.',
  288. settings_move_up_title: 'Move Up',
  289. settings_move_down_title: 'Move Down',
  290. settings_custom_intro: 'Manage filter options for each section:',
  291. settings_manage_sites_button: 'Manage Favorite Sites...', settings_manage_languages_button: 'Manage Language Options...', settings_manage_countries_button: 'Manage Country/Region Options...', settings_manage_time_ranges_button: 'Manage Time Ranges...', settings_manage_file_types_button: 'Manage File Types...', settings_save_button: 'Save Settings', settings_cancel_button: 'Cancel', settings_reset_all_button: 'Reset All',
  292. modal_label_enable_predefined: 'Enable Predefined {type}:',
  293. modal_label_my_custom: 'My Custom {type}:',
  294. modal_label_display_options_for: 'Display Options for {type} (Drag to Sort):',
  295. modal_button_add_new_option: 'Add New Option...',
  296. modal_button_add_predefined_option: 'Add Predefined...',
  297. modal_button_add_custom_option: 'Add Custom...',
  298. modal_placeholder_name: 'Name', modal_placeholder_domain: 'Domain (e.g., site.com OR example.net)', modal_placeholder_text: 'Text', modal_placeholder_value: 'Value (e.g., pdf OR docx)',
  299. modal_hint_domain: 'Format: domain (e.g., `wikipedia.org`) or TLD/SLD (`.edu`). Use `OR` (case-insensitive, space separated) for multiple.',
  300. modal_hint_language: 'Format: starts with `lang_`, e.g., `lang_ja`, `lang_zh-TW`. Use `|` for multiple.', modal_hint_country: 'Format: `country` + 2-letter uppercase code, e.g., `countryDE`', modal_hint_time: 'Format: `h`, `d`, `w`, `m`, `y`, optionally followed by numbers, e.g., `h1`, `d7`, `w`',
  301. modal_hint_filetype: 'Format: extension (e.g., `pdf`). Use `OR` (case-insensitive, space separated) for multiple (e.g., `docx OR xls`).',
  302. modal_tooltip_domain: 'Enter domain(s) or TLD/SLD(s). Use OR for multiple, e.g., site.com OR example.org',
  303. modal_tooltip_language: 'Format: lang_xx or lang_xx-XX, separate multiple with |', modal_tooltip_country: 'Format: countryXX (XX = uppercase country code)', modal_tooltip_time: 'Format: h, d, w, m, y, optionally followed by numbers',
  304. modal_tooltip_filetype: 'File extension(s). Use OR for multiple, e.g., pdf OR docx',
  305. modal_button_add_title: 'Add', modal_button_update_title: 'Update Item', modal_button_cancel_edit_title: 'Cancel Edit', modal_button_edit_title: 'Edit', modal_button_delete_title: 'Delete', modal_button_remove_from_list_title: 'Remove from list', modal_button_complete: 'Done', value_empty: '(empty)', date_range_from: 'From:', date_range_to: 'To:', sidebar_collapse_title: 'Collapse', sidebar_expand_title: 'Expand', sidebar_drag_title: 'Drag', sidebar_settings_title: 'Settings',
  306. alert_invalid_start_date: 'Invalid start date', alert_invalid_end_date: 'Invalid end date', alert_end_before_start: 'End date cannot be earlier than start date', alert_start_in_future: 'Start date cannot be in the future', alert_end_in_future: 'End date cannot be in the future', alert_select_date: 'Please select a date', alert_error_applying_date: 'Error applying date range', alert_error_applying_filter: 'Error applying filter {type}={value}', alert_error_applying_site_search: 'Error applying site search for {site}', alert_error_clearing_site_search: 'Error clearing site search', alert_error_resetting_filters: 'Error resetting filters', alert_error_toggling_verbatim: 'Error toggling Verbatim search', alert_error_toggling_personalization: 'Error toggling Personalization search', alert_enter_display_name: 'Please enter the display name for {type}.', alert_enter_value: 'Please enter the corresponding value for {type}.', alert_invalid_value_format: 'The value format for {type} is incorrect. {hint}', alert_duplicate_name: 'Custom item display name "{name}" already exists. Please use a different name.', alert_update_failed_invalid_index: 'Update failed: Invalid item index.', alert_edit_failed_missing_fields: 'Cannot edit: Input or button fields not found.',
  307. alert_no_more_predefined_to_add: 'No more predefined {type} options available to add.',
  308. alert_generic_error: 'An unexpected error occurred. Please check the console or try again. Context: {context}',
  309. confirm_delete_item: 'Are you sure you want to delete the custom item "{name}"?', confirm_remove_item_from_list: 'Are you sure you want to remove "{name}" from this display list?', confirm_reset_settings: 'Are you sure you want to reset all settings to their default values?', alert_settings_reset_success: 'Settings have been reset to default. You can continue editing or click "Save Settings" to confirm.', confirm_reset_all_menu: 'Are you sure you want to reset all settings to their default values?\nThis cannot be undone and requires a page refresh to take effect.', alert_reset_all_menu_success: 'All settings have been reset to defaults.\nPlease refresh the page to apply the changes.', alert_reset_all_menu_fail: 'Failed to reset settings via menu command! Please check the console.', alert_init_fail: '{scriptName} initialization failed. Some features may not work. Please check the console for technical details.\nTechnical Error: {error}', menu_open_settings: '⚙️ Open Settings', menu_reset_all_settings: '🚨 Reset All Settings',
  310. },
  311. };
  312. let effectiveTranslations = JSON.parse(JSON.stringify(builtInTranslations));
  313. let _currentLocale = 'en';
  314.  
  315. function _mergeExternalTranslations() {
  316. if (typeof window.GSCS_Namespace !== 'undefined' && typeof window.GSCS_Namespace.i18nPack === 'object' && typeof window.GSCS_Namespace.i18nPack.translations === 'object') {
  317. const externalTranslations = window.GSCS_Namespace.i18nPack.translations;
  318. for (const langCode in externalTranslations) {
  319. if (Object.prototype.hasOwnProperty.call(externalTranslations, langCode)) {
  320. if (!effectiveTranslations[langCode]) {
  321. effectiveTranslations[langCode] = {};
  322. }
  323. for (const key in externalTranslations[langCode]) {
  324. if (Object.prototype.hasOwnProperty.call(externalTranslations[langCode], key)) {
  325. effectiveTranslations[langCode][key] = externalTranslations[langCode][key];
  326. }
  327. }
  328. }
  329. }
  330. } else {
  331. console.warn(`${LOG_PREFIX} [i18n] External i18n pack (window.GSCS_Namespace.i18nPack) not found or invalid. Using built-in translations only.`);
  332. }
  333. const ensureKeys = (lang, defaults) => {
  334. if (!effectiveTranslations[lang]) effectiveTranslations[lang] = {};
  335. for (const key in defaults) {
  336. if (!effectiveTranslations[lang][key]) {
  337. effectiveTranslations[lang][key] = defaults[key];
  338. }
  339. }
  340. };
  341. ensureKeys('en', builtInTranslations.en);
  342. ensureKeys('zh-TW', builtInTranslations['zh-TW']);
  343. }
  344.  
  345. function _detectBrowserLocale() {
  346. let locale = 'en';
  347. try {
  348. if (navigator.languages && navigator.languages.length) {
  349. locale = navigator.languages[0];
  350. } else if (navigator.language) {
  351. locale = navigator.language;
  352. }
  353. } catch (e) {
  354. console.warn(`${LOG_PREFIX} [i18n] Error accessing navigator.language(s):`, e);
  355. }
  356. if (effectiveTranslations[locale]) return locale;
  357. if (locale.includes('-')) {
  358. const parts = locale.split('-');
  359. if (parts.length > 0 && effectiveTranslations[parts[0]]) return parts[0];
  360. if (parts.length > 2 && effectiveTranslations[`${parts[0]}-${parts[1]}`]) return `${parts[0]}-${parts[1]}`;
  361. }
  362. return 'en';
  363. }
  364.  
  365. function _updateActiveLocale(settingsToUse) {
  366. let newLocale = 'en';
  367. const langSettingSource = (settingsToUse && Object.keys(settingsToUse).length > 0 && typeof settingsToUse.interfaceLanguage === 'string')
  368. ? settingsToUse
  369. : defaultSettings;
  370. const userSelectedLang = langSettingSource.interfaceLanguage;
  371. if (userSelectedLang && userSelectedLang !== 'auto') {
  372. if (effectiveTranslations[userSelectedLang]) {
  373. newLocale = userSelectedLang;
  374. } else if (userSelectedLang.includes('-')) {
  375. const genericLang = userSelectedLang.split('-')[0];
  376. if (effectiveTranslations[genericLang]) {
  377. newLocale = genericLang;
  378. } else {
  379. newLocale = _detectBrowserLocale();
  380. }
  381. } else {
  382. newLocale = _detectBrowserLocale();
  383. }
  384. } else {
  385. newLocale = _detectBrowserLocale();
  386. }
  387. if (_currentLocale !== newLocale) {
  388. _currentLocale = newLocale;
  389. }
  390. if (userSelectedLang && userSelectedLang !== 'auto' && _currentLocale !== userSelectedLang && !userSelectedLang.includes(_currentLocale)) {
  391. console.warn(`${LOG_PREFIX} [i18n] User selected language "${userSelectedLang}" was not fully available or matched. Using best match: "${_currentLocale}".`);
  392. }
  393. }
  394.  
  395. _mergeExternalTranslations();
  396.  
  397. function getString(key, replacements = {}) {
  398. let str = `[ERR: ${key} @ ${_currentLocale}]`;
  399. let found = false;
  400. if (effectiveTranslations[_currentLocale] && typeof effectiveTranslations[_currentLocale][key] !== 'undefined') {
  401. str = effectiveTranslations[_currentLocale][key];
  402. found = true;
  403. }
  404. else if (_currentLocale.includes('-')) {
  405. const genericLang = _currentLocale.split('-')[0];
  406. if (effectiveTranslations[genericLang] && typeof effectiveTranslations[genericLang][key] !== 'undefined') {
  407. str = effectiveTranslations[genericLang][key];
  408. found = true;
  409. }
  410. }
  411. if (!found && _currentLocale !== 'en') {
  412. if (effectiveTranslations['en'] && typeof effectiveTranslations['en'][key] !== 'undefined') {
  413. str = effectiveTranslations['en'][key];
  414. found = true;
  415. }
  416. }
  417. if (!found) {
  418. if (!(effectiveTranslations['en'] && typeof effectiveTranslations['en'][key] !== 'undefined')) {
  419. console.error(`${LOG_PREFIX} [i18n] CRITICAL: Missing translation for key: "${key}" in BOTH locale: "${_currentLocale}" AND default locale "en".`);
  420. } else {
  421. str = effectiveTranslations['en'][key];
  422. found = true;
  423. }
  424. if(!found) str = `[ERR_NF: ${key}]`;
  425. }
  426. if (typeof str === 'string') {
  427. for (const placeholder in replacements) {
  428. if (Object.prototype.hasOwnProperty.call(replacements, placeholder)) {
  429. str = str.replace(new RegExp(`\\{${placeholder}\\}`, 'g'), replacements[placeholder]);
  430. }
  431. }
  432. } else {
  433. console.error(`${LOG_PREFIX} [i18n] CRITICAL: Translation for key "${key}" is not a string:`, str);
  434. return `[INVALID_TYPE_FOR_KEY: ${key}]`;
  435. }
  436. return str;
  437. }
  438.  
  439. return {
  440. getString: getString,
  441. getCurrentLocale: function() { return _currentLocale; },
  442. getTranslationsForLocale: function(locale = 'en') { return effectiveTranslations[locale] || effectiveTranslations['en']; },
  443. initializeBaseLocale: function() { _updateActiveLocale(defaultSettings); },
  444. updateActiveLocale: function(activeSettings) { _updateActiveLocale(activeSettings); },
  445. getAvailableLocales: function() {
  446. const locales = new Set(['auto', 'en']);
  447. Object.keys(effectiveTranslations).forEach(lang => {
  448. if (Object.keys(effectiveTranslations[lang]).length > 0) {
  449. locales.add(lang);
  450. }
  451. });
  452. return Array.from(locales).sort((a, b) => {
  453. if (a === 'auto') return -1;
  454. if (b === 'auto') return 1;
  455. if (a === 'en' && b !== 'auto') return -1;
  456. if (b === 'en' && a !== 'auto') return 1;
  457. let nameA = a, nameB = b;
  458. try { nameA = new Intl.DisplayNames([a],{type:'language'}).of(a); } catch(e){}
  459. try { nameB = new Intl.DisplayNames([b],{type:'language'}).of(b); } catch(e){}
  460. return nameA.localeCompare(nameB);
  461. });
  462. }
  463. };
  464. })();
  465. const _ = LocalizationService.getString;
  466.  
  467. const Utils = {
  468. debounce: function(func, wait) {
  469. let timeout;
  470. return function executedFunction(...args) {
  471. const context = this;
  472. const later = () => {
  473. timeout = null;
  474. func.apply(context, args);
  475. };
  476. clearTimeout(timeout);
  477. timeout = setTimeout(later, wait);
  478. };
  479. },
  480. mergeDeep: function(target, source) {
  481. if (!source) return target;
  482. target = target || {};
  483. for (const key in source) {
  484. if (Object.prototype.hasOwnProperty.call(source, key)) {
  485. const targetValue = target[key];
  486. const sourceValue = source[key];
  487. if (sourceValue && typeof sourceValue === 'object' && !Array.isArray(sourceValue)) {
  488. target[key] = Utils.mergeDeep(targetValue, sourceValue);
  489. } else if (typeof sourceValue !== 'undefined') {
  490. target[key] = sourceValue;
  491. }
  492. }
  493. }
  494. return target;
  495. },
  496. clamp: function(num, min, max) {
  497. return Math.min(Math.max(num, min), max);
  498. },
  499. parseIconAndText: function(fullText) {
  500. const match = fullText.match(/^(\P{L}\P{N}\s*)+/u);
  501. let icon = '';
  502. let text = fullText;
  503. if (match && match[0].trim() !== '') {
  504. icon = match[0].trim();
  505. text = fullText.substring(icon.length).trim();
  506. }
  507. return { icon, text };
  508. },
  509. getCurrentURL: function() {
  510. try {
  511. return new URL(window.location.href);
  512. } catch (e) {
  513. console.error(`${LOG_PREFIX} Error creating URL object:`, e);
  514. return null;
  515. }
  516. },
  517. parseCombinedValue: function(valueString) {
  518. if (typeof valueString !== 'string' || !valueString.trim()) {
  519. return [];
  520. }
  521. return valueString.split(/\s+OR\s+/i).map(s => s.trim()).filter(s => s.length > 0);
  522. }
  523. };
  524. const NotificationManager = (function() {
  525. let container = null;
  526. function init() {
  527. if (document.getElementById(IDS.NOTIFICATION_CONTAINER)) {
  528. container = document.getElementById(IDS.NOTIFICATION_CONTAINER);
  529. return;
  530. }
  531. container = document.createElement('div');
  532. container.id = IDS.NOTIFICATION_CONTAINER;
  533. if (document.body) {
  534. document.body.appendChild(container);
  535. } else {
  536. console.error(LOG_PREFIX + " NotificationManager.init(): document.body is not available!");
  537. container = null;
  538. }
  539. }
  540. function show(messageKey, messageArgs = {}, type = 'info', duration = 3000) {
  541. if (!container) {
  542. const alertMsg = (typeof _ === 'function' && _(messageKey, messageArgs) && !(_(messageKey, messageArgs).startsWith('[ERR:')))
  543. ? _(messageKey, messageArgs)
  544. : `${messageKey} (args: ${JSON.stringify(messageArgs)})`;
  545. alert(alertMsg);
  546. return null;
  547. }
  548. const notificationElement = document.createElement('div');
  549. notificationElement.classList.add(CSS.NOTIFICATION);
  550. const typeClass = CSS[`NTF_${type.toUpperCase()}`] || CSS.NTF_INFO;
  551. notificationElement.classList.add(typeClass);
  552. notificationElement.textContent = _(messageKey, messageArgs);
  553. if (duration <= 0) {
  554. const closeButton = document.createElement('span');
  555. closeButton.innerHTML = '×';
  556. closeButton.style.cursor = 'pointer';
  557. closeButton.style.marginLeft = '10px';
  558. closeButton.style.float = 'right';
  559. closeButton.onclick = () => notificationElement.remove();
  560. notificationElement.appendChild(closeButton);
  561. }
  562. container.appendChild(notificationElement);
  563. if (duration > 0) {
  564. setTimeout(() => {
  565. notificationElement.style.opacity = '0';
  566. setTimeout(() => notificationElement.remove(), 500);
  567. }, duration);
  568. }
  569. return notificationElement;
  570. }
  571. return { init: init, show: show };
  572. })();
  573.  
  574. function createGenericListItem(index, item, listId, mapping) {
  575. const listItem = document.createElement('li');
  576. listItem.dataset[DATA_ATTR.INDEX] = index;
  577. listItem.dataset[DATA_ATTR.LIST_ID] = listId;
  578. listItem.dataset[DATA_ATTR.ITEM_ID] = item.id || item.value || item.url;
  579. listItem.draggable = true;
  580. const dragIconSpan = document.createElement('span');
  581. dragIconSpan.classList.add(CSS.DRAG_ICON);
  582. dragIconSpan.innerHTML = SVG_ICONS.dragGrip;
  583. listItem.appendChild(dragIconSpan);
  584. const textSpan = document.createElement('span');
  585. let displayText = item.text;
  586. let paramName = '';
  587. if (item.type === 'predefined' && item.originalKey) {
  588. displayText = _(item.originalKey);
  589. if (listId === IDS.COUNTRIES_LIST) {
  590. const parsed = Utils.parseIconAndText(displayText);
  591. displayText = `${parsed.icon} ${parsed.text}`.trim();
  592. }
  593. }
  594. if (mapping) {
  595. if (listId === IDS.LANG_LIST) paramName = ALL_SECTION_DEFINITIONS.find(s=>s.id === 'sidebar-section-language').param;
  596. else if (listId === IDS.COUNTRIES_LIST) paramName = ALL_SECTION_DEFINITIONS.find(s=>s.id === 'sidebar-section-country').param;
  597. else if (listId === IDS.SITES_LIST) paramName = 'site';
  598. else if (listId === IDS.TIME_LIST) paramName = ALL_SECTION_DEFINITIONS.find(s=>s.id === 'sidebar-section-time').param;
  599. else if (listId === IDS.FT_LIST) {
  600. const ftSection = ALL_SECTION_DEFINITIONS.find(s => s.id === 'sidebar-section-filetype');
  601. if (ftSection) paramName = ftSection.param;
  602. }
  603. }
  604. const valueForDisplay = item.value || item.url || _('value_empty');
  605. textSpan.textContent = `${displayText} (${paramName}=${valueForDisplay})`;
  606. textSpan.title = textSpan.textContent;
  607. listItem.appendChild(textSpan);
  608. const controlsSpan = document.createElement('span');
  609. controlsSpan.classList.add(CSS.ITEM_CONTROLS);
  610. if (item.type === 'custom' || listId === IDS.SITES_LIST || listId === IDS.TIME_LIST || listId === IDS.FT_LIST) {
  611. controlsSpan.innerHTML =
  612. `<button class="${CSS.EDIT_CUSTOM_ITEM}" title="${_('modal_button_edit_title')}">${SVG_ICONS.edit}</button> ` +
  613. `<button class="${CSS.DELETE_CUSTOM_ITEM}" title="${_('modal_button_delete_title')}">${SVG_ICONS.delete}</button>`;
  614. listItem.dataset[DATA_ATTR.ITEM_TYPE] = 'custom';
  615. } else if (item.type === 'predefined') {
  616. controlsSpan.innerHTML =
  617. `<button class="${CSS.REMOVE_FROM_LIST_BTN}" title="${_('modal_button_remove_from_list_title')}">${SVG_ICONS.removeFromList}</button>`;
  618. listItem.dataset[DATA_ATTR.ITEM_TYPE] = 'predefined';
  619. }
  620. listItem.appendChild(controlsSpan);
  621. return listItem;
  622. }
  623.  
  624. function populateListInModal(listId, items, contextElement = document) {
  625. const listElement = contextElement.querySelector(`#${listId}`);
  626. if (!listElement) {
  627. console.warn(`${LOG_PREFIX} List element not found: #${listId} in context`, contextElement);
  628. return;
  629. }
  630. listElement.innerHTML = '';
  631. const fragment = document.createDocumentFragment();
  632. const mapping = getListMapping(listId);
  633. if (!Array.isArray(items)) items = [];
  634. items.forEach((item, index) => {
  635. fragment.appendChild(createGenericListItem(index, item, listId, mapping));
  636. });
  637. listElement.appendChild(fragment);
  638. }
  639.  
  640. function getListMapping(listId) {
  641. const listMappings = {
  642. [IDS.SITES_LIST]: { itemsArrayKey: 'favoriteSites', customItemsMasterKey: null, valueKey: 'url', populateFn: populateListInModal, textInput: `#${IDS.NEW_SITE_NAME}`, valueInput: `#${IDS.NEW_SITE_URL}`, addButton: `#${IDS.ADD_SITE_BTN}`, nameKey: 'section_site_search', isSortableMixed: false, predefinedSourceKey: null },
  643. [IDS.LANG_LIST]: { itemsArrayKey: 'displayLanguages', customItemsMasterKey: 'customLanguages', valueKey: 'value', populateFn: populateListInModal, textInput: `#${IDS.NEW_LANG_TEXT}`, valueInput: `#${IDS.NEW_LANG_VALUE}`, addButton: `#${IDS.ADD_LANG_BTN}`, nameKey: 'section_language', isSortableMixed: true, predefinedSourceKey: 'language' },
  644. [IDS.COUNTRIES_LIST]: { itemsArrayKey: 'displayCountries', customItemsMasterKey: 'customCountries', valueKey: 'value', populateFn: populateListInModal, textInput: `#${IDS.NEW_COUNTRY_TEXT}`, valueInput: `#${IDS.NEW_COUNTRY_VALUE}`, addButton: `#${IDS.ADD_COUNTRY_BTN}`, nameKey: 'section_country', isSortableMixed: true, predefinedSourceKey: 'country' },
  645. [IDS.TIME_LIST]: { itemsArrayKey: 'customTimeRanges', customItemsMasterKey: null, valueKey: 'value', populateFn: populateListInModal, textInput: `#${IDS.NEW_TIME_TEXT}`, valueInput: `#${IDS.NEW_TIME_VALUE}`, addButton: `#${IDS.ADD_TIME_BTN}`, nameKey: 'section_time', isSortableMixed: false, predefinedSourceKey: 'time' },
  646. [IDS.FT_LIST]: { itemsArrayKey: 'customFiletypes', customItemsMasterKey: null, valueKey: 'value', populateFn: populateListInModal, textInput: `#${IDS.NEW_FT_TEXT}`, valueInput: `#${IDS.NEW_FT_VALUE}`, addButton: `#${IDS.ADD_FT_BTN}`, nameKey: 'section_filetype', isSortableMixed: false, predefinedSourceKey: 'filetype' },
  647. };
  648. return listMappings[listId] || null;
  649. }
  650.  
  651. function validateCustomInput(inputElement) {
  652. if (!inputElement) return false;
  653. const value = inputElement.value.trim();
  654. const id = inputElement.id;
  655. let isValid = false;
  656. let isEmpty = value === '';
  657.  
  658. if (id === IDS.NEW_SITE_NAME || id === IDS.NEW_LANG_TEXT || id === IDS.NEW_TIME_TEXT || id === IDS.NEW_FT_TEXT || id === IDS.NEW_COUNTRY_TEXT) {
  659. isValid = !isEmpty;
  660. } else if (id === IDS.NEW_SITE_URL) {
  661. const singleDomainRegex = /^(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,})$|(?:^\.(?:[a-zA-Z0-9-]{1,63}\.)*[a-zA-Z]{2,63}$)/;
  662. const parts = Utils.parseCombinedValue(value);
  663. if (isEmpty) isValid = true; // Empty is fine, might not be required
  664. else if (parts.length > 0) isValid = parts.every(part => singleDomainRegex.test(part));
  665. else isValid = false; // e.g. "OR" alone, or just spaces
  666. } else if (id === IDS.NEW_LANG_VALUE) {
  667. isValid = isEmpty || /^lang_[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,4})?(?:\|lang_[a-zA-Z]{2,3}(?:-[a-zA-Z0-9]{2,4})?)*$/.test(value);
  668. } else if (id === IDS.NEW_TIME_VALUE) {
  669. isValid = isEmpty || /^[hdwmy]\d*$/.test(value);
  670. } else if (id === IDS.NEW_FT_VALUE) {
  671. const singleFiletypeRegex = /^[a-zA-Z0-9]+$/;
  672. const parts = Utils.parseCombinedValue(value);
  673. if (isEmpty) isValid = true;
  674. else if (parts.length > 0) isValid = parts.every(part => singleFiletypeRegex.test(part));
  675. else isValid = false;
  676. } else if (id === IDS.NEW_COUNTRY_VALUE) {
  677. isValid = isEmpty || /^country[A-Z]{2}$/.test(value);
  678. }
  679.  
  680. inputElement.classList.remove('input-valid', 'input-invalid', CSS.INPUT_HAS_ERROR);
  681. _clearInputError(inputElement);
  682. if (!isEmpty) { // Only add validation classes if not empty
  683. inputElement.classList.add(isValid ? 'input-valid' : 'input-invalid');
  684. if (!isValid) inputElement.classList.add(CSS.INPUT_HAS_ERROR);
  685. }
  686. return isValid || isEmpty; // Return true if format is valid OR if it's empty (emptiness check is separate)
  687. }
  688.  
  689. function _getInputErrorElement(inputElement) {
  690. if (!inputElement || !inputElement.id) return null;
  691. let errorEl = inputElement.nextElementSibling;
  692. if (errorEl && errorEl.classList.contains(CSS.INPUT_ERROR_MESSAGE) && errorEl.id === `${inputElement.id}-error-msg`) {
  693. return errorEl;
  694. }
  695. const parentDiv = inputElement.parentElement;
  696. if (parentDiv) {
  697. return parentDiv.querySelector(`#${inputElement.id}-error-msg`);
  698. }
  699. return null;
  700. }
  701. function _showInputError(inputElement, messageKey, messageArgs = {}) {
  702. if (!inputElement) return;
  703. const errorElement = _getInputErrorElement(inputElement);
  704. if (errorElement) {
  705. errorElement.textContent = _(messageKey, messageArgs);
  706. errorElement.classList.add(CSS.ERROR_VISIBLE);
  707. }
  708. inputElement.classList.add(CSS.INPUT_HAS_ERROR);
  709. inputElement.classList.remove('input-valid');
  710. }
  711. function _clearInputError(inputElement) {
  712. if (!inputElement) return;
  713. const errorElement = _getInputErrorElement(inputElement);
  714. if (errorElement) {
  715. errorElement.textContent = '';
  716. errorElement.classList.remove(CSS.ERROR_VISIBLE);
  717. }
  718. inputElement.classList.remove(CSS.INPUT_HAS_ERROR, 'input-invalid');
  719. }
  720. function _clearAllInputErrorsInGroup(inputGroupElement) {
  721. if (!inputGroupElement) return;
  722. inputGroupElement.querySelectorAll(`input[type="text"]`).forEach(input => {
  723. _clearInputError(input);
  724. input.classList.remove('input-valid', 'input-invalid');
  725. });
  726. }
  727. function _showGlobalMessage(messageKey, messageArgs = {}, type = 'info', duration = 3000, targetElementId = IDS.SETTINGS_MESSAGE_BAR) {
  728. const messageBar = document.getElementById(targetElementId);
  729. if (!messageBar) {
  730. if (targetElementId !== IDS.SETTINGS_MESSAGE_BAR && NotificationManager && typeof NotificationManager.show === 'function') {
  731. NotificationManager.show(messageKey, messageArgs, type, duration > 0 ? duration : 5000);
  732. } else {
  733. const alertMsg = (typeof _ === 'function' && _(messageKey, messageArgs) && !(_(messageKey, messageArgs).startsWith('[ERR:')))
  734. ? _(messageKey, messageArgs)
  735. : `${messageKey} (args: ${JSON.stringify(messageArgs)})`;
  736. alert(alertMsg);
  737. }
  738. return;
  739. }
  740. if (globalMessageTimeout && targetElementId === IDS.SETTINGS_MESSAGE_BAR) {
  741. clearTimeout(globalMessageTimeout);
  742. globalMessageTimeout = null;
  743. }
  744. messageBar.textContent = _(messageKey, messageArgs);
  745. messageBar.className = `${CSS.MESSAGE_BAR}`;
  746. messageBar.classList.add(CSS[`MSG_${type.toUpperCase()}`] || CSS.MSG_INFO);
  747. messageBar.style.display = 'block';
  748. if (duration > 0 && targetElementId === IDS.SETTINGS_MESSAGE_BAR) {
  749. globalMessageTimeout = setTimeout(() => {
  750. messageBar.style.display = 'none';
  751. messageBar.textContent = '';
  752. messageBar.className = CSS.MESSAGE_BAR;
  753. }, duration);
  754. }
  755. }
  756. function _validateAndPrepareCustomItemData(textInput, valueInput, itemTypeName, listId) {
  757. if (!textInput || !valueInput) {
  758. _showGlobalMessage('alert_edit_failed_missing_fields', {}, 'error', 0);
  759. return { isValid: false };
  760. }
  761. _clearInputError(textInput);
  762. _clearInputError(valueInput);
  763. const text = textInput.value.trim();
  764. const value = valueInput.value.trim();
  765. let hint = '';
  766. if (text === '') {
  767. _showInputError(textInput, 'alert_enter_display_name', { type: itemTypeName });
  768. textInput.focus();
  769. return { isValid: false, errorField: textInput };
  770. } else {
  771. textInput.classList.remove(CSS.INPUT_HAS_ERROR);
  772. // validateCustomInput(textInput); // No need to re-validate text if non-empty for basic types
  773. }
  774. if (value === '') {
  775. _showInputError(valueInput, 'alert_enter_value', { type: itemTypeName });
  776. valueInput.focus();
  777. return { isValid: false, errorField: valueInput };
  778. } else {
  779. const isValueFormatValid = validateCustomInput(valueInput); // This also handles visual feedback
  780. if (!isValueFormatValid) { // validateCustomInput already showed error if !isValid and not empty
  781. if (valueInput.classList.contains('input-invalid')) { // Error was shown by validateCustomInput
  782. valueInput.focus();
  783. return { isValid: false, errorField: valueInput };
  784. }
  785. // If not marked invalid by validateCustomInput but still failed (e.g. more complex logic not in regex)
  786. if (listId === IDS.COUNTRIES_LIST) hint = _('modal_tooltip_country');
  787. else if (listId === IDS.LANG_LIST) hint = _('modal_tooltip_language');
  788. else if (listId === IDS.TIME_LIST) hint = _('modal_tooltip_time');
  789. else if (listId === IDS.FT_LIST) hint = _('modal_tooltip_filetype');
  790. else if (listId === IDS.SITES_LIST) hint = _('modal_tooltip_domain');
  791. _showInputError(valueInput, 'alert_invalid_value_format', { type: itemTypeName, hint: hint });
  792. valueInput.focus();
  793. return { isValid: false, errorField: valueInput };
  794. }
  795. }
  796. return { isValid: true, text: text, value: value };
  797. }
  798. function _isDuplicateCustomItem(text, itemsToCheck, listId, editingIndex, editingItemInfoRef) {
  799. const lowerText = text.toLowerCase();
  800. return itemsToCheck.some((item, idx) => {
  801. const itemIsCustom = item.type === 'custom' || listId === IDS.SITES_LIST || listId === IDS.TIME_LIST || listId === IDS.FT_LIST;
  802. if (!itemIsCustom) return false;
  803. if (editingItemInfoRef && editingItemInfoRef.listId === listId && editingIndex === idx) {
  804. if (editingItemInfoRef.originalText?.toLowerCase() === lowerText) {
  805. return false;
  806. }
  807. }
  808. return item.text.toLowerCase() === lowerText;
  809. });
  810. }
  811. function applyThemeToElement(element, themeSetting) {
  812. if (!element) return;
  813. element.classList.remove( CSS.LIGHT_THEME, CSS.DARK_THEME, 'minimal-theme', 'minimal-light', 'minimal-dark' );
  814. let effectiveTheme = themeSetting;
  815. const isSettingsOrModal = element.id === IDS.SETTINGS_WINDOW || element.id === IDS.SETTINGS_OVERLAY || element.classList.contains('settings-modal-content') || element.classList.contains('settings-modal-overlay');
  816. if (isSettingsOrModal) {
  817. if (themeSetting === 'minimal-light') effectiveTheme = 'light';
  818. else if (themeSetting === 'minimal-dark') effectiveTheme = 'dark';
  819. }
  820. switch (effectiveTheme) {
  821. case 'dark': element.classList.add(CSS.DARK_THEME); break;
  822. case 'minimal-light': element.classList.add('minimal-theme', 'minimal-light'); break;
  823. case 'minimal-dark': element.classList.add('minimal-theme', 'minimal-dark'); break;
  824. case 'system': const systemIsDark = systemThemeMediaQuery && systemThemeMediaQuery.matches; element.classList.add(systemIsDark ? CSS.DARK_THEME : CSS.LIGHT_THEME); break;
  825. case 'light': default: element.classList.add(CSS.LIGHT_THEME); break;
  826. }
  827. }
  828.  
  829. const PredefinedOptionChooser = (function() {
  830. let _chooserContainer = null;
  831. let _currentListId = null;
  832. let _currentPredefinedSourceKey = null;
  833. let _currentDisplayItemsArrayRef = null;
  834. let _currentModalContentContext = null;
  835. let _onAddCallback = null;
  836.  
  837. function _buildChooserHTML(listId, predefinedSourceKey, displayItemsArrayRef) {
  838. const allPredefinedSystemOptions = PREDEFINED_OPTIONS[predefinedSourceKey] || [];
  839. const currentDisplayedValues = new Set(
  840. displayItemsArrayRef.filter(item => item.type === 'predefined').map(item => item.value)
  841. );
  842.  
  843. const availablePredefinedToAdd = allPredefinedSystemOptions.filter(
  844. opt => !currentDisplayedValues.has(opt.value)
  845. );
  846.  
  847. if (availablePredefinedToAdd.length === 0) {
  848. const itemTypeName = getListMapping(listId)?.nameKey ? _(getListMapping(listId).nameKey) : predefinedSourceKey;
  849. _showGlobalMessage('alert_no_more_predefined_to_add', { type: itemTypeName }, 'info', 3000, IDS.SETTINGS_MESSAGE_BAR);
  850. return null;
  851. }
  852.  
  853. let listHTML = `<ul id="${IDS.MODAL_PREDEFINED_CHOOSER_LIST}">`;
  854. availablePredefinedToAdd.forEach(opt => {
  855. let displayText = _(opt.textKey);
  856. if (listId === IDS.COUNTRIES_LIST) {
  857. const parsed = Utils.parseIconAndText(displayText);
  858. displayText = `${parsed.icon} ${parsed.text}`.trim();
  859. }
  860. const sanitizedValueForId = opt.value.replace(/[^a-zA-Z0-9-_]/g, '');
  861. listHTML += `<li class="${CSS.MODAL_PREDEFINED_CHOOSER_ITEM}"><input type="checkbox" value="${opt.value}" id="chooser-${sanitizedValueForId}"><label for="chooser-${sanitizedValueForId}">${displayText}</label></li>`;
  862. });
  863. listHTML += `</ul>`;
  864.  
  865. const buttonsHTML = `
  866. <div class="chooser-buttons" style="text-align: right; margin-top: 10px;">
  867. <button id="${IDS.MODAL_PREDEFINED_CHOOSER_ADD_BTN}" class="${CSS.TOOL_BUTTON}" style="margin-right: 5px;">${_('modal_button_add_title')}</button>
  868. <button id="${IDS.MODAL_PREDEFINED_CHOOSER_CANCEL_BTN}" class="${CSS.TOOL_BUTTON}">${_('settings_cancel_button')}</button>
  869. </div>`;
  870. return listHTML + buttonsHTML;
  871. }
  872.  
  873. function _handleAdd() {
  874. if (!_chooserContainer) return;
  875. const selectedValues = [];
  876. _chooserContainer.querySelectorAll(`#${IDS.MODAL_PREDEFINED_CHOOSER_LIST} input[type="checkbox"]:checked`).forEach(cb => {
  877. selectedValues.push(cb.value);
  878. });
  879.  
  880. if (selectedValues.length > 0 && typeof _onAddCallback === 'function') {
  881. _onAddCallback(selectedValues, _currentPredefinedSourceKey, _currentDisplayItemsArrayRef, _currentListId, _currentModalContentContext);
  882. }
  883. hide();
  884. }
  885.  
  886. function show(manageType, listId, predefinedSourceKey, displayItemsArrayRef, contextElement, onAddCb) {
  887. hide();
  888.  
  889. _currentListId = listId;
  890. _currentPredefinedSourceKey = predefinedSourceKey;
  891. _currentDisplayItemsArrayRef = displayItemsArrayRef;
  892. _currentModalContentContext = contextElement;
  893. _onAddCallback = onAddCb;
  894.  
  895. const chooserHTML = _buildChooserHTML(listId, predefinedSourceKey, displayItemsArrayRef);
  896. if (!chooserHTML) return;
  897.  
  898. _chooserContainer = document.createElement('div');
  899. _chooserContainer.id = IDS.MODAL_PREDEFINED_CHOOSER_CONTAINER;
  900. _chooserContainer.classList.add(CSS.MODAL_PREDEFINED_CHOOSER_CLASS);
  901. _chooserContainer.innerHTML = chooserHTML;
  902.  
  903. const addNewBtn = contextElement.querySelector(`#${IDS.MODAL_ADD_NEW_OPTION_BTN}`);
  904. if (addNewBtn && addNewBtn.parentNode) {
  905. addNewBtn.insertAdjacentElement('afterend', _chooserContainer);
  906. } else {
  907. const mainListElement = contextElement.querySelector(`#${listId}`);
  908. mainListElement?.insertAdjacentElement('beforebegin', _chooserContainer);
  909. }
  910. _chooserContainer.style.display = 'block';
  911.  
  912. _chooserContainer.querySelector(`#${IDS.MODAL_PREDEFINED_CHOOSER_ADD_BTN}`).addEventListener('click', _handleAdd);
  913. _chooserContainer.querySelector(`#${IDS.MODAL_PREDEFINED_CHOOSER_CANCEL_BTN}`).addEventListener('click', hide);
  914. }
  915.  
  916. function hide() {
  917. if (_chooserContainer) {
  918. _chooserContainer.remove();
  919. _chooserContainer = null;
  920. }
  921. _currentListId = null;
  922. _currentPredefinedSourceKey = null;
  923. _currentDisplayItemsArrayRef = null;
  924. _currentModalContentContext = null;
  925. _onAddCallback = null;
  926. }
  927.  
  928. return {
  929. show: show,
  930. hide: hide,
  931. isOpen: function() { return !!_chooserContainer; }
  932. };
  933. })();
  934.  
  935.  
  936. const ModalManager = (function() {
  937. let _currentModal = null;
  938. let _currentModalContent = null;
  939. let _editingItemInfo = null;
  940. let _draggedListItem = null;
  941.  
  942. const modalConfigsData = {
  943. 'site': { modalTitleKey: 'manageSitesTitle', listId: IDS.SITES_LIST, itemsArrayKey: 'favoriteSites', customItemsMasterKey: null, textPKey: 'modal_placeholder_name', valPKey: 'modal_placeholder_domain', hintKey: 'modal_hint_domain', fmtKey: 'modal_tooltip_domain', isSortableMixed: false, predefinedSourceKey: null, hasPredefinedToggles: false, manageType: 'site' },
  944. 'language': { modalTitleKey: 'manageLanguagesTitle', listId: IDS.LANG_LIST, itemsArrayKey: 'displayLanguages', customItemsMasterKey: 'customLanguages', textPKey: 'modal_placeholder_text', valPKey: 'modal_placeholder_value', hintKey: 'modal_hint_language', fmtKey: 'modal_tooltip_language', predefinedSourceKey: 'language', isSortableMixed: true, hasPredefinedToggles: false, manageType: 'language' },
  945. 'country': { modalTitleKey: 'manageCountriesTitle', listId: IDS.COUNTRIES_LIST, itemsArrayKey: 'displayCountries', customItemsMasterKey: 'customCountries', textPKey: 'modal_placeholder_text', valPKey: 'modal_placeholder_value', hintKey: 'modal_hint_country', fmtKey: 'modal_tooltip_country', predefinedSourceKey: 'country', isSortableMixed: true, hasPredefinedToggles: false, manageType: 'country' },
  946. 'time': { modalTitleKey: 'manageTimeRangesTitle',listId: IDS.TIME_LIST, itemsArrayKey: 'customTimeRanges', customItemsMasterKey: null, textPKey: 'modal_placeholder_text', valPKey: 'modal_placeholder_value', hintKey: 'modal_hint_time', fmtKey: 'modal_tooltip_time', predefinedSourceKey: 'time', isSortableMixed: false, hasPredefinedToggles: true, manageType: 'time' },
  947. 'filetype': { modalTitleKey: 'manageFileTypesTitle', listId: IDS.FT_LIST, itemsArrayKey: 'customFiletypes', customItemsMasterKey: null, textPKey: 'modal_placeholder_text', valPKey: 'modal_placeholder_value', hintKey: 'modal_hint_filetype', fmtKey: 'modal_tooltip_filetype', predefinedSourceKey: 'filetype', isSortableMixed: false, hasPredefinedToggles: true, manageType: 'filetype' },
  948. };
  949.  
  950. function _createPredefinedOptionsSectionHTML(currentOptionType, typeNameKey, predefinedOptionsSource, enabledPredefinedValues) {
  951. const label = _(typeNameKey);
  952. const optionsHTML = (predefinedOptionsSource[currentOptionType] || []).map(option => {
  953. const checkboxId = `predefined-${currentOptionType}-${option.value.replace(/[^a-zA-Z0-9-_]/g, '')}`;
  954. const translatedOptionText = _(option.textKey);
  955. const isChecked = enabledPredefinedValues.has(option.value);
  956. return `<li><input type="checkbox" id="${checkboxId}" value="${option.value}" data-option-type="${currentOptionType}" ${isChecked ? 'checked' : ''}><label for="${checkboxId}">${translatedOptionText}</label></li>`;
  957. }).join('');
  958.  
  959. return `<label style="font-weight: bold;">${_('modal_label_enable_predefined', { type: label })}</label><ul class="predefined-options-list" data-option-type="${currentOptionType}">${optionsHTML}</ul>`;
  960. }
  961.  
  962. function _createModalListAndInputHTML(currentListId, textPlaceholderKey, valuePlaceholderKey, hintKey, formatTooltipKey, itemTypeName, isSortableMixed = false) {
  963. const mapping = getListMapping(currentListId);
  964. const typeNameToDisplay = itemTypeName || (mapping ? _(mapping.nameKey) : 'Items');
  965.  
  966. let headerHTML = '';
  967. let addNewOptionButtonHTML = '';
  968.  
  969. if (isSortableMixed) {
  970. headerHTML = `<label style="font-weight: bold; margin-top: 0.5em; display: block;">${_('modal_label_display_options_for', {type: typeNameToDisplay})}</label>`;
  971. addNewOptionButtonHTML = `<div style="margin-bottom: 0.5em;"><button id="${IDS.MODAL_ADD_NEW_OPTION_BTN}" class="${CSS.MODAL_ADD_NEW_OPTION_BTN_CLASS} ${CSS.TOOL_BUTTON}">${_('modal_button_add_new_option')}</button></div>`;
  972. } else {
  973. headerHTML = `<label style="font-weight: bold; margin-top: 0.5em; display: block;">${_('modal_label_my_custom', { type: typeNameToDisplay })}</label>`;
  974. }
  975.  
  976. const textInputId = mapping ? mapping.textInput.substring(1) : `new-custom-${currentListId}-text`;
  977. const valueInputId = mapping ? mapping.valueInput.substring(1) : `new-custom-${currentListId}-value`;
  978. const addButtonId = mapping ? mapping.addButton.substring(1) : `add-custom-${currentListId}-button`;
  979.  
  980. const inputGroupHTML = `
  981. <div class="${CSS.CUSTOM_LIST_INPUT_GROUP}">
  982. <div><input type="text" id="${textInputId}" placeholder="${_(textPlaceholderKey)}"><span id="${textInputId}-error-msg" class="${CSS.INPUT_ERROR_MESSAGE}"></span></div>
  983. <div><input type="text" id="${valueInputId}" placeholder="${_(valuePlaceholderKey)}" title="${_(formatTooltipKey)}"><span id="${valueInputId}-error-msg" class="${CSS.INPUT_ERROR_MESSAGE}"></span></div>
  984. <button id="${addButtonId}" class="${CSS.ADD_CUSTOM_BUTTON} custom-list-action-button" data-list-id="${currentListId}" title="${_('modal_button_add_title')}">${SVG_ICONS.add}</button>
  985. <button class="cancel-edit-button" style="display: none;" title="${_('modal_button_cancel_edit_title')}">${SVG_ICONS.close}</button>
  986. </div>`;
  987. const hintHTML = `<span class="setting-value-hint">${_(hintKey)}</span>`;
  988.  
  989. return `${addNewOptionButtonHTML}${headerHTML}<ul id="${currentListId}" class="${CSS.CUSTOM_LIST}"></ul>${inputGroupHTML}${hintHTML}`;
  990. }
  991.  
  992. function _resetEditStateInternal(contextElement = _currentModalContent) {
  993. if (_editingItemInfo) {
  994. const mapping = getListMapping(_editingItemInfo.listId);
  995. if (_editingItemInfo.addButton) {
  996. _editingItemInfo.addButton.innerHTML = SVG_ICONS.add;
  997. _editingItemInfo.addButton.title = _('modal_button_add_title');
  998. _editingItemInfo.addButton.classList.remove('update-mode');
  999. }
  1000. if (_editingItemInfo.cancelButton) {
  1001. _editingItemInfo.cancelButton.style.display = 'none';
  1002. }
  1003. if (mapping && contextElement) {
  1004. const textInput = contextElement.querySelector(mapping.textInput);
  1005. const valueInput = contextElement.querySelector(mapping.valueInput);
  1006. const inputGroup = textInput?.closest(`.${CSS.CUSTOM_LIST_INPUT_GROUP}`);
  1007. if(inputGroup) _clearAllInputErrorsInGroup(inputGroup);
  1008.  
  1009. if (textInput) { textInput.value = ''; textInput.classList.remove('input-valid', 'input-invalid', CSS.INPUT_HAS_ERROR); _clearInputError(textInput); }
  1010. if (valueInput) { valueInput.value = ''; valueInput.classList.remove('input-valid', 'input-invalid', CSS.INPUT_HAS_ERROR); _clearInputError(valueInput); }
  1011. }
  1012. }
  1013. _editingItemInfo = null;
  1014. }
  1015.  
  1016. function _prepareEditItemActionInternal(item, index, listId, mapping, contextElement) {
  1017. const textInput = contextElement.querySelector(mapping.textInput);
  1018. const valueInput = contextElement.querySelector(mapping.valueInput);
  1019. const addButton = contextElement.querySelector(mapping.addButton);
  1020. const cancelButton = addButton?.parentElement?.querySelector('.cancel-edit-button');
  1021.  
  1022. if (textInput && valueInput && addButton && cancelButton) {
  1023. if (_editingItemInfo && (_editingItemInfo.listId !== listId || _editingItemInfo.index !== index)) {
  1024. _resetEditStateInternal(contextElement);
  1025. }
  1026.  
  1027. textInput.value = item.text;
  1028. valueInput.value = item[mapping.valueKey] || item.value;
  1029.  
  1030. _editingItemInfo = {
  1031. listId,
  1032. index,
  1033. originalValue: item[mapping.valueKey] || item.value,
  1034. originalText: item.text,
  1035. addButton,
  1036. cancelButton,
  1037. arrayKey: mapping.itemsArrayKey || mapping.displayArrayKey
  1038. };
  1039.  
  1040. addButton.innerHTML = SVG_ICONS.update;
  1041. addButton.title = _('modal_button_update_title');
  1042. addButton.classList.add('update-mode');
  1043. cancelButton.style.display = 'inline-block';
  1044.  
  1045. validateCustomInput(valueInput);
  1046. validateCustomInput(textInput);
  1047. textInput.focus();
  1048. } else {
  1049. const errorSourceInput = textInput || valueInput || addButton?.closest(`.${CSS.CUSTOM_LIST_INPUT_GROUP}`)?.querySelector('input[type="text"]');
  1050. if (errorSourceInput) _showInputError(errorSourceInput, 'alert_edit_failed_missing_fields');
  1051. else _showGlobalMessage('alert_edit_failed_missing_fields', {}, 'error', 0, _currentModalContent?.querySelector(`#${IDS.SETTINGS_MESSAGE_BAR}`) ? IDS.SETTINGS_MESSAGE_BAR : null);
  1052.  
  1053. }
  1054. }
  1055.  
  1056. function _handleCustomListActionsInternal(event, contextElement, itemsArrayRef) {
  1057. const button = event.target.closest(`button.${CSS.EDIT_CUSTOM_ITEM}, button.${CSS.DELETE_CUSTOM_ITEM}, button.${CSS.REMOVE_FROM_LIST_BTN}`);
  1058. if (!button) return;
  1059.  
  1060. const listItem = button.closest(`li[data-${DATA_ATTR.INDEX}][data-list-id]`);
  1061. if (!listItem) return;
  1062.  
  1063. const index = parseInt(listItem.dataset[DATA_ATTR.INDEX], 10);
  1064. const listId = listItem.getAttribute('data-list-id');
  1065.  
  1066. if (isNaN(index) || !listId || index < 0 || index >= itemsArrayRef.length) return;
  1067.  
  1068. const mapping = getListMapping(listId);
  1069. if (!mapping) return;
  1070.  
  1071. const item = itemsArrayRef[index];
  1072. if (!item) return;
  1073.  
  1074. const itemIsTrulyCustom = item.type === 'custom' ||
  1075. (!item.type && (listId === IDS.SITES_LIST || listId === IDS.TIME_LIST || listId === IDS.FT_LIST));
  1076.  
  1077.  
  1078. if (button.classList.contains(CSS.DELETE_CUSTOM_ITEM) && itemIsTrulyCustom) {
  1079. if (confirm(_('confirm_delete_item', { name: item.text }))) {
  1080. if (_editingItemInfo && _editingItemInfo.listId === listId && _editingItemInfo.index === index) {
  1081. _resetEditStateInternal(contextElement);
  1082. }
  1083. itemsArrayRef.splice(index, 1);
  1084. mapping.populateFn(listId, itemsArrayRef, contextElement);
  1085. }
  1086. } else if (button.classList.contains(CSS.REMOVE_FROM_LIST_BTN) && item.type === 'predefined') {
  1087. if (confirm(_('confirm_remove_item_from_list', { name: (item.originalKey ? _(item.originalKey) : item.text) }))) {
  1088. itemsArrayRef.splice(index, 1);
  1089. mapping.populateFn(listId, itemsArrayRef, contextElement);
  1090. }
  1091. } else if (button.classList.contains(CSS.EDIT_CUSTOM_ITEM) && itemIsTrulyCustom) {
  1092. _prepareEditItemActionInternal(item, index, listId, mapping, contextElement);
  1093. }
  1094. }
  1095.  
  1096. function _handleCustomItemSubmitInternal(listId, contextElement, itemsArrayRef) {
  1097. const mapping = getListMapping(listId);
  1098. if (!mapping) return;
  1099.  
  1100. const itemTypeName = _(mapping.nameKey);
  1101. const textInput = contextElement.querySelector(mapping.textInput);
  1102. const valueInput = contextElement.querySelector(mapping.valueInput);
  1103.  
  1104. const inputGroup = textInput?.closest(`.${CSS.CUSTOM_LIST_INPUT_GROUP}`);
  1105. if (inputGroup) _clearAllInputErrorsInGroup(inputGroup);
  1106.  
  1107.  
  1108. const validationResult = _validateAndPrepareCustomItemData(textInput, valueInput, itemTypeName, listId);
  1109. if (!validationResult.isValid) {
  1110. if (validationResult.errorField) validationResult.errorField.focus();
  1111. return;
  1112. }
  1113.  
  1114. const { text, value } = validationResult;
  1115. const editingIdx = (_editingItemInfo && _editingItemInfo.listId === listId) ? _editingItemInfo.index : -1;
  1116.  
  1117. let isDuplicate;
  1118. if (mapping.isSortableMixed) {
  1119. isDuplicate = _isDuplicateCustomItem(text, itemsArrayRef, listId, editingIdx, _editingItemInfo);
  1120. } else {
  1121. isDuplicate = itemsArrayRef.some((item, idx) => {
  1122. if (editingIdx === idx && (_editingItemInfo?.originalText?.toLowerCase() === text.toLowerCase())) return false;
  1123. return item.text.toLowerCase() === text.toLowerCase();
  1124. });
  1125. }
  1126.  
  1127. if (isDuplicate) {
  1128. if (textInput) _showInputError(textInput, 'alert_duplicate_name', { name: text });
  1129. textInput?.focus();
  1130. return;
  1131. }
  1132.  
  1133. let newItemData;
  1134. if (listId === IDS.SITES_LIST) {
  1135. newItemData = { text: text, url: value };
  1136. } else if (mapping.isSortableMixed) {
  1137. newItemData = { id: value, text: text, value: value, type: 'custom' };
  1138. } else {
  1139. newItemData = { text: text, value: value };
  1140. }
  1141.  
  1142. const itemBeingEdited = (editingIdx > -1) ? itemsArrayRef[editingIdx] : null;
  1143. const itemBeingEditedIsCustom = itemBeingEdited &&
  1144. (itemBeingEdited.type === 'custom' ||
  1145. listId === IDS.SITES_LIST ||
  1146. listId === IDS.TIME_LIST ||
  1147. listId === IDS.FT_LIST);
  1148.  
  1149. if (editingIdx > -1 && itemBeingEditedIsCustom) {
  1150. itemsArrayRef[editingIdx] = {...itemsArrayRef[editingIdx], ...newItemData };
  1151. _resetEditStateInternal(contextElement);
  1152. } else {
  1153. itemsArrayRef.push(newItemData);
  1154. }
  1155.  
  1156. mapping.populateFn(listId, itemsArrayRef, contextElement);
  1157.  
  1158. if (!_editingItemInfo || _editingItemInfo.listId !== listId) {
  1159. if (textInput) { textInput.value = ''; _clearInputError(textInput); textInput.focus(); }
  1160. if (valueInput) { valueInput.value = ''; _clearInputError(valueInput); }
  1161. }
  1162. }
  1163.  
  1164. function _getDragAfterModalListItem(container, y) {
  1165. const draggableElements = [...container.querySelectorAll(`li[draggable="true"]:not(.${CSS.DRAGGING_ITEM})`)];
  1166. return draggableElements.reduce((closest, child) => {
  1167. const box = child.getBoundingClientRect();
  1168. const offset = y - box.top - box.height / 2;
  1169. if (offset < 0 && offset > closest.offset) {
  1170. return { offset: offset, element: child };
  1171. } else {
  1172. return closest;
  1173. }
  1174. }, { offset: Number.NEGATIVE_INFINITY }).element;
  1175. }
  1176.  
  1177. function _handleModalListDragStart(event) {
  1178. if (!event.target.matches('li[draggable="true"]')) return;
  1179. _draggedListItem = event.target;
  1180. event.dataTransfer.effectAllowed = 'move';
  1181. event.dataTransfer.setData('text/plain', _draggedListItem.dataset.index);
  1182. _draggedListItem.classList.add(CSS.DRAGGING_ITEM);
  1183. const list = _draggedListItem.closest('ul');
  1184. if (list) { list.querySelectorAll('li:not(.gscs-dragging-item)').forEach(li => li.style.pointerEvents = 'none'); }
  1185. }
  1186.  
  1187. function _handleModalListDragOver(event) {
  1188. event.preventDefault();
  1189. const listElement = event.currentTarget;
  1190. listElement.querySelectorAll(`li.${CSS.DRAG_OVER_HIGHLIGHT}`).forEach(li => li.classList.remove(CSS.DRAG_OVER_HIGHLIGHT));
  1191.  
  1192. const targetItem = event.target.closest('li[draggable="true"]');
  1193. if (targetItem && targetItem !== _draggedListItem) {
  1194. targetItem.classList.add(CSS.DRAG_OVER_HIGHLIGHT);
  1195. } else {
  1196. const afterElement = _getDragAfterModalListItem(listElement, event.clientY);
  1197. if (afterElement) {
  1198. afterElement.classList.add(CSS.DRAG_OVER_HIGHLIGHT);
  1199. }
  1200. }
  1201. }
  1202. function _handleModalListDragLeave(event) {
  1203. const listElement = event.currentTarget;
  1204. if (event.relatedTarget && listElement.contains(event.relatedTarget)) return;
  1205. listElement.querySelectorAll(`li.${CSS.DRAG_OVER_HIGHLIGHT}`).forEach(li => li.classList.remove(CSS.DRAG_OVER_HIGHLIGHT));
  1206. }
  1207.  
  1208.  
  1209. function _handleModalListDrop(event, listId, itemsArrayRef) {
  1210. event.preventDefault();
  1211. if (!_draggedListItem) return;
  1212.  
  1213. const draggedIndexOriginal = parseInt(event.dataTransfer.getData('text/plain'), 10);
  1214. if (isNaN(draggedIndexOriginal) || draggedIndexOriginal < 0 || draggedIndexOriginal >= itemsArrayRef.length) {
  1215. _handleModalListDragEnd(event.currentTarget);
  1216. return;
  1217. }
  1218.  
  1219. const listElement = event.currentTarget;
  1220. const mapping = getListMapping(listId);
  1221. if (!mapping) { _handleModalListDragEnd(listElement); return; }
  1222.  
  1223.  
  1224. const draggedItemData = itemsArrayRef[draggedIndexOriginal];
  1225. if (!draggedItemData) { _handleModalListDragEnd(listElement); return; }
  1226.  
  1227.  
  1228. const itemsWithoutDragged = itemsArrayRef.filter((item, index) => index !== draggedIndexOriginal);
  1229.  
  1230. const afterElement = _getDragAfterModalListItem(listElement, event.clientY);
  1231. let newIndexInSplicedArray;
  1232.  
  1233. if (afterElement) {
  1234. const originalIndexOfAfterElement = parseInt(afterElement.dataset.index, 10);
  1235. let countSkipped = 0; newIndexInSplicedArray = -1;
  1236. for(let i=0; i < itemsArrayRef.length; i++) {
  1237. if (i === draggedIndexOriginal) continue;
  1238. if (i === originalIndexOfAfterElement) {
  1239. newIndexInSplicedArray = countSkipped;
  1240. break;
  1241. }
  1242. countSkipped++;
  1243. }
  1244. if (newIndexInSplicedArray === -1 && originalIndexOfAfterElement === itemsArrayRef.length -1 && draggedIndexOriginal < originalIndexOfAfterElement) {
  1245. newIndexInSplicedArray = itemsWithoutDragged.length;
  1246. } else if (newIndexInSplicedArray === -1) {
  1247. newIndexInSplicedArray = itemsWithoutDragged.length;
  1248. }
  1249.  
  1250. } else {
  1251. newIndexInSplicedArray = itemsWithoutDragged.length;
  1252. }
  1253.  
  1254. itemsWithoutDragged.splice(newIndexInSplicedArray, 0, draggedItemData);
  1255.  
  1256. itemsArrayRef.length = 0;
  1257. itemsWithoutDragged.forEach(item => itemsArrayRef.push(item));
  1258.  
  1259. _handleModalListDragEnd(listElement);
  1260. mapping.populateFn(listId, itemsArrayRef, _currentModalContent);
  1261.  
  1262. const newLiElements = listElement.querySelectorAll('li');
  1263. newLiElements.forEach((li, idx) => {
  1264. li.dataset.index = idx;
  1265. });
  1266. }
  1267.  
  1268.  
  1269. function _handleModalListDragEnd(listElement) {
  1270. if (_draggedListItem) {
  1271. _draggedListItem.classList.remove(CSS.DRAGGING_ITEM);
  1272. }
  1273. _draggedListItem = null;
  1274. (listElement || _currentModalContent)?.querySelectorAll(`li.${CSS.DRAG_OVER_HIGHLIGHT}`).forEach(li => li.classList.remove(CSS.DRAG_OVER_HIGHLIGHT));
  1275. _currentModalContent?.querySelectorAll('ul.custom-list li[draggable="true"]').forEach(li => li.style.pointerEvents = '');
  1276. }
  1277.  
  1278.  
  1279. function _addPredefinedItemsToModalList(selectedValues, predefinedSourceKey, displayItemsArrayRef, listIdToUpdate, modalContentContext) {
  1280. const mapping = getListMapping(listIdToUpdate);
  1281. if (!mapping) return;
  1282.  
  1283. selectedValues.forEach(value => {
  1284. const predefinedOpt = PREDEFINED_OPTIONS[predefinedSourceKey]?.find(p => p.value === value);
  1285. if (predefinedOpt && !displayItemsArrayRef.some(item => item.value === value && item.type === 'predefined')) {
  1286. displayItemsArrayRef.push({
  1287. id: predefinedOpt.value,
  1288. text: _(predefinedOpt.textKey),
  1289. value: predefinedOpt.value,
  1290. type: 'predefined',
  1291. originalKey: predefinedOpt.textKey
  1292. });
  1293. }
  1294. });
  1295. mapping.populateFn(listIdToUpdate, displayItemsArrayRef, modalContentContext);
  1296. }
  1297.  
  1298. function _bindModalContentEventsInternal(modalContent, itemsArrayRef, listIdForDragDrop = null) {
  1299. if (!modalContent) return;
  1300.  
  1301. if (modalContent.dataset.modalEventsBound === 'true' && listIdForDragDrop === modalContent.dataset.boundListId) return;
  1302.  
  1303.  
  1304. modalContent.addEventListener('click', (event) => {
  1305. const target = event.target;
  1306. let listIdForAction = listIdForDragDrop || target.closest('[data-list-id]')?.dataset.listId || target.closest(`.${CSS.ADD_CUSTOM_BUTTON}`)?.dataset.listId;
  1307.  
  1308. const addNewOptionButton = target.closest(`#${IDS.MODAL_ADD_NEW_OPTION_BTN}`);
  1309. if (addNewOptionButton && listIdForAction) {
  1310. const mapping = getListMapping(listIdForAction);
  1311. const configForModal = modalConfigsData[Object.keys(modalConfigsData).find(key => modalConfigsData[key].listId === listIdForAction)];
  1312.  
  1313. if (mapping && configForModal && configForModal.predefinedSourceKey && configForModal.isSortableMixed) {
  1314. PredefinedOptionChooser.show(
  1315. configForModal.manageType,
  1316. listIdForAction,
  1317. configForModal.predefinedSourceKey,
  1318. itemsArrayRef,
  1319. modalContent,
  1320. _addPredefinedItemsToModalList
  1321. );
  1322. } else if (mapping) {
  1323. const textInput = modalContent.querySelector(mapping.textInput);
  1324. textInput?.focus();
  1325. }
  1326. return;
  1327. }
  1328.  
  1329.  
  1330. const addButton = target.closest(`.${CSS.ADD_CUSTOM_BUTTON}.custom-list-action-button`);
  1331. const itemControlButton = target.closest(`button.${CSS.EDIT_CUSTOM_ITEM}, button.${CSS.DELETE_CUSTOM_ITEM}, button.${CSS.REMOVE_FROM_LIST_BTN}`);
  1332. const cancelEditButton = target.closest('.cancel-edit-button');
  1333.  
  1334. if (itemControlButton && listIdForAction) { _handleCustomListActionsInternal(event, modalContent, itemsArrayRef); return; }
  1335. if (addButton && listIdForAction) { _handleCustomItemSubmitInternal(listIdForAction, modalContent, itemsArrayRef); return; }
  1336. if (cancelEditButton) { _resetEditStateInternal(modalContent); return; }
  1337. });
  1338. modalContent.dataset.modalEventsBound = 'true';
  1339. modalContent.dataset.boundListId = listIdForDragDrop;
  1340.  
  1341.  
  1342. modalContent.addEventListener('input', (event) => {
  1343. const target = event.target;
  1344. if (target.matches(`#${IDS.NEW_SITE_NAME}, #${IDS.NEW_SITE_URL}, #${IDS.NEW_LANG_TEXT}, #${IDS.NEW_LANG_VALUE}, #${IDS.NEW_TIME_TEXT}, #${IDS.NEW_TIME_VALUE}, #${IDS.NEW_FT_TEXT}, #${IDS.NEW_FT_VALUE}, #${IDS.NEW_COUNTRY_TEXT}, #${IDS.NEW_COUNTRY_VALUE}`)) {
  1345. _clearInputError(target); validateCustomInput(target);
  1346. }
  1347. });
  1348.  
  1349. if (listIdForDragDrop) {
  1350. const draggableListElement = modalContent.querySelector(`#${listIdForDragDrop}`);
  1351. if (draggableListElement) {
  1352. if (draggableListElement.dataset.dragEventsBound !== 'true') {
  1353. draggableListElement.dataset.dragEventsBound = 'true';
  1354. draggableListElement.addEventListener('dragstart', _handleModalListDragStart);
  1355. draggableListElement.addEventListener('dragover', _handleModalListDragOver);
  1356. draggableListElement.addEventListener('dragleave', _handleModalListDragLeave);
  1357. draggableListElement.addEventListener('drop', (event) => _handleModalListDrop(event, listIdForDragDrop, itemsArrayRef));
  1358. draggableListElement.addEventListener('dragend', (event) => _handleModalListDragEnd(draggableListElement));
  1359. }
  1360. }
  1361. }
  1362. }
  1363.  
  1364. return {
  1365. show: function(titleKey, contentHTML, onCompleteCallback, currentTheme) {
  1366. this.hide();
  1367. _currentModal = document.createElement('div'); _currentModal.className = 'settings-modal-overlay'; applyThemeToElement(_currentModal, currentTheme);
  1368. _currentModalContent = document.createElement('div'); _currentModalContent.className = 'settings-modal-content'; applyThemeToElement(_currentModalContent, currentTheme);
  1369. const header = document.createElement('div'); header.className = 'settings-modal-header'; header.innerHTML = `<h4>${_(titleKey)}</h4><button class="settings-modal-close-btn" title="${_('settings_close_button_title')}">${SVG_ICONS.close}</button>`;
  1370. const body = document.createElement('div'); body.className = 'settings-modal-body'; body.innerHTML = contentHTML;
  1371. const footer = document.createElement('div'); footer.className = 'settings-modal-footer'; footer.innerHTML = `<button class="modal-complete-btn">${_('modal_button_complete')}</button>`;
  1372. _currentModalContent.appendChild(header); _currentModalContent.appendChild(body); _currentModalContent.appendChild(footer);
  1373. _currentModal.appendChild(_currentModalContent);
  1374. let closeModalHandlerInstance = null; let completeModalHandlerInstance = null; const self = this;
  1375. closeModalHandlerInstance = (event) => { if (event.target === _currentModal || event.target.closest('.settings-modal-close-btn')) { self.hide(true); _currentModal?.removeEventListener('click', closeModalHandlerInstance, true); header.querySelector('.settings-modal-close-btn')?.removeEventListener('click', closeModalHandlerInstance); footer.querySelector('.modal-complete-btn')?.removeEventListener('click', completeModalHandlerInstance); } };
  1376. completeModalHandlerInstance = () => { if (onCompleteCallback && typeof onCompleteCallback === 'function') { onCompleteCallback(_currentModalContent); } _currentModal?.removeEventListener('click', closeModalHandlerInstance, true); header.querySelector('.settings-modal-close-btn')?.removeEventListener('click', closeModalHandlerInstance); footer.querySelector('.modal-complete-btn')?.removeEventListener('click', completeModalHandlerInstance); self.hide(false); };
  1377. _currentModal.addEventListener('click', closeModalHandlerInstance, true);
  1378. header.querySelector('.settings-modal-close-btn').addEventListener('click', closeModalHandlerInstance);
  1379. footer.querySelector('.modal-complete-btn').addEventListener('click', completeModalHandlerInstance);
  1380. _currentModalContent.addEventListener('click', (event) => event.stopPropagation());
  1381. document.body.appendChild(_currentModal);
  1382. return _currentModalContent;
  1383. },
  1384. hide: function(isCancel = false) {
  1385. PredefinedOptionChooser.hide();
  1386. if (_currentModal) {
  1387. const inputGroup = _currentModalContent?.querySelector(`.${CSS.CUSTOM_LIST_INPUT_GROUP}`);
  1388. if (inputGroup) _clearAllInputErrorsInGroup(inputGroup);
  1389. _resetEditStateInternal();
  1390. _currentModal.remove();
  1391. }
  1392. _currentModal = null; _currentModalContent = null; _handleModalListDragEnd();
  1393. },
  1394. openManageCustomOptions: function(manageType, currentSettingsRef, PREDEFINED_OPTIONS_REF, onModalCompleteCallback) {
  1395. const config = modalConfigsData[manageType];
  1396. if (!config) { console.error("Error: Could not get config for manageType:", manageType); return; }
  1397. const mapping = getListMapping(config.listId);
  1398. if (!mapping) { console.error("Error: Could not get mapping for listId:", config.listId); return; }
  1399.  
  1400. const tempItems = JSON.parse(JSON.stringify(currentSettingsRef[config.itemsArrayKey] || []));
  1401. let contentHTML = '';
  1402. const itemTypeNameForDisplay = _(mapping.nameKey);
  1403.  
  1404. if (config.isSortableMixed) {
  1405. contentHTML += _createModalListAndInputHTML(config.listId, config.textPKey, config.valPKey, config.hintKey, config.fmtKey, itemTypeNameForDisplay, true);
  1406. } else if (config.hasPredefinedToggles && config.predefinedSourceKey && PREDEFINED_OPTIONS_REF[config.predefinedSourceKey]) {
  1407. const enabledValues = new Set(currentSettingsRef.enabledPredefinedOptions[config.predefinedSourceKey] || []);
  1408. contentHTML += _createPredefinedOptionsSectionHTML(config.predefinedSourceKey, mapping.nameKey, PREDEFINED_OPTIONS_REF, enabledValues);
  1409. contentHTML += '<hr style="margin: 1em 0;">';
  1410. contentHTML += _createModalListAndInputHTML(config.listId, config.textPKey, config.valPKey, config.hintKey, config.fmtKey, itemTypeNameForDisplay, false);
  1411. } else {
  1412. contentHTML += _createModalListAndInputHTML(config.listId, config.textPKey, config.valPKey, config.hintKey, config.fmtKey, itemTypeNameForDisplay, false);
  1413. }
  1414.  
  1415. const modalContentElement = this.show(
  1416. config.modalTitleKey,
  1417. contentHTML,
  1418. (modalContent) => {
  1419. let newEnabledPredefs = null;
  1420. if (config.hasPredefinedToggles && config.predefinedSourceKey) {
  1421. newEnabledPredefs = [];
  1422. modalContent.querySelectorAll(`.predefined-options-list input[data-option-type="${config.predefinedSourceKey}"]:checked`).forEach(cb => newEnabledPredefs.push(cb.value));
  1423. }
  1424. onModalCompleteCallback(tempItems, newEnabledPredefs, config.itemsArrayKey, config.predefinedSourceKey, config.customItemsMasterKey, config.isSortableMixed, manageType);
  1425. },
  1426. currentSettingsRef.theme
  1427. );
  1428.  
  1429. if (modalContentElement) {
  1430. if (mapping && mapping.populateFn) {
  1431. mapping.populateFn(config.listId, tempItems, modalContentElement);
  1432. }
  1433. _bindModalContentEventsInternal(modalContentElement, tempItems, config.listId);
  1434. }
  1435. },
  1436. resetEditStateGlobally: function() { _resetEditStateInternal(_currentModalContent || document); },
  1437. isModalOpen: function() { return !!_currentModal; }
  1438. };
  1439. })();
  1440.  
  1441. const SettingsUIPaneGenerator = (function() {
  1442. function createGeneralPaneHTML() {
  1443. let langOpts = LocalizationService.getAvailableLocales().map(lc => {
  1444. let dn;
  1445. if (lc === 'auto') dn = _('settings_language_auto');
  1446. else { try { dn = new Intl.DisplayNames([lc],{type:'language'}).of(lc); dn = dn.charAt(0).toUpperCase() + dn.slice(1); } catch(e){ dn = lc; } dn = `${dn} (${lc})`; }
  1447. return `<option value="${lc}">${dn}</option>`;
  1448. }).join('');
  1449. const accordionHintHTML = `<div class="${CSS.SETTING_VALUE_HINT}" style="margin-top:0.3em; margin-left:1.7em; font-weight:normal;">${_('settings_accordion_mode_hint_desc')}</div>`;
  1450. return `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_INTERFACE_LANGUAGE}">${_('settings_interface_language')}</label><select id="${IDS.SETTING_INTERFACE_LANGUAGE}">${langOpts}</select></div>` +
  1451. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_SECTION_MODE}">${_('settings_section_mode')}</label><select id="${IDS.SETTING_SECTION_MODE}"><option value="remember">${_('settings_section_mode_remember')}</option><option value="expandAll">${_('settings_section_mode_expand')}</option><option value="collapseAll">${_('settings_section_mode_collapse')}</option></select><div style="margin-top:0.6em;"><input type="checkbox" id="${IDS.SETTING_ACCORDION}"><label for="${IDS.SETTING_ACCORDION}" class="${CSS.INLINE_LABEL}">${_('settings_accordion_mode')}</label>${accordionHintHTML}</div></div>` +
  1452. `<div class="${CSS.SETTING_ITEM}"><input type="checkbox" id="${IDS.SETTING_DRAGGABLE}"><label for="${IDS.SETTING_DRAGGABLE}" class="${CSS.INLINE_LABEL}">${_('settings_enable_drag')}</label></div>` +
  1453. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_RESET_LOCATION}">${_('settings_reset_button_location')}</label><select id="${IDS.SETTING_RESET_LOCATION}"><option value="tools">${_('settings_location_tools')}</option><option value="topBlock">${_('settings_location_top')}</option><option value="header">${_('settings_location_header')}</option><option value="none">${_('settings_location_hide')}</option></select></div>` +
  1454. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_VERBATIM_LOCATION}">${_('settings_verbatim_button_location')}</label><select id="${IDS.SETTING_VERBATIM_LOCATION}"><option value="tools">${_('settings_location_tools')}</option><option value="topBlock">${_('settings_location_top')}</option><option value="header">${_('settings_location_header')}</option><option value="none">${_('settings_location_hide')}</option></select></div>` +
  1455. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_ADV_SEARCH_LOCATION}">${_('settings_adv_search_location')}</label><select id="${IDS.SETTING_ADV_SEARCH_LOCATION}"><option value="tools">${_('settings_location_tools')}</option><option value="topBlock">${_('settings_location_top')}</option><option value="header">${_('settings_location_header')}</option><option value="none">${_('settings_location_hide')}</option></select></div>`+
  1456. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_PERSONALIZE_LOCATION}">${_('settings_personalize_button_location')}</label><select id="${IDS.SETTING_PERSONALIZE_LOCATION}"><option value="tools">${_('settings_location_tools')}</option><option value="topBlock">${_('settings_location_top')}</option><option value="header">${_('settings_location_header')}</option><option value="none">${_('settings_location_hide')}</option></select></div>`;
  1457. }
  1458. function createAppearancePaneHTML() {
  1459. return `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_WIDTH}">${_('settings_sidebar_width')}</label><span class="${CSS.RANGE_HINT}">${_('settings_width_range_hint')}</span><input type="range" id="${IDS.SETTING_WIDTH}" min="90" max="270" step="5"><span class="${CSS.RANGE_VALUE}"></span></div>` +
  1460. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_FONT_SIZE}">${_('settings_font_size')}</label><span class="${CSS.RANGE_HINT}">${_('settings_font_size_range_hint')}</span><input type="range" id="${IDS.SETTING_FONT_SIZE}" min="8" max="24" step="0.5"><span class="${CSS.RANGE_VALUE}"></span></div>` +
  1461. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_HEADER_ICON_SIZE}">${_('settings_header_icon_size')}</label><span class="${CSS.RANGE_HINT}">${_('settings_header_icon_size_range_hint')}</span><input type="range" id="${IDS.SETTING_HEADER_ICON_SIZE}" min="8" max="32" step="0.5"><span class="${CSS.RANGE_VALUE}"></span></div>` +
  1462. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_VERTICAL_SPACING}">${_('settings_vertical_spacing')}</label><span class="${CSS.RANGE_HINT}">${_('settings_vertical_spacing_range_hint')}</span><input type="range" id="${IDS.SETTING_VERTICAL_SPACING}" min="0.05" max="1.5" step="0.05"><span class="${CSS.RANGE_VALUE}"></span></div>` +
  1463. `<div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_THEME}">${_('settings_theme')}</label><select id="${IDS.SETTING_THEME}"><option value="system">${_('settings_theme_system')}</option><option value="light">${_('settings_theme_light')}</option><option value="dark">${_('settings_theme_dark')}</option><option value="minimal-light">${_('settings_theme_minimal_light')}</option><option value="minimal-dark">${_('settings_theme_minimal_dark')}</option></select></div><div class="${CSS.SETTING_ITEM}"><input type="checkbox" id="${IDS.SETTING_HOVER}"><label for="${IDS.SETTING_HOVER}" class="${CSS.INLINE_LABEL}">${_('settings_hover_mode')}</label><div style="margin-top:0.8em;padding-left:1.5em;"><label for="${IDS.SETTING_OPACITY}" style="display:block;margin-bottom:0.4em;font-weight:normal;">${_('settings_idle_opacity')}</label><span class="${CSS.RANGE_HINT}" style="width:auto;display:inline-block;margin-right:1em;">${_('settings_opacity_range_hint')}</span><input type="range" id="${IDS.SETTING_OPACITY}" min="0.1" max="1.0" step="0.05" style="width:calc(100% - 18em);vertical-align:middle;display:inline-block;"><span class="${CSS.RANGE_VALUE}" style="display:inline-block;min-width:3em;text-align:right;vertical-align:middle;"></span></div></div><div class="${CSS.SETTING_ITEM}"><label for="${IDS.SETTING_COUNTRY_DISPLAY_MODE}">${_('settings_country_display')}</label><select id="${IDS.SETTING_COUNTRY_DISPLAY_MODE}"><option value="iconAndText">${_('settings_country_display_icontext')}</option><option value="textOnly">${_('settings_country_display_text')}</option><option value="iconOnly">${_('settings_country_display_icon')}</option></select></div>`;
  1464. }
  1465. function createFeaturesPaneHTML() {
  1466. const visItemsHTML = ALL_SECTION_DEFINITIONS.map(def=>{ const dn=_(def.titleKey)||def.id; return `<div class="${CSS.SETTING_ITEM} ${CSS.SIMPLE_ITEM}"><input type="checkbox" id="setting-visible-${def.id}" data-${DATA_ATTR.SECTION_ID}="${def.id}"><label for="setting-visible-${def.id}" class="${CSS.INLINE_LABEL}">${dn}</label></div>`; }).join('');
  1467. const siteSearchCheckboxModeHTML =
  1468. `<div class="${CSS.SETTING_ITEM}">` +
  1469. `<input type="checkbox" id="${IDS.SETTING_SITE_SEARCH_CHECKBOX_MODE}"><label for="${IDS.SETTING_SITE_SEARCH_CHECKBOX_MODE}" class="${CSS.INLINE_LABEL}">${_('settings_enable_site_search_checkbox_mode')}</label>` +
  1470. `<div class="${CSS.SETTING_VALUE_HINT}" style="margin-top:0.3em; margin-left:1.7em; font-weight:normal;">${_('settings_enable_site_search_checkbox_mode_hint')}</div>` +
  1471. `</div>`;
  1472. const filetypeSearchCheckboxModeHTML =
  1473. `<div class="${CSS.SETTING_ITEM}">` +
  1474. `<input type="checkbox" id="${IDS.SETTING_FILETYPE_SEARCH_CHECKBOX_MODE}"><label for="${IDS.SETTING_FILETYPE_SEARCH_CHECKBOX_MODE}" class="${CSS.INLINE_LABEL}">${_('settings_enable_filetype_search_checkbox_mode')}</label>` +
  1475. `<div class="${CSS.SETTING_VALUE_HINT}" style="margin-top:0.3em; margin-left:1.7em; font-weight:normal;">${_('settings_enable_filetype_search_checkbox_mode_hint')}</div>` +
  1476. `</div>`;
  1477. return `<p>${_('settings_visible_sections')}</p>${visItemsHTML}` +
  1478. `${siteSearchCheckboxModeHTML}${filetypeSearchCheckboxModeHTML}<hr style="margin:1.2em 0;">` +
  1479. `<p style="font-weight:bold;margin-bottom:0.5em;">${_('settings_section_order')}</p><p class="${CSS.SETTING_VALUE_HINT}" style="font-size:0.9em;margin-top:-0.3em;margin-bottom:0.7em;">${_('settings_section_order_hint')}</p><ul id="${IDS.SIDEBAR_SECTION_ORDER_LIST}" class="${CSS.SECTION_ORDER_LIST}"></ul>`;
  1480. }
  1481. function createCustomPaneHTML() {
  1482. return `<div class="${CSS.SETTING_ITEM}"><p>${_('settings_custom_intro')}</p><button class="${CSS.MANAGE_CUSTOM_BUTTON}" data-${DATA_ATTR.MANAGE_TYPE}="site">${_('settings_manage_sites_button')}</button></div><div class="${CSS.SETTING_ITEM}"><button class="${CSS.MANAGE_CUSTOM_BUTTON}" data-${DATA_ATTR.MANAGE_TYPE}="language">${_('settings_manage_languages_button')}</button></div><div class="${CSS.SETTING_ITEM}"><button class="${CSS.MANAGE_CUSTOM_BUTTON}" data-${DATA_ATTR.MANAGE_TYPE}="country">${_('settings_manage_countries_button')}</button></div><div class="${CSS.SETTING_ITEM}"><button class="${CSS.MANAGE_CUSTOM_BUTTON}" data-${DATA_ATTR.MANAGE_TYPE}="time">${_('settings_manage_time_ranges_button')}</button></div><div class="${CSS.SETTING_ITEM}"><button class="${CSS.MANAGE_CUSTOM_BUTTON}" data-${DATA_ATTR.MANAGE_TYPE}="filetype">${_('settings_manage_file_types_button')}</button></div>`;
  1483. }
  1484. return { createGeneralPaneHTML, createAppearancePaneHTML, createFeaturesPaneHTML, createCustomPaneHTML };
  1485. })();
  1486.  
  1487. const SectionOrderDragHandler = (function() {
  1488. let _draggedItem = null; let _listElement = null; let _settingsRef = null; let _onOrderUpdateCallback = null;
  1489. function getDragAfterElement(container, y) { const draggableElements = [...container.querySelectorAll(`li[draggable="true"]:not(.${CSS.DRAGGING_ITEM})`)]; return draggableElements.reduce((closest, child) => { const box = child.getBoundingClientRect(); const offset = y - box.top - box.height / 2; if (offset < 0 && offset > closest.offset) { return { offset: offset, element: child }; } else { return closest; } }, { offset: Number.NEGATIVE_INFINITY }).element; }
  1490. function handleDragStart(event) { _draggedItem = event.target; event.dataTransfer.effectAllowed = 'move'; event.dataTransfer.setData('text/plain', _draggedItem.dataset.sectionId); _draggedItem.classList.add(CSS.DRAGGING_ITEM); if (_listElement) { _listElement.querySelectorAll('li:not(.gscs-dragging-item)').forEach(li => li.style.pointerEvents = 'none'); } }
  1491. function handleDragOver(event) { event.preventDefault(); if (!_listElement) return; _listElement.querySelectorAll(`li.${CSS.DRAG_OVER_HIGHLIGHT}`).forEach(li => { li.classList.remove(CSS.DRAG_OVER_HIGHLIGHT); }); const targetItem = event.target.closest('li[draggable="true"]'); if (targetItem && targetItem !== _draggedItem) { targetItem.classList.add(CSS.DRAG_OVER_HIGHLIGHT); } else if (!targetItem && _listElement.contains(event.target)) { const afterElement = getDragAfterElement(_listElement, event.clientY); if (afterElement) { afterElement.classList.add(CSS.DRAG_OVER_HIGHLIGHT); } } }
  1492. function handleDragLeave(event) { const relatedTarget = event.relatedTarget; if (_listElement && (!relatedTarget || !_listElement.contains(relatedTarget))) { _listElement.querySelectorAll(`li.${CSS.DRAG_OVER_HIGHLIGHT}`).forEach(li => { li.classList.remove(CSS.DRAG_OVER_HIGHLIGHT); }); } }
  1493. function handleDrop(event) {
  1494. event.preventDefault(); if (!_draggedItem || !_listElement || !_settingsRef || !_onOrderUpdateCallback) return;
  1495. const draggedSectionId = event.dataTransfer.getData('text/plain');
  1496. let currentVisibleOrder = _settingsRef.sidebarSectionOrder.filter(id => _settingsRef.visibleSections[id]);
  1497. const oldIndexInVisible = currentVisibleOrder.indexOf(draggedSectionId);
  1498. if (oldIndexInVisible > -1) { currentVisibleOrder.splice(oldIndexInVisible, 1); } else { handleDragEnd(); return; }
  1499. const afterElement = getDragAfterElement(_listElement, event.clientY);
  1500. if (afterElement) { const targetId = afterElement.dataset.sectionId; const newIndexInVisible = currentVisibleOrder.indexOf(targetId); if (newIndexInVisible > -1) { currentVisibleOrder.splice(newIndexInVisible, 0, draggedSectionId); } else { currentVisibleOrder.push(draggedSectionId); }
  1501. } else { currentVisibleOrder.push(draggedSectionId); }
  1502. const hiddenSectionOrder = _settingsRef.sidebarSectionOrder.filter(id => !_settingsRef.visibleSections[id]);
  1503. _settingsRef.sidebarSectionOrder = [...currentVisibleOrder, ...hiddenSectionOrder];
  1504. handleDragEnd(); _onOrderUpdateCallback();
  1505. }
  1506. function handleDragEnd() { if (_draggedItem) { _draggedItem.classList.remove(CSS.DRAGGING_ITEM); } _draggedItem = null; if (_listElement) { _listElement.querySelectorAll('li').forEach(li => { li.classList.remove(CSS.DRAG_OVER_HIGHLIGHT); li.style.pointerEvents = ''; }); } }
  1507. function initialize(listEl, currentSettings, orderUpdateCallback) { _listElement = listEl; _settingsRef = currentSettings; _onOrderUpdateCallback = orderUpdateCallback; if (_listElement && _listElement.dataset.sectionOrderDragBound !== 'true') { _listElement.addEventListener('dragstart', handleDragStart); _listElement.addEventListener('dragover', handleDragOver); _listElement.addEventListener('dragleave', handleDragLeave); _listElement.addEventListener('drop', handleDrop); _listElement.addEventListener('dragend', handleDragEnd); _listElement.dataset.sectionOrderDragBound = 'true'; } }
  1508. function destroy() { if (_listElement && _listElement.dataset.sectionOrderDragBound === 'true') { _listElement.removeEventListener('dragstart', handleDragStart); _listElement.removeEventListener('dragover', handleDragOver); _listElement.removeEventListener('dragleave', handleDragLeave); _listElement.removeEventListener('drop', handleDrop); _listElement.removeEventListener('dragend', handleDragEnd); delete _listElement.dataset.sectionOrderDragBound; } _listElement = null; _settingsRef = null; _onOrderUpdateCallback = null; }
  1509. return { initialize, destroy };
  1510. })();
  1511.  
  1512. const SettingsManager = (function() {
  1513. let _settingsWindow = null; let _settingsOverlay = null; let _currentSettings = {};
  1514. let _settingsBackup = {}; let _defaultSettingsRef = null; let _isInitialized = false;
  1515. let _applySettingsToSidebar_cb = ()=>{}; let _buildSidebarUI_cb = ()=>{};
  1516. let _applySectionCollapseStates_cb = ()=>{}; let _initMenuCommands_cb = ()=>{};
  1517. let _renderSectionOrderList_ext_cb = ()=>{};
  1518.  
  1519. function _populateSliderSetting_internal(win,id,value,formatFn=(val)=>val){const i=win.querySelector(`#${id}`);if(i){i.value=value;let vs=i.parentNode.querySelector(`.${CSS.RANGE_VALUE}`);if(vs&&vs.classList.contains(CSS.RANGE_VALUE)){vs.textContent=formatFn(value);}}}
  1520. function _populateGeneralSettings_internal(win,s){ const lS=win.querySelector(`#${IDS.SETTING_INTERFACE_LANGUAGE}`);if(lS)lS.value=s.interfaceLanguage;const sMS=win.querySelector(`#${IDS.SETTING_SECTION_MODE}`),acC=win.querySelector(`#${IDS.SETTING_ACCORDION}`);if(sMS&&acC){sMS.value=s.sectionDisplayMode;const iRM=s.sectionDisplayMode==='remember';acC.disabled=!iRM;acC.checked=iRM?s.accordionMode:false; const accordionHint = acC.parentElement.querySelector(`.${CSS.SETTING_VALUE_HINT}`); if(accordionHint) accordionHint.style.color = iRM ? '' : 'grey';} const dC=win.querySelector(`#${IDS.SETTING_DRAGGABLE}`);if(dC)dC.checked=s.draggableHandleEnabled;const rLS=win.querySelector(`#${IDS.SETTING_RESET_LOCATION}`);if(rLS)rLS.value=s.resetButtonLocation;const vLS=win.querySelector(`#${IDS.SETTING_VERBATIM_LOCATION}`);if(vLS)vLS.value=s.verbatimButtonLocation;const aSLS=win.querySelector(`#${IDS.SETTING_ADV_SEARCH_LOCATION}`);if(aSLS)aSLS.value=s.advancedSearchLinkLocation; const pznLS = win.querySelector(`#${IDS.SETTING_PERSONALIZE_LOCATION}`); if (pznLS) pznLS.value = s.personalizationButtonLocation;}
  1521. function _populateAppearanceSettings_internal(win,s){_populateSliderSetting_internal(win,IDS.SETTING_WIDTH,s.sidebarWidth);_populateSliderSetting_internal(win,IDS.SETTING_FONT_SIZE,s.fontSize,v=>parseFloat(v).toFixed(1));_populateSliderSetting_internal(win,IDS.SETTING_HEADER_ICON_SIZE,s.headerIconSize,v=>parseFloat(v).toFixed(1));_populateSliderSetting_internal(win,IDS.SETTING_VERTICAL_SPACING,s.verticalSpacingMultiplier,v=>`x ${parseFloat(v).toFixed(2)}`);_populateSliderSetting_internal(win,IDS.SETTING_OPACITY,s.idleOpacity,v=>parseFloat(v).toFixed(2));const tS=win.querySelector(`#${IDS.SETTING_THEME}`);if(tS)tS.value=s.theme;const cDS=win.querySelector(`#${IDS.SETTING_COUNTRY_DISPLAY_MODE}`);if(cDS)cDS.value=s.countryDisplayMode;const hC=win.querySelector(`#${IDS.SETTING_HOVER}`),oI=win.querySelector(`#${IDS.SETTING_OPACITY}`);if(hC&&oI){hC.checked=s.hoverMode;const iHE=s.hoverMode;oI.disabled=!iHE;const oC=oI.closest('div');if(oC){oC.style.opacity=iHE?'1':'0.6';oC.style.pointerEvents=iHE?'auto':'none';}}}
  1522. function _populateFeatureSettings_internal(win,s,renderFn){win.querySelectorAll(`#${IDS.TAB_PANE_FEATURES} input[type="checkbox"][data-${DATA_ATTR.SECTION_ID}]`)?.forEach(cb=>{const sId=cb.getAttribute(`data-${DATA_ATTR.SECTION_ID}`);if(sId&&s.visibleSections.hasOwnProperty(sId)){cb.checked=s.visibleSections[sId];}else if(sId&&_defaultSettingsRef.visibleSections.hasOwnProperty(sId)){cb.checked=_defaultSettingsRef.visibleSections[sId]??false;}}); const siteSearchCheckboxModeEl = win.querySelector(`#${IDS.SETTING_SITE_SEARCH_CHECKBOX_MODE}`); if(siteSearchCheckboxModeEl) siteSearchCheckboxModeEl.checked = s.enableSiteSearchCheckboxMode; const filetypeSearchCheckboxModeEl = win.querySelector(`#${IDS.SETTING_FILETYPE_SEARCH_CHECKBOX_MODE}`); if(filetypeSearchCheckboxModeEl) filetypeSearchCheckboxModeEl.checked = s.enableFiletypeCheckboxMode; renderFn(s);}
  1523. function _initializeActiveSettingsTab_internal(){if(!_settingsWindow)return;const tC=_settingsWindow.querySelector(`.${CSS.SETTINGS_TABS}`),cC=_settingsWindow.querySelector(`.${CSS.SETTINGS_TAB_CONTENT}`);if(!tC||!cC)return;const aTB=tC.querySelector(`.${CSS.TAB_BUTTON}.${CSS.ACTIVE}`);const tT=(aTB&&aTB.dataset[DATA_ATTR.TAB])?aTB.dataset[DATA_ATTR.TAB]:'general';tC.querySelectorAll(`.${CSS.TAB_BUTTON}`).forEach(b=>b.classList.toggle(CSS.ACTIVE,b.dataset[DATA_ATTR.TAB]===tT));cC.querySelectorAll(`.${CSS.TAB_PANE}`).forEach(p=>p.classList.toggle(CSS.ACTIVE,p.dataset[DATA_ATTR.TAB]===tT));}
  1524. function _loadFromStorage(){try{const s=GM_getValue(STORAGE_KEY,'{}');return JSON.parse(s||'{}');}catch(e){console.error(`${LOG_PREFIX} Error loading/parsing settings:`,e);return{};}}
  1525. function _migrateToDisplayArraysIfNecessary(settings) {
  1526. const displayTypes = [ { displayKey: 'displayLanguages', predefinedKey: 'language', customKey: 'customLanguages', defaultEnabled: defaultSettings.enabledPredefinedOptions.language }, { displayKey: 'displayCountries', predefinedKey: 'country', customKey: 'customCountries', defaultEnabled: defaultSettings.enabledPredefinedOptions.country } ]; let migrationPerformed = false;
  1527. displayTypes.forEach(typeInfo => { if ((!settings[typeInfo.displayKey] || settings[typeInfo.displayKey].length === 0) && ( (settings.enabledPredefinedOptions && settings.enabledPredefinedOptions[typeInfo.predefinedKey]?.length > 0) || (settings[typeInfo.customKey] && settings[typeInfo.customKey]?.length > 0) ) ) { console.log(`${LOG_PREFIX} Migrating settings for ${typeInfo.displayKey}`); migrationPerformed = true; const newDisplayArray = []; const addedValues = new Set(); const enabledPredefined = settings.enabledPredefinedOptions?.[typeInfo.predefinedKey] || typeInfo.defaultEnabled || []; enabledPredefined.forEach(val => { const predefinedOpt = PREDEFINED_OPTIONS[typeInfo.predefinedKey]?.find(p => p.value === val); if (predefinedOpt && !addedValues.has(predefinedOpt.value)) { newDisplayArray.push({ id: predefinedOpt.value, text: _(predefinedOpt.textKey), value: predefinedOpt.value, type: 'predefined', originalKey: predefinedOpt.textKey }); addedValues.add(predefinedOpt.value); } }); newDisplayArray.sort((a,b) => { const textA = a.originalKey ? _(a.originalKey) : a.text; const textB = b.originalKey ? _(b.originalKey) : b.text; return textA.localeCompare(textB, LocalizationService.getCurrentLocale(), {sensitivity: 'base'}) }); const customItems = settings[typeInfo.customKey] || []; customItems.forEach(customOpt => { if (customOpt.value && !addedValues.has(customOpt.value)) { newDisplayArray.push({ id: customOpt.value, text: customOpt.text, value: customOpt.value, type: 'custom' }); addedValues.add(customOpt.value); } }); settings[typeInfo.displayKey] = newDisplayArray; if (settings.enabledPredefinedOptions) { settings.enabledPredefinedOptions[typeInfo.predefinedKey] = []; } } else if (!settings[typeInfo.displayKey]) { settings[typeInfo.displayKey] = JSON.parse(JSON.stringify(defaultSettings[typeInfo.displayKey] || [])); } });
  1528. if (migrationPerformed) console.log(`${LOG_PREFIX} Migration to display arrays complete.`);
  1529. }
  1530. function _validateAndMergeSettings(saved){
  1531. let newSettings = JSON.parse(JSON.stringify(_defaultSettingsRef)); newSettings = Utils.mergeDeep(newSettings, saved);
  1532. _validateAndMergeCoreSettings_internal(newSettings, saved, _defaultSettingsRef); _validateAndMergeAppearanceSettings_internal(newSettings, saved, _defaultSettingsRef); _validateAndMergeFeatureSettings_internal(newSettings, saved, _defaultSettingsRef); _validateAndMergeCustomLists_internal(newSettings, saved, _defaultSettingsRef);
  1533. _migrateToDisplayArraysIfNecessary(newSettings);
  1534. ['displayLanguages', 'displayCountries'].forEach(displayKey => { if (!Array.isArray(newSettings[displayKey])) { newSettings[displayKey] = JSON.parse(JSON.stringify(_defaultSettingsRef[displayKey])) || []; } newSettings[displayKey] = newSettings[displayKey].filter(item => item && typeof item.id === 'string' && (item.type === 'predefined' ? (typeof item.text === 'string' && typeof item.originalKey === 'string') : typeof item.text === 'string') && typeof item.value === 'string' && (item.type === 'predefined' || item.type === 'custom') ); });
  1535. _validateAndMergePredefinedOptions_internal(newSettings, saved, _defaultSettingsRef); _finalizeSectionOrder_internal(newSettings, saved, _defaultSettingsRef);
  1536. return newSettings;
  1537. }
  1538. function _validateAndMergeCoreSettings_internal(target,source,defaults){if(typeof target.sidebarPosition!=='object'||target.sidebarPosition===null||Array.isArray(target.sidebarPosition)){target.sidebarPosition=JSON.parse(JSON.stringify(defaults.sidebarPosition));}target.sidebarPosition.left=parseInt(target.sidebarPosition.left,10)||defaults.sidebarPosition.left;target.sidebarPosition.top=parseInt(target.sidebarPosition.top,10)||defaults.sidebarPosition.top;if(typeof target.sectionStates!=='object'||target.sectionStates===null||Array.isArray(target.sectionStates)){target.sectionStates={};}target.sidebarCollapsed=!!target.sidebarCollapsed;target.draggableHandleEnabled=typeof target.draggableHandleEnabled==='boolean'?target.draggableHandleEnabled:defaults.draggableHandleEnabled;target.interfaceLanguage=typeof source.interfaceLanguage==='string'?source.interfaceLanguage:defaults.interfaceLanguage;}
  1539. function _validateAndMergeAppearanceSettings_internal(target,source,defaults){target.sidebarWidth=Utils.clamp(parseInt(target.sidebarWidth,10)||defaults.sidebarWidth,90,270);target.fontSize=Utils.clamp(parseFloat(target.fontSize)||defaults.fontSize,8,24);target.headerIconSize=Utils.clamp(parseFloat(target.headerIconSize)||defaults.headerIconSize,8,32);target.verticalSpacingMultiplier=Utils.clamp(parseFloat(target.verticalSpacingMultiplier)||defaults.verticalSpacingMultiplier,0.05,1.5);target.idleOpacity=Utils.clamp(parseFloat(target.idleOpacity)||defaults.idleOpacity,0.1,1.0);target.hoverMode=!!target.hoverMode;const validThemes=['system','light','dark','minimal-light','minimal-dark'];if(target.theme==='minimal')target.theme='minimal-light';else if(!validThemes.includes(target.theme))target.theme=defaults.theme;}
  1540. function _validateAndMergeFeatureSettings_internal(target,source,defaults){if(typeof target.visibleSections!=='object'||target.visibleSections===null||Array.isArray(target.visibleSections)){target.visibleSections=JSON.parse(JSON.stringify(defaults.visibleSections));}const validSectionIDs=new Set(ALL_SECTION_DEFINITIONS.map(def=>def.id));Object.keys(defaults.visibleSections).forEach(id=>{if(!validSectionIDs.has(id)){console.warn(`${LOG_PREFIX} Invalid section ID in defaultSettings.visibleSections: ${id}`);}else if(typeof target.visibleSections[id]!=='boolean'){target.visibleSections[id]=defaults.visibleSections[id]??true;}});const validSectionModes=['remember','expandAll','collapseAll'];if(!validSectionModes.includes(target.sectionDisplayMode))target.sectionDisplayMode=defaults.sectionDisplayMode;target.accordionMode=!!target.accordionMode; target.enableSiteSearchCheckboxMode = typeof target.enableSiteSearchCheckboxMode === 'boolean' ? target.enableSiteSearchCheckboxMode : defaults.enableSiteSearchCheckboxMode; target.enableFiletypeCheckboxMode = typeof target.enableFiletypeCheckboxMode === 'boolean' ? target.enableFiletypeCheckboxMode : defaults.enableFiletypeCheckboxMode; const validButtonLocations=['header','topBlock','tools','none'];if(!validButtonLocations.includes(target.resetButtonLocation))target.resetButtonLocation=defaults.resetButtonLocation;if(!validButtonLocations.includes(target.verbatimButtonLocation))target.verbatimButtonLocation=defaults.verbatimButtonLocation;if(!validButtonLocations.includes(target.advancedSearchLinkLocation))target.advancedSearchLinkLocation=defaults.advancedSearchLinkLocation; if (!validButtonLocations.includes(target.personalizationButtonLocation)) { target.personalizationButtonLocation = defaults.personalizationButtonLocation; } const validCountryDisplayModes=['iconAndText','textOnly','iconOnly'];if(!validCountryDisplayModes.includes(target.countryDisplayMode))target.countryDisplayMode=defaults.countryDisplayMode;}
  1541. function _validateAndMergeCustomLists_internal(target,source,defaults){const listKeys=['favoriteSites','customLanguages','customTimeRanges','customFiletypes','customCountries'];listKeys.forEach(key=>{target[key]=Array.isArray(target[key])?target[key].filter(item=>item&&typeof item.text==='string'&&typeof item[key==='favoriteSites'?'url':'value']==='string'&&item.text.trim()!==''&&item[key==='favoriteSites'?'url':'value'].trim()!==''):JSON.parse(JSON.stringify(defaults[key]));});}
  1542. function _validateAndMergePredefinedOptions_internal(target,source,defaults){ target.enabledPredefinedOptions = target.enabledPredefinedOptions || {}; ['time', 'filetype'].forEach(type => { if (!target.enabledPredefinedOptions[type] || !Array.isArray(target.enabledPredefinedOptions[type])) { target.enabledPredefinedOptions[type] = JSON.parse(JSON.stringify(defaults.enabledPredefinedOptions[type] || [])); } const savedTypeOptions = source.enabledPredefinedOptions?.[type]; if (PREDEFINED_OPTIONS[type] && Array.isArray(savedTypeOptions)) { const validValues = new Set(PREDEFINED_OPTIONS[type].map(opt => opt.value)); target.enabledPredefinedOptions[type] = savedTypeOptions.filter(val => typeof val === 'string' && validValues.has(val)); } else if (!PREDEFINED_OPTIONS[type]) { target.enabledPredefinedOptions[type] = []; } }); if (target.displayLanguages && target.enabledPredefinedOptions) target.enabledPredefinedOptions.language = []; if (target.displayCountries && target.enabledPredefinedOptions) target.enabledPredefinedOptions.country = []; }
  1543. function _finalizeSectionOrder_internal(target,source,defaults){const finalOrder=[];const currentVisibleOrderSet=new Set();const validSectionIDs=new Set(ALL_SECTION_DEFINITIONS.map(def=>def.id));const orderSource=(Array.isArray(source.sidebarSectionOrder)&&source.sidebarSectionOrder.length>0)?source.sidebarSectionOrder:defaults.sidebarSectionOrder;orderSource.forEach(id=>{if(typeof id==='string'&&validSectionIDs.has(id)&&target.visibleSections[id]===true&&!currentVisibleOrderSet.has(id)){finalOrder.push(id);currentVisibleOrderSet.add(id);}});defaults.sidebarSectionOrder.forEach(id=>{if(typeof id==='string'&&validSectionIDs.has(id)&&target.visibleSections[id]===true&&!currentVisibleOrderSet.has(id)){finalOrder.push(id);}});target.sidebarSectionOrder=finalOrder;}
  1544. const _sEH_internal = { [IDS.SETTING_WIDTH]:(t,vS)=>_hSLI(t,'sidebarWidth',vS,90,270,5), [IDS.SETTING_FONT_SIZE]:(t,vS)=>_hSLI(t,'fontSize',vS,8,24,0.5,v=>parseFloat(v).toFixed(1)), [IDS.SETTING_HEADER_ICON_SIZE]:(t,vS)=>_hSLI(t,'headerIconSize',vS,8,32,0.5,v=>parseFloat(v).toFixed(1)), [IDS.SETTING_VERTICAL_SPACING]:(t,vS)=>_hSLI(t,'verticalSpacingMultiplier',vS,0.05,1.5,0.05,v=>`x ${parseFloat(v).toFixed(2)}`), [IDS.SETTING_OPACITY]:(t,vS)=>_hSLI(t,'idleOpacity',vS,0.1,1.0,0.05,v=>parseFloat(v).toFixed(2)), [IDS.SETTING_INTERFACE_LANGUAGE]:(t)=>{const nL=t.value;if(_currentSettings.interfaceLanguage!==nL){_currentSettings.interfaceLanguage=nL;LocalizationService.updateActiveLocale(_currentSettings);_initMenuCommands_cb();publicApi.populateWindow();_buildSidebarUI_cb();}}, [IDS.SETTING_THEME]:(t)=>{_currentSettings.theme=t.value;_applySettingsToSidebar_cb(_currentSettings);}, [IDS.SETTING_HOVER]:(t)=>{_currentSettings.hoverMode=t.checked;const oI=_settingsWindow.querySelector(`#${IDS.SETTING_OPACITY}`);if(oI){const iHE=_currentSettings.hoverMode;oI.disabled=!iHE;const oC=oI.closest('div');if(oC){oC.style.opacity=iHE?'1':'0.6';oC.style.pointerEvents=iHE?'auto':'none';}}_applySettingsToSidebar_cb(_currentSettings);}, [IDS.SETTING_DRAGGABLE]:(t)=>{_currentSettings.draggableHandleEnabled=t.checked;_applySettingsToSidebar_cb(_currentSettings);DragManager.setDraggable(t.checked, sidebar, sidebar?.querySelector(`.${CSS.DRAG_HANDLE}`), _currentSettings, debouncedSaveSettings);}, [IDS.SETTING_ACCORDION]:(t)=>{const sMS=_settingsWindow.querySelector(`#${IDS.SETTING_SECTION_MODE}`);if(sMS?.value==='remember')_currentSettings.accordionMode=t.checked;else{t.checked=false;_currentSettings.accordionMode=false;}_applySettingsToSidebar_cb(_currentSettings);_applySectionCollapseStates_cb();}, [IDS.SETTING_SECTION_MODE]:(t)=>{_currentSettings.sectionDisplayMode=t.value;const aC=_settingsWindow.querySelector(`#${IDS.SETTING_ACCORDION}`);if(aC){const iRM=t.value==='remember';aC.disabled=!iRM; if(aC.parentElement.querySelector(`.${CSS.SETTING_VALUE_HINT}`)) aC.parentElement.querySelector(`.${CSS.SETTING_VALUE_HINT}`).style.color = iRM ? '' : 'grey'; if(!iRM){aC.checked=false;_currentSettings.accordionMode=false;}else{aC.checked=_settingsBackup?.accordionMode??_currentSettings.accordionMode??_defaultSettingsRef.accordionMode;_currentSettings.accordionMode=aC.checked;}}_applySettingsToSidebar_cb(_currentSettings);_applySectionCollapseStates_cb();}, [IDS.SETTING_RESET_LOCATION]:(t)=>{_currentSettings.resetButtonLocation=t.value;_buildSidebarUI_cb();}, [IDS.SETTING_VERBATIM_LOCATION]:(t)=>{_currentSettings.verbatimButtonLocation=t.value;_buildSidebarUI_cb();}, [IDS.SETTING_ADV_SEARCH_LOCATION]:(t)=>{_currentSettings.advancedSearchLinkLocation=t.value;_buildSidebarUI_cb();}, [IDS.SETTING_PERSONALIZE_LOCATION]: (target) => { _currentSettings.personalizationButtonLocation = target.value; _buildSidebarUI_cb(); }, [IDS.SETTING_SITE_SEARCH_CHECKBOX_MODE]: (target) => { _currentSettings.enableSiteSearchCheckboxMode = target.checked; _buildSidebarUI_cb(); }, [IDS.SETTING_FILETYPE_SEARCH_CHECKBOX_MODE]: (target) => { _currentSettings.enableFiletypeCheckboxMode = target.checked; _buildSidebarUI_cb(); }, [IDS.SETTING_COUNTRY_DISPLAY_MODE]:(t)=>{_currentSettings.countryDisplayMode=t.value;_buildSidebarUI_cb();}, };
  1545. function _hSLI(t,sK,vS,min,max,step,fFn=v=>v){const v=Utils.clamp((step===1||step===5)?parseInt(t.value,10):parseFloat(t.value),min,max);if(isNaN(v))_currentSettings[sK]=_defaultSettingsRef[sK];else _currentSettings[sK]=v;if(vS)vS.textContent=fFn(_currentSettings[sK]);_applySettingsToSidebar_cb(_currentSettings);}
  1546. function _lUH_internal(e){const t=e.target;if(!t)return;const sI=t.id;const vS=(t.type==='range')?t.parentNode.querySelector(`.${CSS.RANGE_VALUE}`):null;if(_sEH_internal[sI]){if(t.type==='range')_sEH_internal[sI](t,vS);else _sEH_internal[sI](t);}}
  1547.  
  1548. const publicApi = {
  1549. initialize: function(defaultSettingsObj, applyCb, buildCb, collapseCb, menuCb, renderOrderCb) { if(_isInitialized) return; _defaultSettingsRef = defaultSettingsObj; _applySettingsToSidebar_cb = applyCb; _buildSidebarUI_cb = buildCb; _applySectionCollapseStates_cb = collapseCb; _initMenuCommands_cb = menuCb; _renderSectionOrderList_ext_cb = renderOrderCb; this.load(); this.buildSkeleton(); _isInitialized = true; },
  1550. load: function(){ const s=_loadFromStorage(); _currentSettings=_validateAndMergeSettings(s); LocalizationService.updateActiveLocale(_currentSettings);},
  1551. save: function(logContext='SaveBtn'){ try { ['displayLanguages', 'displayCountries'].forEach(displayKey => { const mapping = getListMapping(displayKey === 'displayLanguages' ? IDS.LANG_LIST : IDS.COUNTRIES_LIST); if (mapping && mapping.customItemsMasterKey && _currentSettings[displayKey] && Array.isArray(_currentSettings[mapping.customItemsMasterKey])) { const displayItems = _currentSettings[displayKey]; const currentDisplayCustomItems = displayItems.filter(item => item.type === 'custom'); const currentDisplayCustomItemValues = new Set(currentDisplayCustomItems.map(item => item.value)); const newMasterList = (_currentSettings[mapping.customItemsMasterKey] || []).filter(masterItem => currentDisplayCustomItemValues.has(masterItem.value)).map(oldMasterItem => { const correspondingDisplayItem = currentDisplayCustomItems.find(d => d.value === oldMasterItem.value); return correspondingDisplayItem ? { text: correspondingDisplayItem.text, value: oldMasterItem.value } : oldMasterItem; }); currentDisplayCustomItems.forEach(dispItem => { if (!newMasterList.find(mi => mi.value === dispItem.value)) { newMasterList.push({ text: dispItem.text, value: dispItem.value }); } }); _currentSettings[mapping.customItemsMasterKey] = newMasterList; } }); GM_setValue(STORAGE_KEY, JSON.stringify(_currentSettings)); console.log(`${LOG_PREFIX} Settings saved by SM${logContext ? ` (${logContext})` : ''}.`); _settingsBackup = JSON.parse(JSON.stringify(_currentSettings)); } catch (e) { console.error(`${LOG_PREFIX} SM save error:`, e); NotificationManager.show('alert_generic_error', { context: 'saving settings' }, 'error', 5000); } },
  1552. reset: function(){ if(confirm(_('confirm_reset_settings'))){ _currentSettings = JSON.parse(JSON.stringify(_defaultSettingsRef)); _migrateToDisplayArraysIfNecessary(_currentSettings); if(!_currentSettings.sidebarSectionOrder||_currentSettings.sidebarSectionOrder.length===0){ _currentSettings.sidebarSectionOrder = [..._defaultSettingsRef.sidebarSectionOrder]; } LocalizationService.updateActiveLocale(_currentSettings); this.populateWindow(); _applySettingsToSidebar_cb(_currentSettings); _buildSidebarUI_cb(); _initMenuCommands_cb(); _showGlobalMessage('alert_settings_reset_success',{},'success',4000);}},
  1553. resetAllFromMenu: function(){ if(confirm(_('confirm_reset_all_menu'))){ try{ GM_setValue(STORAGE_KEY,JSON.stringify(_defaultSettingsRef)); alert(_('alert_reset_all_menu_success')); }catch(e){ _showGlobalMessage('alert_reset_all_menu_fail',{},'error',0); }}},
  1554. getCurrentSettings: function(){ return _currentSettings;},
  1555. buildSkeleton: function(){ if(_settingsWindow)return; _settingsOverlay=document.createElement('div');_settingsOverlay.id=IDS.SETTINGS_OVERLAY;_settingsWindow=document.createElement('div');_settingsWindow.id=IDS.SETTINGS_WINDOW;const h=document.createElement('div');h.classList.add(CSS.SETTINGS_HEADER);h.innerHTML=`<h3>${_('settingsTitle')}</h3><button class="${CSS.SETTINGS_CLOSE_BTN}" title="${_('settings_close_button_title')}">${SVG_ICONS.close}</button>`;const mB=document.createElement('div');mB.id=IDS.SETTINGS_MESSAGE_BAR;mB.classList.add(CSS.MESSAGE_BAR);mB.style.display='none';const ts=document.createElement('div');ts.classList.add(CSS.SETTINGS_TABS);ts.innerHTML=`<button class="${CSS.TAB_BUTTON} ${CSS.ACTIVE}" data-${DATA_ATTR.TAB}="general">${_('settings_tab_general')}</button> <button class="${CSS.TAB_BUTTON}" data-${DATA_ATTR.TAB}="appearance">${_('settings_tab_appearance')}</button> <button class="${CSS.TAB_BUTTON}" data-${DATA_ATTR.TAB}="features">${_('settings_tab_features')}</button> <button class="${CSS.TAB_BUTTON}" data-${DATA_ATTR.TAB}="custom">${_('settings_tab_custom')}</button>`;const c=document.createElement('div');c.classList.add(CSS.SETTINGS_TAB_CONTENT);c.innerHTML=`<div class="${CSS.TAB_PANE} ${CSS.ACTIVE}" data-${DATA_ATTR.TAB}="general" id="${IDS.TAB_PANE_GENERAL}"></div><div class="${CSS.TAB_PANE}" data-${DATA_ATTR.TAB}="appearance" id="${IDS.TAB_PANE_APPEARANCE}"></div><div class="${CSS.TAB_PANE}" data-${DATA_ATTR.TAB}="features" id="${IDS.TAB_PANE_FEATURES}"></div><div class="${CSS.TAB_PANE}" data-${DATA_ATTR.TAB}="custom" id="${IDS.TAB_PANE_CUSTOM}"></div>`;const f=document.createElement('div');f.classList.add(CSS.SETTINGS_FOOTER);f.innerHTML=`<button class="${CSS.RESET_BUTTON}">${_('settings_reset_all_button')}</button><button class="${CSS.CANCEL_BUTTON}">${_('settings_cancel_button')}</button><button class="${CSS.SAVE_BUTTON}">${_('settings_save_button')}</button>`;_settingsWindow.appendChild(h);_settingsWindow.appendChild(mB);_settingsWindow.appendChild(ts);_settingsWindow.appendChild(c);_settingsWindow.appendChild(f);_settingsOverlay.appendChild(_settingsWindow);document.body.appendChild(_settingsOverlay);this.bindEvents();},
  1556. populateWindow: function(){
  1557. if(!_settingsWindow)return;
  1558. try {
  1559. _settingsWindow.querySelector(`.${CSS.SETTINGS_HEADER} h3`).textContent=_( 'settingsTitle');
  1560. _settingsWindow.querySelector(`.${CSS.SETTINGS_CLOSE_BTN}`).title=_( 'settings_close_button_title');
  1561. _settingsWindow.querySelector(`button[data-${DATA_ATTR.TAB}="general"]`).textContent=_( 'settings_tab_general');
  1562. _settingsWindow.querySelector(`button[data-${DATA_ATTR.TAB}="appearance"]`).textContent=_( 'settings_tab_appearance');
  1563. _settingsWindow.querySelector(`button[data-${DATA_ATTR.TAB}="features"]`).textContent=_( 'settings_tab_features');
  1564. _settingsWindow.querySelector(`button[data-${DATA_ATTR.TAB}="custom"]`).textContent=_( 'settings_tab_custom');
  1565. _settingsWindow.querySelector(`.${CSS.RESET_BUTTON}`).textContent=_( 'settings_reset_all_button');
  1566. _settingsWindow.querySelector(`.${CSS.CANCEL_BUTTON}`).textContent=_( 'settings_cancel_button');
  1567. _settingsWindow.querySelector(`.${CSS.SAVE_BUTTON}`).textContent=_( 'settings_save_button');
  1568.  
  1569. const paneGeneral = _settingsWindow.querySelector(`#${IDS.TAB_PANE_GENERAL}`); if(paneGeneral) paneGeneral.innerHTML = SettingsUIPaneGenerator.createGeneralPaneHTML();
  1570. const paneAppearance = _settingsWindow.querySelector(`#${IDS.TAB_PANE_APPEARANCE}`); if(paneAppearance) paneAppearance.innerHTML = SettingsUIPaneGenerator.createAppearancePaneHTML();
  1571. const paneFeatures = _settingsWindow.querySelector(`#${IDS.TAB_PANE_FEATURES}`); if(paneFeatures) paneFeatures.innerHTML = SettingsUIPaneGenerator.createFeaturesPaneHTML();
  1572. const paneCustom = _settingsWindow.querySelector(`#${IDS.TAB_PANE_CUSTOM}`); if(paneCustom) paneCustom.innerHTML = SettingsUIPaneGenerator.createCustomPaneHTML();
  1573.  
  1574. _populateGeneralSettings_internal(_settingsWindow, _currentSettings);
  1575. _populateAppearanceSettings_internal(_settingsWindow, _currentSettings);
  1576. _populateFeatureSettings_internal(_settingsWindow, _currentSettings, _renderSectionOrderList_ext_cb);
  1577. ModalManager.resetEditStateGlobally(); _initializeActiveSettingsTab_internal();
  1578. this.bindLiveUpdateEvents(); this.bindFeaturesTabEvents();
  1579. }catch(e){ _showGlobalMessage('alert_init_fail',{scriptName:SCRIPT_INTERNAL_NAME,error:"Settings UI pop err"},'error',0); }
  1580. },
  1581. show: function(){ if(!_settingsOverlay||!_settingsWindow)return;_settingsBackup = JSON.parse(JSON.stringify(_currentSettings));LocalizationService.updateActiveLocale(_currentSettings);this.populateWindow();applyThemeToElement(_settingsWindow, _currentSettings.theme);applyThemeToElement(_settingsOverlay, _currentSettings.theme);_settingsOverlay.style.display = 'flex';},
  1582. hide: function(isCancel = false){ if(!_settingsOverlay)return;ModalManager.resetEditStateGlobally();if(ModalManager.isModalOpen()) ModalManager.hide(true);_settingsOverlay.style.display = 'none';const messageBar = document.getElementById(IDS.SETTINGS_MESSAGE_BAR);if(messageBar) messageBar.style.display = 'none';if(isCancel && _settingsBackup && Object.keys(_settingsBackup).length > 0){ _currentSettings = JSON.parse(JSON.stringify(_settingsBackup));LocalizationService.updateActiveLocale(_currentSettings);this.populateWindow();_applySettingsToSidebar_cb(_currentSettings);_buildSidebarUI_cb();_initMenuCommands_cb();} else if(isCancel) { console.warn(`${LOG_PREFIX} SM: Cancelled, no backup to restore or backup was identical.`); }},
  1583. bindEvents: function(){
  1584. if(!_settingsWindow || _settingsWindow.dataset.eventsBound === 'true') return;
  1585. _settingsWindow.querySelector(`.${CSS.SETTINGS_CLOSE_BTN}`)?.addEventListener('click', () => this.hide(true));
  1586. _settingsWindow.querySelector(`.${CSS.CANCEL_BUTTON}`)?.addEventListener('click', () => this.hide(true));
  1587. _settingsWindow.querySelector(`.${CSS.SAVE_BUTTON}`)?.addEventListener('click', () => { this.save(); LocalizationService.updateActiveLocale(_currentSettings); _initMenuCommands_cb(); _buildSidebarUI_cb(); this.hide(false); });
  1588. _settingsWindow.querySelector(`.${CSS.RESET_BUTTON}`)?.addEventListener('click', () => this.reset());
  1589. const tabsContainer = _settingsWindow.querySelector(`.${CSS.SETTINGS_TABS}`);
  1590. if(tabsContainer){ tabsContainer.addEventListener('click', e => { const targetButton = e.target.closest(`.${CSS.TAB_BUTTON}`); if(targetButton && !targetButton.classList.contains(CSS.ACTIVE)){ ModalManager.resetEditStateGlobally(); const tabToActivate = targetButton.dataset[DATA_ATTR.TAB]; if(!tabToActivate) return; tabsContainer.querySelectorAll(`.${CSS.TAB_BUTTON}`).forEach(b => b.classList.remove(CSS.ACTIVE)); targetButton.classList.add(CSS.ACTIVE); _settingsWindow.querySelector(`.${CSS.SETTINGS_TAB_CONTENT}`)?.querySelectorAll(`.${CSS.TAB_PANE}`)?.forEach(p => p.classList.remove(CSS.ACTIVE)); _settingsWindow.querySelector(`.${CSS.SETTINGS_TAB_CONTENT} .${CSS.TAB_PANE}[data-${DATA_ATTR.TAB}="${tabToActivate}"]`)?.classList.add(CSS.ACTIVE); } }); }
  1591. _settingsWindow.dataset.eventsBound = 'true';
  1592. const customTabPane = _settingsWindow.querySelector(`#${IDS.TAB_PANE_CUSTOM}`);
  1593. if(customTabPane){ customTabPane.addEventListener('click', (e) => { const manageButton = e.target.closest(`button.${CSS.MANAGE_CUSTOM_BUTTON}`); if(manageButton){ const manageType = manageButton.dataset[DATA_ATTR.MANAGE_TYPE]; if(manageType){ ModalManager.openManageCustomOptions( manageType, _currentSettings, PREDEFINED_OPTIONS, (updatedItemsArray, newEnabledPredefs, itemsArrayKey, predefinedOptKey, customItemsMasterKey, isSortableMixed, manageTypeFromCallback) => { if (itemsArrayKey) { _currentSettings[itemsArrayKey] = updatedItemsArray; } if (predefinedOptKey && newEnabledPredefs) { if (!_currentSettings.enabledPredefinedOptions) _currentSettings.enabledPredefinedOptions = {}; _currentSettings.enabledPredefinedOptions[predefinedOptKey] = newEnabledPredefs; } _buildSidebarUI_cb(); } ); } } }); }
  1594. },
  1595. bindLiveUpdateEvents: function(){ if(!_settingsWindow)return; _settingsWindow.querySelectorAll('input[type="range"]').forEach(el=>{ el.removeEventListener('input',_lUH_internal); el.addEventListener('input',_lUH_internal); }); _settingsWindow.querySelectorAll('select, input[type="checkbox"]:not([data-section-id])').forEach(el=>{ if(_sEH_internal[el.id]){ el.removeEventListener('change',_lUH_internal); el.addEventListener('change',_lUH_internal); } }); },
  1596. bindFeaturesTabEvents: function() {
  1597. const featuresPane = _settingsWindow?.querySelector(`#${IDS.TAB_PANE_FEATURES}`); if (!featuresPane) return;
  1598. featuresPane.querySelectorAll(`input[type="checkbox"][data-${DATA_ATTR.SECTION_ID}]`).forEach(checkbox => { checkbox.removeEventListener('change', this._handleVisibleSectionChange); checkbox.addEventListener('change', this._handleVisibleSectionChange.bind(this)); });
  1599. const siteSearchCheckboxModeEl = featuresPane.querySelector(`#${IDS.SETTING_SITE_SEARCH_CHECKBOX_MODE}`);
  1600. if (siteSearchCheckboxModeEl && _sEH_internal[IDS.SETTING_SITE_SEARCH_CHECKBOX_MODE]) {
  1601. siteSearchCheckboxModeEl.removeEventListener('change', _lUH_internal);
  1602. siteSearchCheckboxModeEl.addEventListener('change', _lUH_internal);
  1603. }
  1604. const filetypeSearchCheckboxModeEl = featuresPane.querySelector(`#${IDS.SETTING_FILETYPE_SEARCH_CHECKBOX_MODE}`);
  1605. if (filetypeSearchCheckboxModeEl && _sEH_internal[IDS.SETTING_FILETYPE_SEARCH_CHECKBOX_MODE]) {
  1606. filetypeSearchCheckboxModeEl.removeEventListener('change', _lUH_internal);
  1607. filetypeSearchCheckboxModeEl.addEventListener('change', _lUH_internal);
  1608. }
  1609.  
  1610. const orderListElement = featuresPane.querySelector(`#${IDS.SIDEBAR_SECTION_ORDER_LIST}`);
  1611. if (orderListElement) { SectionOrderDragHandler.initialize(orderListElement, _currentSettings, () => { _renderSectionOrderList_ext_cb(_currentSettings); _buildSidebarUI_cb(); }); }
  1612. },
  1613. _handleVisibleSectionChange: function(e){ const target = e.target; const sectionId = target.getAttribute(`data-${DATA_ATTR.SECTION_ID}`); if (sectionId && _currentSettings.visibleSections.hasOwnProperty(sectionId)) { _currentSettings.visibleSections[sectionId] = target.checked; _finalizeSectionOrder_internal(_currentSettings, _currentSettings, _defaultSettingsRef); _renderSectionOrderList_ext_cb(_currentSettings); _buildSidebarUI_cb(); } },
  1614. };
  1615. return publicApi;
  1616. })();
  1617. const DragManager = (function() {
  1618. let _isDragging = false; let _dragStartX, _dragStartY, _sidebarStartX, _sidebarStartY;
  1619. let _sidebarElement, _handleElement; let _settingsManagerRef, _saveCallbackRef;
  1620. function _getEventCoordinates(e) { return (e.touches && e.touches.length > 0) ? { x: e.touches[0].clientX, y: e.touches[0].clientY } : { x: e.clientX, y: e.clientY }; }
  1621. function _startDrag(e) { const currentSettings = _settingsManagerRef.getCurrentSettings(); if (!currentSettings.draggableHandleEnabled || currentSettings.sidebarCollapsed || (e.type === 'mousedown' && e.button !== 0)) { return; } e.preventDefault(); _isDragging = true; const coords = _getEventCoordinates(e); _dragStartX = coords.x; _dragStartY = coords.y; _sidebarStartX = _sidebarElement.offsetLeft; _sidebarStartY = _sidebarElement.offsetTop; _sidebarElement.style.cursor = 'grabbing'; _sidebarElement.style.userSelect = 'none'; document.body.style.cursor = 'grabbing'; }
  1622. function _drag(e) { if (!_isDragging) return; e.preventDefault(); const coords = _getEventCoordinates(e); const dx = coords.x - _dragStartX; const dy = coords.y - _dragStartY; let newLeft = _sidebarStartX + dx; let newTop = _sidebarStartY + dy; const maxLeft = window.innerWidth - (_sidebarElement?.offsetWidth ?? 0); const maxTop = window.innerHeight - (_sidebarElement?.offsetHeight ?? 0); newLeft = Utils.clamp(newLeft, 0, maxLeft); newTop = Utils.clamp(newTop, MIN_SIDEBAR_TOP_POSITION, maxTop); if (_sidebarElement) { _sidebarElement.style.left = `${newLeft}px`; _sidebarElement.style.top = `${newTop}px`; } }
  1623. function _stopDrag() { if (_isDragging) { _isDragging = false; if (_sidebarElement) { _sidebarElement.style.cursor = 'default'; _sidebarElement.style.userSelect = ''; } document.body.style.cursor = ''; const currentSettings = _settingsManagerRef.getCurrentSettings(); if (!currentSettings.sidebarPosition) currentSettings.sidebarPosition = {}; currentSettings.sidebarPosition.left = _sidebarElement.offsetLeft; currentSettings.sidebarPosition.top = _sidebarElement.offsetTop; if (typeof _saveCallbackRef === 'function') { _saveCallbackRef('Drag Stop'); } } }
  1624. return { init: function(sidebarEl, handleEl, settingsMgr, saveCb) { _sidebarElement = sidebarEl; _handleElement = handleEl; _settingsManagerRef = settingsMgr; _saveCallbackRef = saveCb; if (_handleElement) { _handleElement.addEventListener('mousedown', _startDrag); _handleElement.addEventListener('touchstart', _startDrag, { passive: false }); } document.addEventListener('mousemove', _drag); document.addEventListener('touchmove', _drag, { passive: false }); document.addEventListener('mouseup', _stopDrag); document.addEventListener('touchend', _stopDrag); document.addEventListener('touchcancel', _stopDrag); }, setDraggable: function(isEnabled, sidebarEl, handleEl) { _sidebarElement = sidebarEl; _handleElement = handleEl; if (_handleElement) { _handleElement.style.display = isEnabled ? 'block' : 'none'; } } };
  1625. })();
  1626. const URLActionManager = (function() {
  1627. function _getURLObject() { try { return new URL(window.location.href); } catch (e) { console.error(`${LOG_PREFIX} Error creating URL object: `, e); return null; }}
  1628. function _navigateTo(url) { const urlString = url.toString(); window.location.href = urlString; }
  1629. function _setSearchParam(urlObj, paramName, value) { urlObj.searchParams.set(paramName, value); }
  1630. function _deleteSearchParam(urlObj, paramName) { urlObj.searchParams.delete(paramName); }
  1631. function _getTbsParts(urlObj) { const tbs = urlObj.searchParams.get('tbs'); return tbs ? tbs.split(',').filter(p => p.trim() !== '') : []; }
  1632. function _setTbsParam(urlObj, tbsPartsArray) { const newTbsValue = tbsPartsArray.join(','); if (newTbsValue) { _setSearchParam(urlObj, 'tbs', newTbsValue); } else { _deleteSearchParam(urlObj, 'tbs'); }}
  1633. return {
  1634. triggerResetFilters: function() {
  1635. try {
  1636. const u = _getURLObject(); if (!u) return;
  1637. const q = u.searchParams.get('q') || '';
  1638. const nP = new URLSearchParams();
  1639. let cQ = q.replace(/\s*\(\s*(?:(?:site|filetype):[\w.:()-]+(?:\s+OR\s+|$))+[^)]*\)\s*/gi, ' ');
  1640. cQ = cQ.replace(/\s*(?:site|filetype):[\w.:()-]+\s*/gi, ' ');
  1641. cQ = cQ.replace(/\s\s+/g, ' ').trim();
  1642.  
  1643. if (cQ) { nP.set('q', cQ); }
  1644. u.search = nP.toString();
  1645. _deleteSearchParam(u, 'tbs'); _deleteSearchParam(u, 'lr'); _deleteSearchParam(u, 'cr');
  1646. _deleteSearchParam(u, 'as_filetype'); _deleteSearchParam(u, 'as_occt');
  1647. _navigateTo(u);
  1648. } catch (e) {
  1649. NotificationManager.show('alert_error_resetting_filters', {}, 'error', 5000);
  1650. }
  1651. },
  1652. triggerToggleVerbatim: function() { try { const u = _getURLObject(); if (!u) return; let tP = _getTbsParts(u); const vP = 'li:1'; const iCA = tP.includes(vP); tP = tP.filter(p => p !== vP); if (!iCA) { tP.push(vP); } _setTbsParam(u, tP); _navigateTo(u); } catch (e) { NotificationManager.show('alert_error_toggling_verbatim', {}, 'error', 5000); }},
  1653. isPersonalizationActive: function() { try { const currentUrl = _getURLObject(); if (!currentUrl) { return true; } return currentUrl.searchParams.get('pws') !== '0'; } catch (e) { console.warn(`${LOG_PREFIX} [URLActionManager.isPersonalizationActive] Error checking personalization status:`, e); return true; } },
  1654. triggerTogglePersonalization: function() { try { const u = _getURLObject(); if (!u) { return; } const personalizationCurrentlyActive = URLActionManager.isPersonalizationActive(); if (personalizationCurrentlyActive) { _setSearchParam(u, 'pws', '0'); } else { _deleteSearchParam(u, 'pws'); } _navigateTo(u); } catch (e) { NotificationManager.show('alert_error_toggling_personalization', {}, 'error', 5000); console.error(`${LOG_PREFIX} [URLActionManager.triggerTogglePersonalization] Error:`, e); } },
  1655. applyFilter: function(type, value) { // Handles non-q-based filters and single 'as_filetype' which might contain OR
  1656. try {
  1657. const u = _getURLObject(); if (!u) return;
  1658. let tP = _getTbsParts(u);
  1659. let pTP;
  1660.  
  1661. const isTimeFilter = type === 'qdr';
  1662. const isStandaloneParam = ['lr', 'cr', 'as_occt'].includes(type);
  1663.  
  1664. if (isTimeFilter) {
  1665. pTP = tP.filter(p => !p.startsWith(`qdr:`) && !p.startsWith('cdr:') && !p.startsWith('cd_min:') && !p.startsWith('cd_max:'));
  1666. if (value !== '') pTP.push(`qdr:${value}`);
  1667. _setTbsParam(u, pTP);
  1668. } else if (isStandaloneParam) {
  1669. _deleteSearchParam(u, type);
  1670. if (value !== '' && !(type === 'as_occt' && value === 'any')) {
  1671. _setSearchParam(u, type, value);
  1672. }
  1673. // pTP = tP; // No change to tbs for these params
  1674. } else if (type === 'as_filetype') {
  1675. const filetypesToApply = Utils.parseCombinedValue(value);
  1676. if (filetypesToApply.length > 1) {
  1677. this.applyCombinedFiletypeSearch(filetypesToApply); // Delegate to combined if OR is present
  1678. return; // applyCombinedFiletypeSearch handles navigation
  1679. }
  1680. // Single filetype or empty (clear)
  1681. let currentQuery = u.searchParams.get('q') || '';
  1682. currentQuery = currentQuery.replace(/\s*\(\s*(?:filetype:[\w.:()-]+(?:\s+OR\s+|$))+[^)]*\)\s*/gi, ' ');
  1683. currentQuery = currentQuery.replace(/\s*filetype:[\w.:()-]+\s*/gi, ' ');
  1684. currentQuery = currentQuery.replace(/\s\s+/g, ' ').trim();
  1685.  
  1686. if (value !== '') { // value here is a single type after parsing or if it was single initially
  1687. _setSearchParam(u, 'q', (currentQuery + ` filetype:${filetypesToApply[0]}`).trim());
  1688. } else {
  1689. if(currentQuery) _setSearchParam(u, 'q', currentQuery);
  1690. else _deleteSearchParam(u, 'q');
  1691. }
  1692. _deleteSearchParam(u, 'as_filetype');
  1693. // pTP = tP; // No change to tbs
  1694. }
  1695. // For standalone and time filters, tbs might be modified, so set it.
  1696. // For as_filetype handled via q, tbs is not modified here.
  1697. if (isTimeFilter || isStandaloneParam) {
  1698. _setTbsParam(u, tP); // tP was modified for time, or not for standalone
  1699. }
  1700. _navigateTo(u);
  1701. } catch (e) {
  1702. NotificationManager.show('alert_error_applying_filter', { type: type, value: value }, 'error', 5000);
  1703. }
  1704. },
  1705. // applySiteSearch and applyCombinedFiletypeSearch expect an array of individual terms
  1706. applySiteSearch: function(siteCriteria) { // siteCriteria can be a string "siteA OR siteB" or an array ["siteA", "siteB"]
  1707. const sitesToSearch = Array.isArray(siteCriteria)
  1708. ? siteCriteria.flatMap(sc => Utils.parseCombinedValue(sc)) // If array, parse each element
  1709. : Utils.parseCombinedValue(siteCriteria); // If string, parse it
  1710. const uniqueSites = [...new Set(sitesToSearch.map(s => s.toLowerCase()))];
  1711.  
  1712.  
  1713. if (uniqueSites.length === 0) {
  1714. this.clearSiteSearch(); return;
  1715. }
  1716. try {
  1717. const u = _getURLObject(); if (!u) return;
  1718. let q = u.searchParams.get('q') || '';
  1719.  
  1720. q = q.replace(/\s*\(\s*(?:(?:site|filetype):[\w.:()-]+(?:\s+OR\s+|$))+[^)]*\)\s*/gi, ' ');
  1721. q = q.replace(/\s*(?:site|filetype):[\w.:()-]+\s*/gi, ' ');
  1722. q = q.replace(/\s\s+/g, ' ').trim();
  1723.  
  1724. let siteQueryPart = '';
  1725. if (uniqueSites.length === 1) {
  1726. siteQueryPart = `site:${uniqueSites[0]}`;
  1727. } else {
  1728. siteQueryPart = `(${uniqueSites.map(s => `site:${s}`).join(' OR ')})`;
  1729. }
  1730.  
  1731. const nQ = `${q} ${siteQueryPart}`.trim();
  1732. _setSearchParam(u, 'q', nQ);
  1733. _deleteSearchParam(u, 'tbs'); _deleteSearchParam(u, 'lr'); _deleteSearchParam(u, 'cr');
  1734. _deleteSearchParam(u, 'as_filetype'); _deleteSearchParam(u, 'as_occt');
  1735. _navigateTo(u);
  1736. } catch (e) {
  1737. const siteForError = uniqueSites.join(', ');
  1738. NotificationManager.show('alert_error_applying_site_search', { site: siteForError }, 'error', 5000);
  1739. }
  1740. },
  1741. applyCombinedFiletypeSearch: function(filetypeCriteria) { // filetypeCriteria can be a string "typeA OR typeB" or an array ["typeA", "typeB"]
  1742. const filetypesToSearch = Array.isArray(filetypeCriteria)
  1743. ? filetypeCriteria.flatMap(fc => Utils.parseCombinedValue(fc))
  1744. : Utils.parseCombinedValue(filetypeCriteria);
  1745. const uniqueFiletypes = [...new Set(filetypesToSearch.map(f => f.toLowerCase()))];
  1746.  
  1747. if (uniqueFiletypes.length === 0) {
  1748. this.clearFiletypeSearch();
  1749. return;
  1750. }
  1751. try {
  1752. const u = _getURLObject(); if (!u) return;
  1753. let q = u.searchParams.get('q') || '';
  1754.  
  1755. q = q.replace(/\s*\(\s*(?:(?:filetype|site):[\w.:()-]+(?:\s+OR\s+|$))+[^)]*\)\s*/gi, ' ');
  1756. q = q.replace(/\s*(?:filetype|site):[\w.:()-]+\s*/gi, ' ');
  1757. q = q.replace(/\s\s+/g, ' ').trim();
  1758.  
  1759. let filetypeQueryPart = '';
  1760. if (uniqueFiletypes.length === 1) {
  1761. filetypeQueryPart = `filetype:${uniqueFiletypes[0]}`;
  1762. } else {
  1763. filetypeQueryPart = `(${uniqueFiletypes.map(ft => `filetype:${ft}`).join(' OR ')})`;
  1764. }
  1765.  
  1766. const nQ = `${q} ${filetypeQueryPart}`.trim();
  1767. _setSearchParam(u, 'q', nQ);
  1768. _deleteSearchParam(u, 'as_filetype');
  1769. _navigateTo(u);
  1770. } catch (e) {
  1771. const ftForError = uniqueFiletypes.join(', ');
  1772. NotificationManager.show('alert_error_applying_filter', { type: 'filetype (combined)', value: ftForError }, 'error', 5000);
  1773. }
  1774. },
  1775. clearSiteSearch: function() {
  1776. try {
  1777. const u = _getURLObject(); if (!u) return;
  1778. const q = u.searchParams.get('q') || '';
  1779. let nQ = q.replace(/\s*\(\s*(?:site:[\w.:()-]+(?:\s+OR\s+|$))+[^)]*\)\s*/gi, ' ');
  1780. nQ = nQ.replace(/\s*site:[\w.:()-]+\s*/gi, ' ');
  1781. nQ = nQ.replace(/\s\s+/g, ' ').trim();
  1782. if (nQ) { _setSearchParam(u, 'q', nQ); } else { _deleteSearchParam(u, 'q'); }
  1783. _navigateTo(u);
  1784. } catch (e) {
  1785. NotificationManager.show('alert_error_clearing_site_search', {}, 'error', 5000);
  1786. }
  1787. },
  1788. clearFiletypeSearch: function() {
  1789. try {
  1790. const u = _getURLObject(); if (!u) return;
  1791. let q = u.searchParams.get('q') || '';
  1792. q = q.replace(/\s*\(\s*(?:filetype:[\w.:()-]+(?:\s+OR\s+|$))+[^)]*\)\s*/gi, ' ');
  1793. q = q.replace(/\s*filetype:[\w.:()-]+\s*/gi, ' ');
  1794. q = q.replace(/\s\s+/g, ' ').trim();
  1795. if (q) { _setSearchParam(u, 'q', q); } else { _deleteSearchParam(u, 'q'); }
  1796. _deleteSearchParam(u, 'as_filetype');
  1797. _navigateTo(u);
  1798. } catch (e) {
  1799. NotificationManager.show('alert_error_applying_filter', { type: 'filetype', value: '(clear)' }, 'error', 5000);
  1800. }
  1801. },
  1802. isVerbatimActive: function() { try { const currentUrl = _getURLObject(); if (!currentUrl) return false; return /li:1/.test(currentUrl.searchParams.get('tbs') || ''); } catch (e) { console.warn(`${LOG_PREFIX} Error checking verbatim status:`, e); return false; }},
  1803. applyDateRange: function(dateMinStr, dateMaxStr) { try { const url = _getURLObject(); if (!url) return; let dateTbsPart = 'cdr:1'; if (dateMinStr) { const [y, m, d] = dateMinStr.split('-'); dateTbsPart += `,cd_min:${m}/${d}/${y}`; } if (dateMaxStr) { const [y, m, d] = dateMaxStr.split('-'); dateTbsPart += `,cd_max:${m}/${d}/${y}`; } let tbsParts = _getTbsParts(url); let preservedTbsParts = tbsParts.filter(p => !p.startsWith('qdr:') && !p.startsWith('cdr:') && !p.startsWith('cd_min:') && !p.startsWith('cd_max:')); let newTbsParts = [...preservedTbsParts, dateTbsPart]; _setTbsParam(url, newTbsParts); _navigateTo(url); } catch (e) { NotificationManager.show('alert_error_applying_date', {}, 'error', 5000); }}
  1804. };
  1805. })();
  1806.  
  1807. function addGlobalStyles() { if (typeof window.GSCS_Namespace !== 'undefined' && typeof window.GSCS_Namespace.stylesText === 'string') { const cleanedCSS = window.GSCS_Namespace.stylesText.replace(/\/\*[\s\S]*?\*\/|([^\\:]|^)\/\/.*$/gm, '$1').replace(/\n\s*\n/g, '\n'); GM_addStyle(cleanedCSS); } else { console.error(`${LOG_PREFIX} CRITICAL: CSS styles provider not found.`); if (typeof IDS !== 'undefined' && IDS.SIDEBAR) { GM_addStyle(`#${IDS.SIDEBAR} { border: 3px dashed red !important; padding: 15px !important; background: white !important; color: red !important; } #${IDS.SIDEBAR}::before { content: "Error: CSS Missing!"; }`);} } }
  1808. function setupSystemThemeListener() { if (systemThemeMediaQuery && systemThemeMediaQuery._sidebarThemeListener) { try { systemThemeMediaQuery.removeEventListener('change', systemThemeMediaQuery._sidebarThemeListener); } catch (e) {} systemThemeMediaQuery._sidebarThemeListener = null; } if (window.matchMedia) { systemThemeMediaQuery = window.matchMedia('(prefers-color-scheme: dark)'); const listener = () => { const cs = SettingsManager.getCurrentSettings(); if (sidebar && cs.theme === 'system') { applyThemeToElement(sidebar, 'system'); } }; systemThemeMediaQuery.addEventListener('change', listener); systemThemeMediaQuery._sidebarThemeListener = listener; } }
  1809. function buildSidebarSkeleton() { sidebar = document.createElement('div'); sidebar.id = IDS.SIDEBAR; const header = document.createElement('div'); header.classList.add(CSS.SIDEBAR_HEADER); const collapseBtn = document.createElement('button'); collapseBtn.id = IDS.COLLAPSE_BUTTON; collapseBtn.innerHTML = SVG_ICONS.chevronLeft; collapseBtn.title = _('sidebar_collapse_title'); const dragHandle = document.createElement('div'); dragHandle.classList.add(CSS.DRAG_HANDLE); dragHandle.title = _('sidebar_drag_title'); const settingsBtn = document.createElement('button'); settingsBtn.id = IDS.SETTINGS_BUTTON; settingsBtn.classList.add(CSS.SETTINGS_BUTTON); settingsBtn.innerHTML = SVG_ICONS.settings; settingsBtn.title = _('sidebar_settings_title'); header.appendChild(collapseBtn); header.appendChild(dragHandle); header.appendChild(settingsBtn); sidebar.appendChild(header); document.body.appendChild(sidebar); }
  1810. function applySettings(settingsToApply) { if (!sidebar) return; const currentSettings = settingsToApply || SettingsManager.getCurrentSettings(); let targetTop = currentSettings.sidebarPosition.top; targetTop = Math.max(MIN_SIDEBAR_TOP_POSITION, targetTop); sidebar.style.left = `${currentSettings.sidebarPosition.left}px`; sidebar.style.top = `${targetTop}px`; sidebar.style.setProperty('--sidebar-font-base-size', `${currentSettings.fontSize}px`); sidebar.style.setProperty('--sidebar-header-icon-base-size', `${currentSettings.headerIconSize}px`); sidebar.style.setProperty('--sidebar-spacing-multiplier', currentSettings.verticalSpacingMultiplier); if (!currentSettings.sidebarCollapsed) { sidebar.style.width = `${currentSettings.sidebarWidth}px`; } else { sidebar.style.width = '40px';} applyThemeToElement(sidebar, currentSettings.theme); if (sidebar._hoverListeners) { sidebar.removeEventListener('mouseenter', sidebar._hoverListeners.enter); sidebar.removeEventListener('mouseleave', sidebar._hoverListeners.leave); sidebar._hoverListeners = null; sidebar.style.opacity = '1';} if (currentSettings.hoverMode && !currentSettings.sidebarCollapsed) { const idleOpacityValue = currentSettings.idleOpacity; sidebar.style.opacity = idleOpacityValue.toString(); const enterL = () => { if (!currentSettings.sidebarCollapsed) sidebar.style.opacity = '1'; }; const leaveL = () => { if (!currentSettings.sidebarCollapsed) sidebar.style.opacity = idleOpacityValue.toString(); }; sidebar.addEventListener('mouseenter', enterL); sidebar.addEventListener('mouseleave', leaveL); sidebar._hoverListeners = { enter: enterL, leave: leaveL }; } else { sidebar.style.opacity = '1'; } applySidebarCollapseVisuals(currentSettings.sidebarCollapsed); }
  1811. function _parseTimeValueToMinutes(timeValue) { if (!timeValue || typeof timeValue !== 'string') return Infinity; const match = timeValue.match(/^([hdwmy])(\d*)$/i); if (!match) return Infinity; const unit = match[1].toLowerCase(); const number = parseInt(match[2] || '1', 10); if (isNaN(number)) return Infinity; switch (unit) { case 'h': return number * 60; case 'd': return number * 24 * 60; case 'w': return number * 7 * 24 * 60; case 'm': return number * 30 * 24 * 60; case 'y': return number * 365 * 24 * 60; default: return Infinity; } }
  1812.  
  1813. function _prepareFilterOptions(sectionId, scriptDefinedOptions, currentSettings, predefinedOptionsSource) {
  1814. const finalOptions = [];
  1815. const tempAddedValues = new Set();
  1816. const sectionDef = ALL_SECTION_DEFINITIONS.find(s => s.id === sectionId);
  1817. if (!sectionDef) return [];
  1818.  
  1819. const isSortableMixedType = sectionDef.displayItemsKey && Array.isArray(currentSettings[sectionDef.displayItemsKey]);
  1820. const isFiletypeCheckboxModeActive = sectionId === 'sidebar-section-filetype' && currentSettings.enableFiletypeCheckboxMode;
  1821. const isSiteCheckboxModeActive = sectionId === 'sidebar-section-site-search' && currentSettings.enableSiteSearchCheckboxMode;
  1822.  
  1823. // 1. Add "Any" type script-defined options (value === '') for sections where it's part of the sortable list
  1824. if (scriptDefinedOptions) {
  1825. scriptDefinedOptions.forEach(opt => {
  1826. if (opt && typeof opt.textKey === 'string' && typeof opt.v === 'string' && opt.v === '') {
  1827. // Only add "Any" to finalOptions if it's NOT filetype/site in checkbox mode (those have dedicated clear divs)
  1828. if (!((isFiletypeCheckboxModeActive && sectionId === 'sidebar-section-filetype') ||
  1829. (isSiteCheckboxModeActive && sectionId === 'sidebar-section-site-search'))) {
  1830. const translatedText = (sectionId === 'sidebar-section-site-search') ? _('filter_any_site') : _(opt.textKey);
  1831. finalOptions.push({ text: translatedText, value: opt.v, originalText: translatedText, isCustom: false, isAnyOption: true });
  1832. tempAddedValues.add(opt.v);
  1833. }
  1834. }
  1835. });
  1836. }
  1837.  
  1838.  
  1839. if (isSortableMixedType) { // For Language, Country
  1840. const displayItems = currentSettings[sectionDef.displayItemsKey] || [];
  1841. displayItems.forEach(item => {
  1842. if (!tempAddedValues.has(item.value)) {
  1843. let displayText = item.text;
  1844. if (item.type === 'predefined' && item.originalKey) {
  1845. displayText = _(item.originalKey);
  1846. if (sectionId === 'sidebar-section-country') {
  1847. const parsed = Utils.parseIconAndText(displayText);
  1848. displayText = `${parsed.icon} ${parsed.text}`.trim();
  1849. }
  1850. }
  1851. finalOptions.push({ text: displayText, value: item.value, originalText: displayText, isCustom: item.type === 'custom' });
  1852. tempAddedValues.add(item.value);
  1853. }
  1854. });
  1855. } else { // For Time, Filetype, Occurrence (and Site Search if not checkbox mode, though site search has its own populate)
  1856. const predefinedKey = sectionDef.predefinedOptionsKey;
  1857. const customKey = sectionDef.customItemsKey;
  1858. const predefinedOptsFromSource = predefinedOptionsSource && predefinedKey ? (predefinedOptionsSource[predefinedKey] || []) : [];
  1859. const customOptsFromSettings = customKey ? (currentSettings[customKey] || []) : [];
  1860. let enabledPredefinedSystemVals;
  1861.  
  1862. if (isFiletypeCheckboxModeActive && sectionId === 'sidebar-section-filetype') {
  1863. enabledPredefinedSystemVals = currentSettings.enabledPredefinedOptions[predefinedKey] || [];
  1864. } else {
  1865. enabledPredefinedSystemVals = predefinedKey ? (currentSettings.enabledPredefinedOptions[predefinedKey] || []) : [];
  1866. }
  1867.  
  1868. const itemsForThisSection = [];
  1869. const enabledSet = new Set(enabledPredefinedSystemVals);
  1870.  
  1871. if (Array.isArray(predefinedOptsFromSource)) {
  1872. predefinedOptsFromSource.forEach(opt => {
  1873. if (opt && typeof opt.textKey === 'string' && typeof opt.value === 'string' && enabledSet.has(opt.value) && !tempAddedValues.has(opt.value)) {
  1874. const translatedText = _(opt.textKey);
  1875. itemsForThisSection.push({ text: translatedText, value: opt.value, originalText: translatedText, isCustom: false });
  1876. }
  1877. });
  1878. }
  1879.  
  1880. const validCustomOptions = Array.isArray(customOptsFromSettings) ? customOptsFromSettings.filter(cOpt => cOpt && typeof cOpt.text === 'string' && typeof cOpt.value === 'string') : [];
  1881. validCustomOptions.forEach(opt => {
  1882. // For custom items, 'value' can now contain OR. The 'isCustom' flag helps differentiate.
  1883. if (!tempAddedValues.has(opt.value)){ // Check against tempAddedValues to avoid re-adding scriptDefined "Any"
  1884. itemsForThisSection.push({ text: opt.text, value: opt.value, originalText: opt.text, isCustom: true });
  1885. }
  1886. });
  1887.  
  1888. itemsForThisSection.forEach(opt => {
  1889. if (!tempAddedValues.has(opt.value)){
  1890. finalOptions.push(opt);
  1891. tempAddedValues.add(opt.value);
  1892. }
  1893. });
  1894. }
  1895.  
  1896. if (scriptDefinedOptions) {
  1897. scriptDefinedOptions.forEach(opt => {
  1898. if (opt && typeof opt.textKey === 'string' && typeof opt.v === 'string' && opt.v !== '' && !tempAddedValues.has(opt.v)) {
  1899. const translatedText = _(opt.textKey);
  1900. finalOptions.push({ text: translatedText, value: opt.v, originalText: translatedText, isCustom: false });
  1901. tempAddedValues.add(opt.v);
  1902. }
  1903. });
  1904. }
  1905.  
  1906. let anyOptionToSortSeparately = null;
  1907. const anyOptionIdx = finalOptions.findIndex(opt => opt.isAnyOption === true);
  1908.  
  1909. if (anyOptionIdx !== -1) {
  1910. anyOptionToSortSeparately = finalOptions.splice(anyOptionIdx, 1)[0];
  1911. }
  1912.  
  1913. finalOptions.sort((a, b) => {
  1914. const isTimeSection = (sectionId === 'sidebar-section-time');
  1915. if (isTimeSection) {
  1916. const timeA = _parseTimeValueToMinutes(a.value);
  1917. const timeB = _parseTimeValueToMinutes(b.value);
  1918. if (timeA !== Infinity || timeB !== Infinity) {
  1919. if (timeA !== timeB) return timeA - timeB;
  1920. }
  1921. }
  1922. const sTA = a.originalText || a.text;
  1923. const sTB = b.originalText || b.text;
  1924. const sL = LocalizationService.getCurrentLocale() === 'en' ? undefined : LocalizationService.getCurrentLocale();
  1925. return sTA.localeCompare(sTB, sL, { numeric: true, sensitivity: 'base' });
  1926. });
  1927.  
  1928. if (anyOptionToSortSeparately) {
  1929. finalOptions.unshift(anyOptionToSortSeparately);
  1930. }
  1931. return finalOptions;
  1932. }
  1933.  
  1934. function _createFilterOptionElement(optionData, filterParam, isCountrySection, countryDisplayMode) { const optionElement = document.createElement('div'); optionElement.classList.add(CSS.FILTER_OPTION); const displayText = optionData.text; if (isCountrySection) { const { icon, text: countryTextOnly } = Utils.parseIconAndText(displayText); switch (countryDisplayMode) { case 'textOnly': optionElement.textContent = countryTextOnly || displayText; break; case 'iconOnly': if (icon) { optionElement.innerHTML = `<span class="country-icon-container">${icon}</span>`; } else { optionElement.textContent = countryTextOnly || displayText; } break; case 'iconAndText': default: if (icon) { const textPart = countryTextOnly || displayText.substring(icon.length).trim(); optionElement.innerHTML = `<span class="country-icon-container">${icon}</span>${textPart}`; } else { optionElement.textContent = displayText; } break; } } else { optionElement.textContent = displayText; } optionElement.title = `${displayText} (${filterParam}=${optionData.value || _('filter_clear_tooltip_suffix')})`; optionElement.dataset[DATA_ATTR.FILTER_TYPE] = filterParam; optionElement.dataset[DATA_ATTR.FILTER_VALUE] = optionData.value; return optionElement; }
  1935. function buildSidebarUI() { if (!sidebar) { console.error("Sidebar element not ready for buildSidebarUI"); return; } const currentSettings = SettingsManager.getCurrentSettings(); const header = sidebar.querySelector(`.${CSS.SIDEBAR_HEADER}`); if (!header) { console.error("Sidebar header not found in buildSidebarUI"); return; } sidebar.querySelectorAll(`#${IDS.FIXED_TOP_BUTTONS}, .${CSS.SIDEBAR_CONTENT_WRAPPER}`).forEach(el => el.remove()); header.querySelectorAll(`.${CSS.HEADER_BUTTON}:not(#${IDS.SETTINGS_BUTTON}):not(#${IDS.COLLAPSE_BUTTON}), a.${CSS.HEADER_BUTTON}`).forEach(el => el.remove()); const rBL = currentSettings.resetButtonLocation; const vBL = currentSettings.verbatimButtonLocation; const aSL = currentSettings.advancedSearchLinkLocation; const pznBL = currentSettings.personalizationButtonLocation; const settingsButtonRef = header.querySelector(`#${IDS.SETTINGS_BUTTON}`); _buildSidebarHeaderControls(header, settingsButtonRef, rBL, vBL, aSL, pznBL, _createAdvancedSearchElementHTML, _createPersonalizationButtonHTML, currentSettings); const fixedTopControlsContainer = _buildSidebarFixedTopControls(rBL, vBL, aSL, pznBL, _createAdvancedSearchElementHTML, _createPersonalizationButtonHTML, currentSettings); if (fixedTopControlsContainer) { header.after(fixedTopControlsContainer); } const contentWrapper = document.createElement('div'); contentWrapper.classList.add(CSS.SIDEBAR_CONTENT_WRAPPER); const sectionDefinitionsMap = new Map(ALL_SECTION_DEFINITIONS.map(def => [def.id, def])); const sectionsFragment = _buildSidebarSections(sectionDefinitionsMap, rBL, vBL, aSL, pznBL, _createAdvancedSearchElementHTML, _createPersonalizationButtonHTML, currentSettings, PREDEFINED_OPTIONS); contentWrapper.appendChild(sectionsFragment); sidebar.appendChild(contentWrapper); _initializeSidebarEventListenersAndStates(); }
  1936. function _buildSidebarSections(sectionDefinitionMap, rBL, vBL, aSL, pznBL, createAdvancedSearchElementFn, createPersonalizationButtonFn, currentSettings, PREDEFINED_OPTIONS_REF) { const contentFragment = document.createDocumentFragment(); currentSettings.sidebarSectionOrder.forEach(sectionId => { if (!currentSettings.visibleSections[sectionId]) return; const sectionData = sectionDefinitionMap.get(sectionId); if (!sectionData) { console.warn(`${LOG_PREFIX} No definition for section ID: ${sectionId}`); return; } let sectionElement = null; const sectionTitleKey = sectionData.titleKey; const sectionIdForDisplay = sectionData.id; switch (sectionData.type) { case 'filter': sectionElement = createFilterSection(sectionIdForDisplay, sectionTitleKey, sectionData.scriptDefined, sectionData.param, currentSettings, PREDEFINED_OPTIONS_REF, currentSettings.countryDisplayMode); break; case 'filetype': sectionElement = _createFiletypeSectionElement(sectionIdForDisplay, sectionTitleKey, sectionData.scriptDefined, sectionData.param, currentSettings, PREDEFINED_OPTIONS_REF); break; case 'date': sectionElement = _createDateSectionElement(sectionIdForDisplay, sectionTitleKey); break; case 'site': sectionElement = _createSiteSearchSectionElement(sectionIdForDisplay, sectionTitleKey, currentSettings.favoriteSites, currentSettings.enableSiteSearchCheckboxMode); break; case 'tools': sectionElement = _createToolsSectionElement( sectionIdForDisplay, sectionTitleKey, rBL, vBL, aSL, pznBL, createAdvancedSearchElementFn, createPersonalizationButtonFn ); break; default: console.warn(`${LOG_PREFIX} Unknown section type: ${sectionData.type} for ID: ${sectionIdForDisplay}`); break; } if (sectionElement) contentFragment.appendChild(sectionElement); }); return contentFragment; }
  1937. function createFilterSection(id, titleKey, scriptDefinedOptions, filterParam, currentSettings, predefinedOptionsSource, countryDisplayMode) { if (!sidebar) return null; const { section, sectionContent, sectionTitle } = _createSectionShell(id, titleKey); sectionTitle.textContent = _(titleKey); const fragment = document.createDocumentFragment(); const isCountrySection = (id === 'sidebar-section-country'); const combinedOptions = _prepareFilterOptions(id, scriptDefinedOptions, currentSettings, predefinedOptionsSource); combinedOptions.forEach(option => { fragment.appendChild(_createFilterOptionElement(option, filterParam, isCountrySection, countryDisplayMode)); }); sectionContent.innerHTML = ''; sectionContent.appendChild(fragment); if (!sectionContent.dataset.filterClickListenerAttached) { sectionContent.addEventListener('click', function(event) { const target = event.target.closest(`.${CSS.FILTER_OPTION}`); if (target && target.classList.contains(CSS.FILTER_OPTION)) { event.preventDefault(); const clickedFilterType = target.dataset[DATA_ATTR.FILTER_TYPE]; const clickedFilterValue = target.dataset[DATA_ATTR.FILTER_VALUE]; if (typeof clickedFilterType !== 'undefined' && typeof clickedFilterValue !== 'undefined') { this.querySelectorAll(`.${CSS.FILTER_OPTION}`).forEach(opt => opt.classList.remove(CSS.SELECTED)); target.classList.add(CSS.SELECTED); if (clickedFilterValue === '' || (clickedFilterType === 'as_occt' && clickedFilterValue === 'any') ) { const defaultVal = (clickedFilterType === 'as_occt') ? 'any' : ''; const anyOpt = this.querySelector(`.${CSS.FILTER_OPTION}[data-${DATA_ATTR.FILTER_VALUE}="${defaultVal}"]`); if (anyOpt) anyOpt.classList.add(CSS.SELECTED); } URLActionManager.applyFilter(clickedFilterType, clickedFilterValue); } } }); sectionContent.dataset.filterClickListenerAttached = 'true'; } return section; }
  1938.  
  1939. function _createSiteSearchSectionElement(sectionId, titleKey, favoriteSites, checkboxModeEnabled) {
  1940. const { section, sectionContent, sectionTitle } = _createSectionShell(sectionId, titleKey);
  1941. sectionTitle.textContent = _(titleKey);
  1942. populateSiteSearchList(sectionContent, favoriteSites, checkboxModeEnabled);
  1943. return section;
  1944. }
  1945.  
  1946. function populateSiteSearchList(sectionContentElement, favoriteSitesArray, checkboxModeEnabled) {
  1947. if (!sectionContentElement) { console.error("Site search section content element missing"); return; }
  1948. sectionContentElement.innerHTML = '';
  1949.  
  1950. const sites = Array.isArray(favoriteSitesArray) ? favoriteSitesArray : [];
  1951. const listFragment = document.createDocumentFragment();
  1952.  
  1953. const clearOptDiv = document.createElement('div');
  1954. clearOptDiv.classList.add(CSS.FILTER_OPTION);
  1955. clearOptDiv.id = IDS.CLEAR_SITE_SEARCH_OPTION;
  1956. clearOptDiv.title = _('tooltip_clear_site_search');
  1957. clearOptDiv.textContent = _('filter_any_site');
  1958. clearOptDiv.dataset[DATA_ATTR.FILTER_TYPE] = 'site_clear'; // Special type for click handler
  1959. sectionContentElement.appendChild(clearOptDiv);
  1960.  
  1961. const listElement = document.createElement('ul');
  1962. listElement.classList.add(CSS.CUSTOM_LIST);
  1963. if (checkboxModeEnabled) {
  1964. listElement.classList.add('checkbox-mode-enabled');
  1965. }
  1966.  
  1967. sites.forEach((site, index) => {
  1968. if (site?.text && site?.url) {
  1969. const li = document.createElement('li');
  1970. const siteValue = site.url;
  1971.  
  1972. if (checkboxModeEnabled) {
  1973. const checkbox = document.createElement('input');
  1974. checkbox.type = 'checkbox';
  1975. checkbox.id = `site-cb-${index}-${Date.now()}`; // Ensure unique ID
  1976. checkbox.value = siteValue;
  1977. checkbox.classList.add(CSS.SITE_SEARCH_ITEM_CHECKBOX);
  1978. checkbox.dataset[DATA_ATTR.SITE_URL] = siteValue;
  1979. li.appendChild(checkbox);
  1980. }
  1981.  
  1982. const opt = document.createElement(checkboxModeEnabled ? 'label' : 'div');
  1983. if (checkboxModeEnabled) {
  1984. opt.htmlFor = `site-cb-${index}-${Date.now()}`; // Ensure matches checkbox ID
  1985. } else {
  1986. opt.classList.add(CSS.FILTER_OPTION);
  1987. }
  1988. opt.dataset[DATA_ATTR.SITE_URL] = siteValue;
  1989. opt.title = _('tooltip_site_search', { siteUrl: siteValue.replace(/\s+OR\s+/gi, ', ') });
  1990. opt.textContent = site.text;
  1991. li.appendChild(opt);
  1992. listFragment.appendChild(li);
  1993. }
  1994. });
  1995. listElement.appendChild(listFragment);
  1996. sectionContentElement.appendChild(listElement);
  1997.  
  1998. if (checkboxModeEnabled) {
  1999. let applyButton = sectionContentElement.querySelector(`#${IDS.APPLY_SELECTED_SITES_BUTTON}`);
  2000. if (!applyButton) {
  2001. applyButton = document.createElement('button');
  2002. applyButton.id = IDS.APPLY_SELECTED_SITES_BUTTON;
  2003. applyButton.classList.add(CSS.TOOL_BUTTON, CSS.APPLY_SITES_BUTTON);
  2004. applyButton.textContent = _('tool_apply_selected_sites');
  2005. sectionContentElement.appendChild(applyButton);
  2006. }
  2007. applyButton.disabled = true;
  2008. applyButton.style.display = 'none';
  2009. }
  2010.  
  2011. if (!sectionContentElement.dataset.siteSearchClickListenerAttached) {
  2012. sectionContentElement.dataset.siteSearchClickListenerAttached = 'true';
  2013. sectionContentElement.addEventListener('click', (event) => {
  2014. const target = event.target;
  2015. const currentSettings = SettingsManager.getCurrentSettings();
  2016. const isCheckboxMode = currentSettings.enableSiteSearchCheckboxMode;
  2017. const clearSiteOpt = target.closest(`#${IDS.CLEAR_SITE_SEARCH_OPTION}`);
  2018.  
  2019. if (clearSiteOpt) {
  2020. URLActionManager.clearSiteSearch();
  2021. sectionContentElement.querySelectorAll(`.${CSS.FILTER_OPTION}.${CSS.SELECTED}, label.${CSS.SELECTED}`).forEach(o => o.classList.remove(CSS.SELECTED));
  2022. clearSiteOpt.classList.add(CSS.SELECTED);
  2023. if (isCheckboxMode) {
  2024. sectionContentElement.querySelectorAll(`input[type="checkbox"].${CSS.SITE_SEARCH_ITEM_CHECKBOX}`).forEach(cb => cb.checked = false);
  2025. _updateApplySitesButtonState(sectionContentElement);
  2026. }
  2027. } else if (isCheckboxMode) {
  2028. const labelElement = target.closest('label');
  2029. if (labelElement && labelElement.dataset[DATA_ATTR.SITE_URL]) {
  2030. event.preventDefault();
  2031. const siteUrlOrCombined = labelElement.dataset[DATA_ATTR.SITE_URL];
  2032. sectionContentElement.querySelectorAll(`input[type="checkbox"].${CSS.SITE_SEARCH_ITEM_CHECKBOX}`).forEach(cb => {
  2033. const correspondingLabel = sectionContentElement.querySelector(`label[for="${cb.id}"]`);
  2034. cb.checked = (cb.value === siteUrlOrCombined);
  2035. if(correspondingLabel) correspondingLabel.classList.toggle(CSS.SELECTED, cb.checked);
  2036. });
  2037. URLActionManager.applySiteSearch(siteUrlOrCombined);
  2038. _updateApplySitesButtonState(sectionContentElement);
  2039. sectionContentElement.querySelector(`#${IDS.CLEAR_SITE_SEARCH_OPTION}`)?.classList.remove(CSS.SELECTED);
  2040. }
  2041. } else {
  2042. const siteOptionDiv = target.closest(`div.${CSS.FILTER_OPTION}:not(#${IDS.CLEAR_SITE_SEARCH_OPTION})`);
  2043. if (siteOptionDiv && siteOptionDiv.dataset[DATA_ATTR.SITE_URL]) {
  2044. const siteUrlOrCombined = siteOptionDiv.dataset[DATA_ATTR.SITE_URL];
  2045. sectionContentElement.querySelectorAll(`.${CSS.FILTER_OPTION}.${CSS.SELECTED}`).forEach(o => o.classList.remove(CSS.SELECTED));
  2046. URLActionManager.applySiteSearch(siteUrlOrCombined);
  2047. siteOptionDiv.classList.add(CSS.SELECTED);
  2048. sectionContentElement.querySelector(`#${IDS.CLEAR_SITE_SEARCH_OPTION}`)?.classList.remove(CSS.SELECTED);
  2049. }
  2050. }
  2051. });
  2052.  
  2053. if (checkboxModeEnabled) {
  2054. sectionContentElement.addEventListener('change', (event) => {
  2055. if (event.target.matches(`input[type="checkbox"].${CSS.SITE_SEARCH_ITEM_CHECKBOX}`)) {
  2056. _updateApplySitesButtonState(sectionContentElement);
  2057. const label = sectionContentElement.querySelector(`label[for="${event.target.id}"]`);
  2058. if (label) label.classList.toggle(CSS.SELECTED, event.target.checked);
  2059. if (event.target.checked) {
  2060. sectionContentElement.querySelector(`#${IDS.CLEAR_SITE_SEARCH_OPTION}`)?.classList.remove(CSS.SELECTED);
  2061. }
  2062. }
  2063. });
  2064. const applyBtn = sectionContentElement.querySelector(`#${IDS.APPLY_SELECTED_SITES_BUTTON}`);
  2065. if(applyBtn && !applyBtn.dataset[DATA_ATTR.LISTENER_ATTACHED]){
  2066. applyBtn.dataset[DATA_ATTR.LISTENER_ATTACHED] = 'true';
  2067. applyBtn.addEventListener('click', () => {
  2068. const selectedValuesFromCheckboxes = [];
  2069. sectionContentElement.querySelectorAll(`input[type="checkbox"].${CSS.SITE_SEARCH_ITEM_CHECKBOX}:checked`).forEach(cb => {
  2070. selectedValuesFromCheckboxes.push(cb.value);
  2071. });
  2072. if (selectedValuesFromCheckboxes.length > 0) {
  2073. URLActionManager.applySiteSearch(selectedValuesFromCheckboxes);
  2074. sectionContentElement.querySelector(`#${IDS.CLEAR_SITE_SEARCH_OPTION}`)?.classList.remove(CSS.SELECTED);
  2075. }
  2076. });
  2077. }
  2078. }
  2079. }
  2080. }
  2081.  
  2082. function _createFiletypeSectionElement(sectionId, titleKey, scriptDefinedOptions, filterParam, currentSettings, predefinedOptionsSource) {
  2083. const { section, sectionContent, sectionTitle } = _createSectionShell(sectionId, titleKey);
  2084. sectionTitle.textContent = _(titleKey);
  2085. populateFiletypeList(sectionContent, scriptDefinedOptions, currentSettings, predefinedOptionsSource, filterParam);
  2086. return section;
  2087. }
  2088.  
  2089. function populateFiletypeList(sectionContentElement, scriptDefinedOpts, currentSettings, predefinedOptsSource, filterParam) {
  2090. if (!sectionContentElement) { console.error("Filetype section content element missing"); return; }
  2091. sectionContentElement.innerHTML = '';
  2092.  
  2093. const checkboxModeEnabled = currentSettings.enableFiletypeCheckboxMode;
  2094. const combinedOptions = _prepareFilterOptions('sidebar-section-filetype', scriptDefinedOpts, currentSettings, predefinedOptsSource);
  2095. const listFragment = document.createDocumentFragment(); // For LIs
  2096.  
  2097. const clearOptDiv = document.createElement('div');
  2098. clearOptDiv.classList.add(CSS.FILTER_OPTION);
  2099. clearOptDiv.id = IDS.CLEAR_FILETYPE_SEARCH_OPTION;
  2100. clearOptDiv.title = _('filter_clear_tooltip_suffix');
  2101. clearOptDiv.textContent = _('filter_any_format');
  2102. clearOptDiv.dataset[DATA_ATTR.FILTER_TYPE] = 'filetype_clear'; // Special type
  2103. sectionContentElement.appendChild(clearOptDiv);
  2104.  
  2105. const listElement = document.createElement('ul');
  2106. listElement.classList.add(CSS.CUSTOM_LIST);
  2107. if (checkboxModeEnabled) {
  2108. listElement.classList.add('checkbox-mode-enabled');
  2109. }
  2110.  
  2111. combinedOptions.forEach((option, index) => {
  2112. if (option.isAnyOption) return; // "Any Format" is handled by the div above
  2113.  
  2114. const li = document.createElement('li');
  2115. const filetypeValue = option.value;
  2116.  
  2117. if (checkboxModeEnabled) {
  2118. const checkbox = document.createElement('input');
  2119. checkbox.type = 'checkbox';
  2120. checkbox.id = `ft-cb-${index}-${Date.now()}`; // Unique ID
  2121. checkbox.value = filetypeValue;
  2122. checkbox.classList.add(CSS.FILETYPE_SEARCH_ITEM_CHECKBOX);
  2123. checkbox.dataset[DATA_ATTR.FILETYPE_VALUE] = filetypeValue;
  2124. li.appendChild(checkbox);
  2125.  
  2126. const label = document.createElement('label');
  2127. label.htmlFor = checkbox.id; // Match checkbox ID
  2128. label.dataset[DATA_ATTR.FILETYPE_VALUE] = filetypeValue;
  2129. label.title = `${option.text} (${filterParam}=${filetypeValue.replace(/\s+OR\s+/gi, ', ')})`;
  2130. label.textContent = option.text;
  2131. li.appendChild(label);
  2132. } else {
  2133. const divOpt = document.createElement('div');
  2134. divOpt.classList.add(CSS.FILTER_OPTION);
  2135. divOpt.dataset[DATA_ATTR.FILTER_TYPE] = filterParam;
  2136. divOpt.dataset[DATA_ATTR.FILTER_VALUE] = filetypeValue;
  2137. divOpt.title = `${option.text} (${filterParam}=${filetypeValue.replace(/\s+OR\s+/gi, ', ')})`;
  2138. divOpt.textContent = option.text;
  2139. li.appendChild(divOpt);
  2140. }
  2141. listFragment.appendChild(li);
  2142. });
  2143. listElement.appendChild(listFragment);
  2144. sectionContentElement.appendChild(listElement);
  2145.  
  2146. if (checkboxModeEnabled) {
  2147. let applyButton = sectionContentElement.querySelector(`#${IDS.APPLY_SELECTED_FILETYPES_BUTTON}`);
  2148. if(!applyButton) {
  2149. applyButton = document.createElement('button');
  2150. applyButton.id = IDS.APPLY_SELECTED_FILETYPES_BUTTON;
  2151. applyButton.classList.add(CSS.TOOL_BUTTON, CSS.APPLY_FILETYPES_BUTTON);
  2152. applyButton.textContent = _('tool_apply_selected_filetypes');
  2153. sectionContentElement.appendChild(applyButton);
  2154. }
  2155. applyButton.disabled = true;
  2156. applyButton.style.display = 'none';
  2157. }
  2158.  
  2159. if (!sectionContentElement.dataset.filetypeClickListenerAttached) {
  2160. sectionContentElement.dataset.filetypeClickListenerAttached = 'true';
  2161. sectionContentElement.addEventListener('click', (event) => {
  2162. const target = event.target;
  2163. const isCheckboxMode = SettingsManager.getCurrentSettings().enableFiletypeCheckboxMode;
  2164. const clearFiletypeOpt = target.closest(`#${IDS.CLEAR_FILETYPE_SEARCH_OPTION}`);
  2165.  
  2166. if (clearFiletypeOpt) {
  2167. URLActionManager.clearFiletypeSearch();
  2168. sectionContentElement.querySelectorAll(`.${CSS.FILTER_OPTION}.${CSS.SELECTED}, label.${CSS.SELECTED}`).forEach(o => o.classList.remove(CSS.SELECTED));
  2169. clearFiletypeOpt.classList.add(CSS.SELECTED);
  2170. if (isCheckboxMode) {
  2171. sectionContentElement.querySelectorAll(`input[type="checkbox"].${CSS.FILETYPE_SEARCH_ITEM_CHECKBOX}`).forEach(cb => cb.checked = false);
  2172. _updateApplyFiletypesButtonState(sectionContentElement);
  2173. }
  2174. } else if (isCheckboxMode) {
  2175. const labelElement = target.closest('label');
  2176. if (labelElement && labelElement.dataset[DATA_ATTR.FILETYPE_VALUE]) {
  2177. event.preventDefault();
  2178. const filetypeValueOrCombined = labelElement.dataset[DATA_ATTR.FILETYPE_VALUE];
  2179. sectionContentElement.querySelectorAll(`input[type="checkbox"].${CSS.FILETYPE_SEARCH_ITEM_CHECKBOX}`).forEach(cb => {
  2180. const correspondingLabel = sectionContentElement.querySelector(`label[for="${cb.id}"]`);
  2181. cb.checked = (cb.value === filetypeValueOrCombined);
  2182. if(correspondingLabel) correspondingLabel.classList.toggle(CSS.SELECTED, cb.checked);
  2183. });
  2184. URLActionManager.applyCombinedFiletypeSearch(filetypeValueOrCombined);
  2185. _updateApplyFiletypesButtonState(sectionContentElement);
  2186. sectionContentElement.querySelector(`#${IDS.CLEAR_FILETYPE_SEARCH_OPTION}`)?.classList.remove(CSS.SELECTED);
  2187. }
  2188. } else {
  2189. const optionDiv = target.closest(`div.${CSS.FILTER_OPTION}:not(#${IDS.CLEAR_FILETYPE_SEARCH_OPTION})`);
  2190. if (optionDiv && optionDiv.dataset[DATA_ATTR.FILTER_VALUE]) {
  2191. const clickedFilterType = optionDiv.dataset[DATA_ATTR.FILTER_TYPE];
  2192. const clickedFilterValueOrCombined = optionDiv.dataset[DATA_ATTR.FILTER_VALUE];
  2193. sectionContentElement.querySelectorAll(`.${CSS.FILTER_OPTION}.${CSS.SELECTED}`).forEach(o => o.classList.remove(CSS.SELECTED));
  2194. optionDiv.classList.add(CSS.SELECTED);
  2195. URLActionManager.applyFilter(clickedFilterType, clickedFilterValueOrCombined);
  2196. sectionContentElement.querySelector(`#${IDS.CLEAR_FILETYPE_SEARCH_OPTION}`)?.classList.remove(CSS.SELECTED);
  2197. }
  2198. }
  2199. });
  2200.  
  2201. if (checkboxModeEnabled) {
  2202. sectionContentElement.addEventListener('change', (event) => {
  2203. if (event.target.matches(`input[type="checkbox"].${CSS.FILETYPE_SEARCH_ITEM_CHECKBOX}`)) {
  2204. _updateApplyFiletypesButtonState(sectionContentElement);
  2205. const label = sectionContentElement.querySelector(`label[for="${event.target.id}"]`);
  2206. if (label) label.classList.toggle(CSS.SELECTED, event.target.checked);
  2207. if (event.target.checked) {
  2208. sectionContentElement.querySelector(`#${IDS.CLEAR_FILETYPE_SEARCH_OPTION}`)?.classList.remove(CSS.SELECTED);
  2209. }
  2210. }
  2211. });
  2212. const applyBtn = sectionContentElement.querySelector(`#${IDS.APPLY_SELECTED_FILETYPES_BUTTON}`);
  2213. if (applyBtn && !applyBtn.dataset[DATA_ATTR.LISTENER_ATTACHED]) {
  2214. applyBtn.dataset[DATA_ATTR.LISTENER_ATTACHED] = 'true';
  2215. applyBtn.addEventListener('click', () => {
  2216. const selectedValuesFromCheckboxes = [];
  2217. sectionContentElement.querySelectorAll(`input[type="checkbox"].${CSS.FILETYPE_SEARCH_ITEM_CHECKBOX}:checked`).forEach(cb => {
  2218. selectedValuesFromCheckboxes.push(cb.value);
  2219. });
  2220. if (selectedValuesFromCheckboxes.length > 0) {
  2221. URLActionManager.applyCombinedFiletypeSearch(selectedValuesFromCheckboxes);
  2222. sectionContentElement.querySelector(`#${IDS.CLEAR_FILETYPE_SEARCH_OPTION}`)?.classList.remove(CSS.SELECTED);
  2223. }
  2224. });
  2225. }
  2226. }
  2227. }
  2228. }
  2229.  
  2230. function _updateApplySitesButtonState(sectionContentElement) {
  2231. if (!sectionContentElement) return;
  2232. const applyButton = sectionContentElement.querySelector(`#${IDS.APPLY_SELECTED_SITES_BUTTON}`);
  2233. if (!applyButton) return;
  2234. const checkedCount = sectionContentElement.querySelectorAll(`input[type="checkbox"].${CSS.SITE_SEARCH_ITEM_CHECKBOX}:checked`).length;
  2235. applyButton.disabled = checkedCount === 0;
  2236. applyButton.style.display = checkedCount > 0 ? 'inline-flex' : 'none';
  2237. }
  2238.  
  2239. function _updateApplyFiletypesButtonState(sectionContentElement) {
  2240. if (!sectionContentElement) return;
  2241. const applyButton = sectionContentElement.querySelector(`#${IDS.APPLY_SELECTED_FILETYPES_BUTTON}`);
  2242. if (!applyButton) return;
  2243. const checkedCount = sectionContentElement.querySelectorAll(`input[type="checkbox"].${CSS.FILETYPE_SEARCH_ITEM_CHECKBOX}:checked`).length;
  2244. applyButton.disabled = checkedCount === 0;
  2245. applyButton.style.display = checkedCount > 0 ? 'inline-flex' : 'none';
  2246. }
  2247.  
  2248. function renderSectionOrderList(settingsRef) { const settingsWindowEl = document.getElementById(IDS.SETTINGS_WINDOW); const orderListElement = settingsWindowEl?.querySelector(`#${IDS.SIDEBAR_SECTION_ORDER_LIST}`); if (!orderListElement) return; orderListElement.innerHTML = ''; const currentSettings = settingsRef || SettingsManager.getCurrentSettings(); const visibleOrderedSections = currentSettings.sidebarSectionOrder.filter(id => currentSettings.visibleSections[id]); if (visibleOrderedSections.length === 0) { orderListElement.innerHTML = `<li><span style="font-style:italic;color:var(--settings-tab-color);">${_('settings_no_orderable_sections')}</span></li>`; return; } const fragment = document.createDocumentFragment(); visibleOrderedSections.forEach((sectionId) => { const definition = ALL_SECTION_DEFINITIONS.find(def => def.id === sectionId); const displayName = definition ? _(definition.titleKey) : sectionId; const listItem = document.createElement('li'); listItem.dataset.sectionId = sectionId; listItem.draggable = true; const dragIconSpan = document.createElement('span'); dragIconSpan.classList.add(CSS.DRAG_ICON); dragIconSpan.innerHTML = SVG_ICONS.dragGrip; listItem.appendChild(dragIconSpan); const nameSpan = document.createElement('span'); nameSpan.textContent = displayName; listItem.appendChild(nameSpan); fragment.appendChild(listItem); }); orderListElement.appendChild(fragment); }
  2249. function _initMenuCommands() { if (typeof GM_registerMenuCommand === 'function') { const openSettingsText = _('menu_open_settings'); const resetAllText = _('menu_reset_all_settings'); if (typeof GM_unregisterMenuCommand === 'function') { try { GM_unregisterMenuCommand(openSettingsText); } catch (e) {} try { GM_unregisterMenuCommand(resetAllText); } catch (e) {} } GM_registerMenuCommand(openSettingsText, SettingsManager.show.bind(SettingsManager)); GM_registerMenuCommand(resetAllText, SettingsManager.resetAllFromMenu.bind(SettingsManager)); } }
  2250. function _createSectionShell(id, titleKey) { const section = document.createElement('div'); section.id = id; section.classList.add(CSS.SIDEBAR_SECTION); const sectionTitle = document.createElement('div'); sectionTitle.classList.add(CSS.SECTION_TITLE); sectionTitle.textContent = _(titleKey); section.appendChild(sectionTitle); const sectionContent = document.createElement('div'); sectionContent.classList.add(CSS.SECTION_CONTENT); section.appendChild(sectionContent); return { section, sectionContent, sectionTitle }; }
  2251. function _createDateSectionElement(sectionId, titleKey) { const { section, sectionContent, sectionTitle } = _createSectionShell(sectionId, titleKey); sectionTitle.textContent = _(titleKey); const today = new Date(); const yyyy = today.getFullYear(); const mm = String(today.getMonth() + 1).padStart(2, '0'); const dd = String(today.getDate()).padStart(2, '0'); const todayString = `${yyyy}-${mm}-${dd}`; sectionContent.innerHTML = `<label class="${CSS.DATE_INPUT_LABEL}" for="${IDS.DATE_MIN}">${_('date_range_from')}</label>` + `<input type="date" class="${CSS.DATE_INPUT}" id="${IDS.DATE_MIN}" max="${todayString}">` + `<label class="${CSS.DATE_INPUT_LABEL}" for="${IDS.DATE_MAX}">${_('date_range_to')}</label>` + `<input type="date" class="${CSS.DATE_INPUT}" id="${IDS.DATE_MAX}" max="${todayString}">` + `<span id="${IDS.DATE_RANGE_ERROR_MSG}" class="${CSS.DATE_RANGE_ERROR_MSG} ${CSS.INPUT_ERROR_MESSAGE}"></span>` + `<button class="${CSS.TOOL_BUTTON} apply-date-range">${_('tool_apply_date')}</button>`; return section; }
  2252. function _createStandardButton({ id = null, className, svgIcon, textContent = null, title, clickHandler, isActive = false }) { const button = document.createElement('button'); if (id) button.id = id; button.classList.add(className); if (isActive) button.classList.add(CSS.ACTIVE); button.title = title; let content = svgIcon || ''; if (textContent) { content = svgIcon ? `${svgIcon} ${textContent}` : textContent; } button.innerHTML = content.trim(); if (clickHandler) { if (!button.dataset[DATA_ATTR.LISTENER_ATTACHED]) { button.addEventListener('click', clickHandler); button.dataset[DATA_ATTR.LISTENER_ATTACHED] = 'true'; } } return button; }
  2253. function _createPersonalizationButtonHTML(forLocation = 'tools') { const personalizationActive = URLActionManager.isPersonalizationActive(); const isIconOnlyLocation = (forLocation === 'header'); const svgIcon = SVG_ICONS.personalization || ''; const displayText = !isIconOnlyLocation ? _('tool_personalization_toggle') : ''; const titleKey = personalizationActive ? 'tooltip_toggle_personalization_off' : 'tooltip_toggle_personalization_on'; return _createStandardButton({ id: IDS.TOOL_PERSONALIZE, className: (forLocation === 'header') ? CSS.HEADER_BUTTON : CSS.TOOL_BUTTON, svgIcon: svgIcon, textContent: displayText, title: _(titleKey), clickHandler: () => URLActionManager.triggerTogglePersonalization(), isActive: personalizationActive }); }
  2254. function _createAdvancedSearchElementHTML(isButtonLike = false) { const el = document.createElement('a'); let iconHTML = SVG_ICONS.magnifyingGlass || ''; if (isButtonLike) { el.classList.add(CSS.TOOL_BUTTON); el.innerHTML = `${iconHTML} ${_('tool_advanced_search')}`; } else { el.classList.add(CSS.HEADER_BUTTON); el.innerHTML = iconHTML; } const baseUrl = "https://www.google.com/advanced_search"; let finalUrl = baseUrl; try { const currentFullUrl = Utils.getCurrentURL(); if (currentFullUrl) { const currentQuery = currentFullUrl.searchParams.get('q'); if (currentQuery) { let queryWithoutSite = currentQuery.replace(/\s*\(\s*(?:site:[\w.:()-]+(?:\s+OR\s+|$))+[^)]*\)\s*/gi, ' '); queryWithoutSite = queryWithoutSite.replace(/\s*site:[\w.:()-]+\s*/gi, ' '); queryWithoutSite = queryWithoutSite.replace(/\s\s+/g, ' ').trim(); if (queryWithoutSite) { finalUrl = `${baseUrl}?as_q=${encodeURIComponent(queryWithoutSite)}`; } } } } catch (e) { console.warn(`${LOG_PREFIX} Error constructing advanced search URL with query:`, e); } el.href = finalUrl; el.target = "_blank"; el.rel = "noopener noreferrer"; el.title = _('link_advanced_search_title'); return el; }
  2255. function _buildSidebarHeaderControls(headerEl, settingsBtnRef, rBL, vBL, aSL, pznBL, advSearchFn, personalizeBtnFn, settings) { const verbatimActive = URLActionManager.isVerbatimActive(); const buttonsInOrder = []; if (aSL === 'header' && advSearchFn && settings.advancedSearchLinkLocation !== 'none') { buttonsInOrder.push(advSearchFn(false)); } if (vBL === 'header' && settings.verbatimButtonLocation !== 'none') { buttonsInOrder.push(_createStandardButton({ id: IDS.TOOL_VERBATIM, className: CSS.HEADER_BUTTON, svgIcon: SVG_ICONS.verbatim, title: _('tool_verbatim_search'), clickHandler: URLActionManager.triggerToggleVerbatim, isActive: verbatimActive })); } if (pznBL === 'header' && personalizeBtnFn && settings.personalizationButtonLocation !== 'none') { buttonsInOrder.push(personalizeBtnFn('header')); } if (rBL === 'header' && settings.resetButtonLocation !== 'none') { buttonsInOrder.push(_createStandardButton({ id: IDS.TOOL_RESET_BUTTON, className: CSS.HEADER_BUTTON, svgIcon: SVG_ICONS.reset, title: _('tool_reset_filters'), clickHandler: URLActionManager.triggerResetFilters })); } buttonsInOrder.forEach(btn => { if (settingsBtnRef) { headerEl.insertBefore(btn, settingsBtnRef); } else { headerEl.appendChild(btn); } }); }
  2256. function _buildSidebarFixedTopControls(rBL, vBL, aSL, pznBL, advSearchFn, personalizeBtnFn, settings) { const fTBC = document.createElement('div'); fTBC.id = IDS.FIXED_TOP_BUTTONS; const fTF = document.createDocumentFragment(); const verbatimActive = URLActionManager.isVerbatimActive(); if (rBL === 'topBlock' && settings.resetButtonLocation !== 'none') { const btn = _createStandardButton({ id: IDS.TOOL_RESET_BUTTON, className: CSS.TOOL_BUTTON, svgIcon: SVG_ICONS.reset, textContent: _('tool_reset_filters'), title: _('tool_reset_filters'), clickHandler: URLActionManager.triggerResetFilters }); const bD = document.createElement('div'); bD.classList.add(CSS.FIXED_TOP_BUTTON_ITEM); bD.appendChild(btn); fTF.appendChild(bD); } if (pznBL === 'topBlock' && personalizeBtnFn && settings.personalizationButtonLocation !== 'none') { const btnPzn = personalizeBtnFn('topBlock'); const bDPzn = document.createElement('div'); bDPzn.classList.add(CSS.FIXED_TOP_BUTTON_ITEM); bDPzn.appendChild(btnPzn); fTF.appendChild(bDPzn); } if (vBL === 'topBlock' && settings.verbatimButtonLocation !== 'none') { const btnVerbatim = _createStandardButton({ id: IDS.TOOL_VERBATIM, className: CSS.TOOL_BUTTON, svgIcon: SVG_ICONS.verbatim, textContent: _('tool_verbatim_search'), title: _('tool_verbatim_search'), clickHandler: URLActionManager.triggerToggleVerbatim, isActive: verbatimActive }); const bDVerbatim = document.createElement('div'); bDVerbatim.classList.add(CSS.FIXED_TOP_BUTTON_ITEM); bDVerbatim.appendChild(btnVerbatim); fTF.appendChild(bDVerbatim); } if (aSL === 'topBlock' && advSearchFn && settings.advancedSearchLinkLocation !== 'none') { const linkEl = advSearchFn(true); const bDAdv = document.createElement('div'); bDAdv.classList.add(CSS.FIXED_TOP_BUTTON_ITEM); bDAdv.appendChild(linkEl); fTF.appendChild(bDAdv); } if (fTF.childElementCount > 0) { fTBC.appendChild(fTF); return fTBC; } return null; }
  2257. function _createToolsSectionElement(sectionId, titleKey, rBL, vBL, aSL, pznBL, advSearchFn, personalizeBtnFn) { const { section, sectionContent, sectionTitle } = _createSectionShell(sectionId, titleKey); sectionTitle.textContent = _(titleKey); const frag = document.createDocumentFragment(); const verbatimActive = URLActionManager.isVerbatimActive(); const currentSettings = SettingsManager.getCurrentSettings(); if (rBL === 'tools' && currentSettings.resetButtonLocation !== 'none') { const btn = _createStandardButton({ id: IDS.TOOL_RESET_BUTTON, className: CSS.TOOL_BUTTON, svgIcon: SVG_ICONS.reset, textContent: _('tool_reset_filters'), title: _('tool_reset_filters'), clickHandler: URLActionManager.triggerResetFilters }); frag.appendChild(btn); } if (pznBL === 'tools' && personalizeBtnFn && currentSettings.personalizationButtonLocation !== 'none') { const btnPzn = personalizeBtnFn('tools'); frag.appendChild(btnPzn); } if (vBL === 'tools' && currentSettings.verbatimButtonLocation !== 'none') { const btnVerbatim = _createStandardButton({ id: IDS.TOOL_VERBATIM, className: CSS.TOOL_BUTTON, svgIcon: SVG_ICONS.verbatim, textContent: _('tool_verbatim_search'), title: _('tool_verbatim_search'), clickHandler: URLActionManager.triggerToggleVerbatim, isActive: verbatimActive }); frag.appendChild(btnVerbatim); } if (aSL === 'tools' && advSearchFn && currentSettings.advancedSearchLinkLocation !== 'none') { frag.appendChild(advSearchFn(true)); } if (frag.childElementCount > 0) { sectionContent.appendChild(frag); return section; } return null; }
  2258. function _validateDateInputs(minInput, maxInput, errorMsgElement) { _clearElementMessage(errorMsgElement, CSS.ERROR_VISIBLE); minInput.classList.remove(CSS.INPUT_HAS_ERROR); maxInput.classList.remove(CSS.INPUT_HAS_ERROR); let isValid = true; const today = new Date(); today.setHours(0, 0, 0, 0); const startDateStr = minInput.value; const endDateStr = maxInput.value; let startDate = null; let endDate = null; if (startDateStr) { startDate = new Date(startDateStr); startDate.setHours(0,0,0,0); if (startDate > today) { _showElementMessage(errorMsgElement, 'alert_start_in_future', {}, CSS.ERROR_VISIBLE); minInput.classList.add(CSS.INPUT_HAS_ERROR); isValid = false; } } if (endDateStr) { endDate = new Date(endDateStr); endDate.setHours(0,0,0,0); if (endDate > today && !maxInput.getAttribute('max')) { if (isValid) _showElementMessage(errorMsgElement, 'alert_end_in_future', {}, CSS.ERROR_VISIBLE); else errorMsgElement.textContent += " " + _('alert_end_in_future'); maxInput.classList.add(CSS.INPUT_HAS_ERROR); isValid = false; } } if (startDate && endDate && startDate > endDate) { if (isValid) _showElementMessage(errorMsgElement, 'alert_end_before_start', {}, CSS.ERROR_VISIBLE); else errorMsgElement.textContent += " " + _('alert_end_before_start'); minInput.classList.add(CSS.INPUT_HAS_ERROR); maxInput.classList.add(CSS.INPUT_HAS_ERROR); isValid = false; } return isValid; }
  2259. function addDateRangeListener() { const dateRangeSection = sidebar?.querySelector('#sidebar-section-date-range'); if (!dateRangeSection) return; const applyButton = dateRangeSection.querySelector('.apply-date-range'); const errorMsgElement = dateRangeSection.querySelector(`#${IDS.DATE_RANGE_ERROR_MSG}`); const dateMinInput = dateRangeSection.querySelector(`#${IDS.DATE_MIN}`); const dateMaxInput = dateRangeSection.querySelector(`#${IDS.DATE_MAX}`); if (!applyButton || !errorMsgElement || !dateMinInput || !dateMaxInput) { console.warn(`${LOG_PREFIX} Date range elements not found for listener setup.`); return; } const handleDateValidation = () => { const isValid = _validateDateInputs(dateMinInput, dateMaxInput, errorMsgElement); applyButton.disabled = !isValid; }; if (!dateMinInput.dataset[DATA_ATTR.LISTENER_ATTACHED]) { dateMinInput.addEventListener('input', handleDateValidation); dateMinInput.addEventListener('change', handleDateValidation); dateMinInput.dataset[DATA_ATTR.LISTENER_ATTACHED] = 'true'; } if (!dateMaxInput.dataset[DATA_ATTR.LISTENER_ATTACHED]) { dateMaxInput.addEventListener('input', handleDateValidation); dateMaxInput.addEventListener('change', handleDateValidation); dateMaxInput.dataset[DATA_ATTR.LISTENER_ATTACHED] = 'true'; } if (!applyButton.dataset[DATA_ATTR.LISTENER_ATTACHED]) { applyButton.dataset[DATA_ATTR.LISTENER_ATTACHED] = 'true'; applyButton.addEventListener('click', () => { if (!_validateDateInputs(dateMinInput, dateMaxInput, errorMsgElement)) return; URLActionManager.applyDateRange(dateMinInput.value, dateMaxInput.value); }); } handleDateValidation(); }
  2260. function _initializeSidebarEventListenersAndStates() { addDateRangeListener(); addToolButtonListeners(); initializeSelectedFilters(); applySectionCollapseStates(); }
  2261. function _clearElementMessage(element, visibleClass = CSS.ERROR_VISIBLE) { if(!element)return; element.textContent=''; element.classList.remove(visibleClass);}
  2262. function _showElementMessage(element, messageKey, messageArgs = {}, visibleClass = CSS.ERROR_VISIBLE) { if(!element)return; element.textContent=_(messageKey,messageArgs); element.classList.add(visibleClass);}
  2263. function addToolButtonListeners() { const queryAreas = [ sidebar?.querySelector(`.${CSS.SIDEBAR_HEADER}`), sidebar?.querySelector(`#${IDS.FIXED_TOP_BUTTONS}`), sidebar?.querySelector(`#sidebar-section-tools .${CSS.SECTION_CONTENT}`) ].filter(Boolean); queryAreas.forEach(area => { area.querySelectorAll(`#${IDS.TOOL_VERBATIM}:not([data-${DATA_ATTR.LISTENER_ATTACHED}])`).forEach(b => { b.addEventListener('click', URLActionManager.triggerToggleVerbatim); b.dataset[DATA_ATTR.LISTENER_ATTACHED] = 'true'; }); area.querySelectorAll(`#${IDS.TOOL_RESET_BUTTON}:not([data-${DATA_ATTR.LISTENER_ATTACHED}])`).forEach(b => { b.addEventListener('click', URLActionManager.triggerResetFilters); b.dataset[DATA_ATTR.LISTENER_ATTACHED] = 'true'; }); }); }
  2264. function applySidebarCollapseVisuals(isCollapsed) { if(!sidebar)return; const collapseButton = sidebar.querySelector(`#${IDS.COLLAPSE_BUTTON}`); if(isCollapsed){ sidebar.classList.add(CSS.SIDEBAR_COLLAPSED); if(collapseButton){ collapseButton.innerHTML = SVG_ICONS.chevronRight; collapseButton.title = _('sidebar_expand_title');}} else{ sidebar.classList.remove(CSS.SIDEBAR_COLLAPSED); if(collapseButton){ collapseButton.innerHTML = SVG_ICONS.chevronLeft; collapseButton.title = _('sidebar_collapse_title');}} }
  2265. function applySectionCollapseStates() { if(!sidebar)return; const currentSettings = SettingsManager.getCurrentSettings(); const sections = sidebar.querySelectorAll(`.${CSS.SIDEBAR_CONTENT_WRAPPER} .${CSS.SIDEBAR_SECTION}`); sections.forEach(section => { const content = section.querySelector(`.${CSS.SECTION_CONTENT}`); const title = section.querySelector(`.${CSS.SECTION_TITLE}`); const sectionId = section.id; if (content && title && sectionId) { let shouldBeCollapsed = false; if (currentSettings.sectionDisplayMode === 'collapseAll') { shouldBeCollapsed = true; } else if (currentSettings.sectionDisplayMode === 'expandAll') { shouldBeCollapsed = false; } else { shouldBeCollapsed = currentSettings.sectionStates?.[sectionId] === true; } content.classList.toggle(CSS.COLLAPSED, shouldBeCollapsed); title.classList.toggle(CSS.COLLAPSED, shouldBeCollapsed); if (currentSettings.sectionDisplayMode === 'remember') { if (!currentSettings.sectionStates) currentSettings.sectionStates = {}; currentSettings.sectionStates[sectionId] = shouldBeCollapsed; } } }); }
  2266.  
  2267. function initializeSelectedFilters() {
  2268. if (!sidebar) return;
  2269. try {
  2270. const currentUrl = URLActionManager._getURLObject ? URLActionManager._getURLObject() : Utils.getCurrentURL();
  2271. if (!currentUrl) return;
  2272. const params = currentUrl.searchParams;
  2273. const currentTbs = params.get('tbs') || '';
  2274. const currentQuery = params.get('q') || '';
  2275.  
  2276. ALL_SECTION_DEFINITIONS.forEach(sectionDef => {
  2277. if (sectionDef.type === 'filter' && sectionDef.param && sectionDef.id !== 'sidebar-section-filetype' && sectionDef.id !== 'sidebar-section-site-search') {
  2278. _initializeStandaloneFilterState(params, sectionDef.id, sectionDef.param);
  2279. }
  2280. });
  2281. _initializeTimeFilterState(currentTbs);
  2282. _initializeVerbatimState();
  2283. _initializePersonalizationState();
  2284. _initializeDateRangeInputs(currentTbs);
  2285. _initializeSiteSearchState(currentQuery);
  2286. _initializeFiletypeSearchState(currentQuery, params.get('as_filetype'));
  2287. } catch (e) {
  2288. console.error(`${LOG_PREFIX} Error initializing filter highlights:`, e);
  2289. }
  2290. }
  2291.  
  2292. function _initializeStandaloneFilterState(params, sectionId, paramToGetFromURL) {
  2293. const sectionElement = sidebar?.querySelector(`#${sectionId}`);
  2294. if (!sectionElement) return;
  2295. const urlValue = params.get(paramToGetFromURL);
  2296. const options = sectionElement.querySelectorAll(`.${CSS.FILTER_OPTION}`);
  2297. let anOptionWasSelectedBasedOnUrl = false;
  2298.  
  2299. options.forEach(opt => {
  2300. const optionValue = opt.dataset[DATA_ATTR.FILTER_VALUE];
  2301. const isSelected = (urlValue !== null && urlValue === optionValue);
  2302. opt.classList.toggle(CSS.SELECTED, isSelected);
  2303. if (isSelected) anOptionWasSelectedBasedOnUrl = true;
  2304. });
  2305.  
  2306. if (!anOptionWasSelectedBasedOnUrl) {
  2307. const defaultOptionQuery = (paramToGetFromURL === 'as_occt')
  2308. ? `.${CSS.FILTER_OPTION}[data-${DATA_ATTR.FILTER_VALUE}="any"]`
  2309. : `.${CSS.FILTER_OPTION}[data-${DATA_ATTR.FILTER_VALUE}=""]`;
  2310. const defaultOpt = sectionElement.querySelector(defaultOptionQuery);
  2311. if (defaultOpt) {
  2312. defaultOpt.classList.add(CSS.SELECTED);
  2313. }
  2314. }
  2315. }
  2316.  
  2317. function _initializeTimeFilterState(currentTbs){ const timeSection = sidebar?.querySelector('#sidebar-section-time'); if(!timeSection) return; const qdrMatch = currentTbs.match(/qdr:([^,]+)/); const activeQdrValue = qdrMatch ? qdrMatch[1] : null; const hasDateRange = /cdr:1/.test(currentTbs); const timeOptions = timeSection.querySelectorAll(`.${CSS.FILTER_OPTION}`); timeOptions.forEach(opt => { const optionValue = opt.dataset[DATA_ATTR.FILTER_VALUE]; let shouldBeSelected = false; if(hasDateRange){ shouldBeSelected = (optionValue === '');} else if(activeQdrValue){ shouldBeSelected = (optionValue === activeQdrValue); } else { shouldBeSelected = (optionValue === '');} opt.classList.toggle(CSS.SELECTED, shouldBeSelected); }); }
  2318. function _initializeVerbatimState(){ const isVerbatimActiveNow = URLActionManager.isVerbatimActive(); sidebar?.querySelectorAll(`#${IDS.TOOL_VERBATIM}`).forEach(b=>b.classList.toggle(CSS.ACTIVE, isVerbatimActiveNow)); }
  2319. function _initializePersonalizationState() { const isActive = URLActionManager.isPersonalizationActive(); sidebar?.querySelectorAll(`#${IDS.TOOL_PERSONALIZE}`).forEach(button => { button.classList.toggle(CSS.ACTIVE, isActive); const titleKey = isActive ? 'tooltip_toggle_personalization_off' : 'tooltip_toggle_personalization_on'; button.title = _(titleKey); const svgIcon = SVG_ICONS.personalization || ''; const isIconOnly = button.classList.contains(CSS.HEADER_BUTTON) && !button.classList.contains(CSS.TOOL_BUTTON); const currentText = !isIconOnly ? _('tool_personalization_toggle') : ''; let newHTML = ''; if(svgIcon) newHTML += svgIcon; if(currentText) newHTML += (svgIcon && currentText ? ' ' : '') + currentText; button.innerHTML = newHTML.trim(); }); }
  2320. function _initializeDateRangeInputs(currentTbs){ const dateSection = sidebar?.querySelector('#sidebar-section-date-range'); if (!dateSection) return; const dateMinInput = dateSection.querySelector(`#${IDS.DATE_MIN}`); const dateMaxInput = dateSection.querySelector(`#${IDS.DATE_MAX}`); const errorMsgElement = dateSection.querySelector(`#${IDS.DATE_RANGE_ERROR_MSG}`); const applyButton = dateSection.querySelector('.apply-date-range'); if (errorMsgElement) _clearElementMessage(errorMsgElement, CSS.ERROR_VISIBLE); if (/cdr:1/.test(currentTbs)) { const minMatch = currentTbs.match(/cd_min:(\d{1,2})\/(\d{1,2})\/(\d{4})/); const maxMatch = currentTbs.match(/cd_max:(\d{1,2})\/(\d{1,2})\/(\d{4})/); if (dateMinInput) dateMinInput.value = minMatch ? `${minMatch[3]}-${minMatch[1].padStart(2, '0')}-${minMatch[2].padStart(2, '0')}` : ''; if (dateMaxInput) dateMaxInput.value = maxMatch ? `${maxMatch[3]}-${maxMatch[1].padStart(2, '0')}-${maxMatch[2].padStart(2, '0')}` : ''; } else { if (dateMinInput) dateMinInput.value = ''; if (dateMaxInput) dateMaxInput.value = ''; } if (dateMinInput && dateMaxInput && errorMsgElement && applyButton) { const isValid = _validateDateInputs(dateMinInput, dateMaxInput, errorMsgElement); applyButton.disabled = !isValid; } }
  2321.  
  2322. function _initializeSiteSearchState(currentQuery){
  2323. const siteSearchSectionContent = sidebar?.querySelector('#sidebar-section-site-search .'+CSS.SECTION_CONTENT);
  2324. if (!siteSearchSectionContent) return;
  2325.  
  2326. const clearSiteOptDiv = siteSearchSectionContent.querySelector(`#${IDS.CLEAR_SITE_SEARCH_OPTION}`);
  2327. const listElement = siteSearchSectionContent.querySelector('ul.' + CSS.CUSTOM_LIST);
  2328. const currentSettings = SettingsManager.getCurrentSettings();
  2329. const checkboxModeEnabled = currentSettings.enableSiteSearchCheckboxMode;
  2330.  
  2331. siteSearchSectionContent.querySelectorAll(`.${CSS.FILTER_OPTION}.${CSS.SELECTED}, label.${CSS.SELECTED}`).forEach(opt => opt.classList.remove(CSS.SELECTED));
  2332. if (checkboxModeEnabled && listElement) {
  2333. listElement.querySelectorAll(`input[type="checkbox"].${CSS.SITE_SEARCH_ITEM_CHECKBOX}`).forEach(cb => cb.checked = false);
  2334. }
  2335.  
  2336. const siteMatchOr = currentQuery.match(/\(\s*(site:[\w.:()-]+(?:\s+OR\s+site:[\w.:()-]+)*)\s*\)/i);
  2337. let activeSiteUrlsFromQuery = [];
  2338.  
  2339. if (siteMatchOr && siteMatchOr[1]) {
  2340. const innerQuery = siteMatchOr[1];
  2341. const individualSiteMatches = [...innerQuery.matchAll(/site:([\w.:()-]+)/gi)];
  2342. activeSiteUrlsFromQuery = individualSiteMatches.map(match => match[1].toLowerCase());
  2343. } else {
  2344. const siteMatchSimple = currentQuery.match(/(?<!\S)site:([\w.:()-]+)(?!\S)/i);
  2345. if (siteMatchSimple && siteMatchSimple[1]) {
  2346. activeSiteUrlsFromQuery.push(siteMatchSimple[1].toLowerCase());
  2347. }
  2348. }
  2349. activeSiteUrlsFromQuery.sort(); // Sort for consistent comparison
  2350.  
  2351. if (activeSiteUrlsFromQuery.length > 0) {
  2352. if(clearSiteOptDiv) clearSiteOptDiv.classList.remove(CSS.SELECTED);
  2353. let customOptionFullyMatched = false;
  2354.  
  2355. if (listElement) {
  2356. const customSiteOptions = Array.from(listElement.querySelectorAll(checkboxModeEnabled ? 'label' : `div.${CSS.FILTER_OPTION}`));
  2357. for (const optElement of customSiteOptions) {
  2358. const customSiteValue = optElement.dataset[DATA_ATTR.SITE_URL];
  2359. if (!customSiteValue) continue;
  2360.  
  2361. const definedCustomSites = Utils.parseCombinedValue(customSiteValue).map(s => s.toLowerCase()).sort();
  2362. if (definedCustomSites.length === activeSiteUrlsFromQuery.length && definedCustomSites.every((val, index) => val === activeSiteUrlsFromQuery[index])) {
  2363. if (checkboxModeEnabled) {
  2364. const checkbox = listElement.querySelector(`input[type="checkbox"][value="${customSiteValue}"]`);
  2365. if (checkbox) checkbox.checked = true;
  2366. }
  2367. optElement.classList.add(CSS.SELECTED);
  2368. customOptionFullyMatched = true;
  2369. break; // Found a full match for the custom OR group
  2370. }
  2371. }
  2372. }
  2373.  
  2374. // If no custom OR option fully matched, but URL has sites, select individual checkboxes/options if applicable
  2375. if (!customOptionFullyMatched && listElement) {
  2376. activeSiteUrlsFromQuery.forEach(url => {
  2377. if (checkboxModeEnabled) {
  2378. const checkbox = listElement.querySelector(`input[type="checkbox"].${CSS.SITE_SEARCH_ITEM_CHECKBOX}[value="${url}"]`);
  2379. if (checkbox) { checkbox.checked = true; const label = listElement.querySelector(`label[for="${checkbox.id}"]`); if(label) label.classList.add(CSS.SELECTED); }
  2380. } else {
  2381. // This case is less likely if a combined query was in URL, but handle for single site from URL
  2382. const option = listElement.querySelector(`.${CSS.FILTER_OPTION}[data-${DATA_ATTR.SITE_URL}="${url}"]`);
  2383. if (option) option.classList.add(CSS.SELECTED);
  2384. }
  2385. });
  2386. }
  2387. } else {
  2388. if (clearSiteOptDiv) clearSiteOptDiv.classList.add(CSS.SELECTED);
  2389. }
  2390.  
  2391. if (checkboxModeEnabled) {
  2392. _updateApplySitesButtonState(siteSearchSectionContent);
  2393. }
  2394. }
  2395.  
  2396. function _initializeFiletypeSearchState(currentQuery, asFiletypeParam) {
  2397. const filetypeSectionContent = sidebar?.querySelector('#sidebar-section-filetype .'+CSS.SECTION_CONTENT);
  2398. if (!filetypeSectionContent) return;
  2399.  
  2400. const clearFiletypeOptDiv = filetypeSectionContent.querySelector(`#${IDS.CLEAR_FILETYPE_SEARCH_OPTION}`);
  2401. const listElement = filetypeSectionContent.querySelector('ul.' + CSS.CUSTOM_LIST);
  2402. const currentSettings = SettingsManager.getCurrentSettings();
  2403. const checkboxModeEnabled = currentSettings.enableFiletypeCheckboxMode;
  2404.  
  2405. filetypeSectionContent.querySelectorAll(`.${CSS.FILTER_OPTION}.${CSS.SELECTED}, label.${CSS.SELECTED}`).forEach(opt => opt.classList.remove(CSS.SELECTED));
  2406. if (checkboxModeEnabled && listElement) {
  2407. listElement.querySelectorAll(`input[type="checkbox"].${CSS.FILETYPE_SEARCH_ITEM_CHECKBOX}`).forEach(cb => cb.checked = false);
  2408. }
  2409.  
  2410. let activeFiletypesFromQuery = [];
  2411. const filetypeMatchOr = currentQuery.match(/\(\s*(filetype:[\w.:()-]+(?:\s+OR\s+filetype:[\w.:()-]+)*)\s*\)/i);
  2412.  
  2413. if (filetypeMatchOr && filetypeMatchOr[1]) {
  2414. const innerQuery = filetypeMatchOr[1];
  2415. const individualFiletypeMatches = [...innerQuery.matchAll(/filetype:([\w.:()-]+)/gi)];
  2416. activeFiletypesFromQuery = individualFiletypeMatches.map(match => match[1].toLowerCase());
  2417. } else {
  2418. const filetypeMatchSimpleSingle = currentQuery.match(/(?<!\S)filetype:([\w.:()-]+)(?!\S)/i);
  2419. if (filetypeMatchSimpleSingle && filetypeMatchSimpleSingle[1]) {
  2420. activeFiletypesFromQuery.push(filetypeMatchSimpleSingle[1].toLowerCase());
  2421. } else if (asFiletypeParam && !currentQuery.includes('filetype:')) { // Only use as_filetype if q doesn't have filetype
  2422. activeFiletypesFromQuery.push(asFiletypeParam.toLowerCase());
  2423. }
  2424. }
  2425. activeFiletypesFromQuery.sort();
  2426.  
  2427. if (activeFiletypesFromQuery.length > 0) {
  2428. if(clearFiletypeOptDiv) clearFiletypeOptDiv.classList.remove(CSS.SELECTED);
  2429. let customOptionFullyMatched = false;
  2430.  
  2431. if (listElement) {
  2432. const customFiletypeOptions = Array.from(listElement.querySelectorAll(checkboxModeEnabled ? 'label' : `div.${CSS.FILTER_OPTION}`));
  2433. for (const optElement of customFiletypeOptions) {
  2434. const customFtValueAttr = checkboxModeEnabled ? optElement.dataset[DATA_ATTR.FILETYPE_VALUE] : optElement.dataset[DATA_ATTR.FILTER_VALUE];
  2435. if (!customFtValueAttr) continue;
  2436.  
  2437. const definedCustomFiletypes = Utils.parseCombinedValue(customFtValueAttr).map(s => s.toLowerCase()).sort();
  2438. if (definedCustomFiletypes.length > 0 && definedCustomFiletypes.length === activeFiletypesFromQuery.length && definedCustomFiletypes.every((val, index) => val === activeFiletypesFromQuery[index])) {
  2439. if (checkboxModeEnabled) {
  2440. const checkbox = listElement.querySelector(`input[type="checkbox"][value="${customFtValueAttr}"]`);
  2441. if (checkbox) checkbox.checked = true;
  2442. }
  2443. optElement.classList.add(CSS.SELECTED);
  2444. customOptionFullyMatched = true;
  2445. break;
  2446. }
  2447. }
  2448. }
  2449.  
  2450. if (!customOptionFullyMatched && listElement) {
  2451. activeFiletypesFromQuery.forEach(ft => {
  2452. if (checkboxModeEnabled) {
  2453. const checkbox = listElement.querySelector(`input[type="checkbox"].${CSS.FILETYPE_SEARCH_ITEM_CHECKBOX}[value="${ft}"]`);
  2454. if (checkbox) { checkbox.checked = true; const label = listElement.querySelector(`label[for="${checkbox.id}"]`); if(label) label.classList.add(CSS.SELECTED); }
  2455. } else {
  2456. const option = listElement.querySelector(`.${CSS.FILTER_OPTION}[data-${DATA_ATTR.FILTER_VALUE}="${ft}"]`);
  2457. if (option) option.classList.add(CSS.SELECTED);
  2458. }
  2459. });
  2460. }
  2461. } else {
  2462. if (clearFiletypeOptDiv) clearFiletypeOptDiv.classList.add(CSS.SELECTED);
  2463. }
  2464. if (checkboxModeEnabled) {
  2465. _updateApplyFiletypesButtonState(filetypeSectionContent);
  2466. }
  2467. }
  2468.  
  2469. function bindSidebarEvents() { if (!sidebar) return; const collapseButton = sidebar.querySelector(`#${IDS.COLLAPSE_BUTTON}`); const settingsButton = sidebar.querySelector(`#${IDS.SETTINGS_BUTTON}`); if (collapseButton) collapseButton.title = _('sidebar_collapse_title'); if (settingsButton) settingsButton.title = _('sidebar_settings_title'); sidebar.addEventListener('click', (e) => { const settingsBtnTarget = e.target.closest(`#${IDS.SETTINGS_BUTTON}`); if (settingsBtnTarget) { SettingsManager.show(); return; } const collapseBtnTarget = e.target.closest(`#${IDS.COLLAPSE_BUTTON}`); if (collapseBtnTarget) { toggleSidebarCollapse(); return; } const sectionTitleTarget = e.target.closest(`.${CSS.SIDEBAR_CONTENT_WRAPPER} .${CSS.SECTION_TITLE}`); if (sectionTitleTarget && !sidebar.classList.contains(CSS.SIDEBAR_COLLAPSED)) { handleSectionCollapse(e); return; } }); }
  2470. function toggleSidebarCollapse() { const cs = SettingsManager.getCurrentSettings(); cs.sidebarCollapsed = !cs.sidebarCollapsed; applySettings(cs); SettingsManager.save('Sidebar Collapse');}
  2471. function handleSectionCollapse(event) { const title = event.target.closest(`.${CSS.SECTION_TITLE}`); if (!title || sidebar?.classList.contains(CSS.SIDEBAR_COLLAPSED) || title.closest(`#${IDS.FIXED_TOP_BUTTONS}`)) return; const section = title.closest(`.${CSS.SIDEBAR_SECTION}`); if (!section) return; const content = section.querySelector(`.${CSS.SECTION_CONTENT}`); const sectionId = section.id; if (!content || !sectionId) return; const currentSettings = SettingsManager.getCurrentSettings(); const isCurrentlyCollapsed = content.classList.contains(CSS.COLLAPSED); const shouldBeCollapsedAfterClick = !isCurrentlyCollapsed; let overallStateChanged = false; if (currentSettings.accordionMode && !shouldBeCollapsedAfterClick) { const sectionsContainer = section.parentElement; if (_applyAccordionEffectToSections(sectionId, sectionsContainer, currentSettings)) overallStateChanged = true; } if (_toggleSectionVisualState(section, title, content, sectionId, shouldBeCollapsedAfterClick, currentSettings)) overallStateChanged = true; if (overallStateChanged && currentSettings.sectionDisplayMode === 'remember') { debouncedSaveSettings('Section Collapse/Accordion'); } }
  2472. function _applyAccordionEffectToSections(clickedSectionId, allSectionsContainer, currentSettings) { let stateChangedForAccordion = false; allSectionsContainer?.querySelectorAll(`.${CSS.SIDEBAR_SECTION}`)?.forEach(otherSection => { if (otherSection.id !== clickedSectionId) { const otherContent = otherSection.querySelector(`.${CSS.SECTION_CONTENT}`); const otherTitle = otherSection.querySelector(`.${CSS.SECTION_TITLE}`); if (otherContent && !otherContent.classList.contains(CSS.COLLAPSED)) { otherContent.classList.add(CSS.COLLAPSED); otherTitle?.classList.add(CSS.COLLAPSED); if (currentSettings.sectionDisplayMode === 'remember') { if (!currentSettings.sectionStates) currentSettings.sectionStates = {}; if (currentSettings.sectionStates[otherSection.id] !== true) { currentSettings.sectionStates[otherSection.id] = true; stateChangedForAccordion = true; } } } } }); return stateChangedForAccordion; }
  2473. function _toggleSectionVisualState(sectionEl, titleEl, contentEl, sectionId, newCollapsedState, currentSettings) { let sectionStateActuallyChanged = false; const isCurrentlyCollapsed = contentEl.classList.contains(CSS.COLLAPSED); if (isCurrentlyCollapsed !== newCollapsedState) { contentEl.classList.toggle(CSS.COLLAPSED, newCollapsedState); titleEl.classList.toggle(CSS.COLLAPSED, newCollapsedState); sectionStateActuallyChanged = true; } if (currentSettings.sectionDisplayMode === 'remember') { if (!currentSettings.sectionStates) currentSettings.sectionStates = {}; if (currentSettings.sectionStates[sectionId] !== newCollapsedState) { currentSettings.sectionStates[sectionId] = newCollapsedState; if (!sectionStateActuallyChanged) sectionStateActuallyChanged = true; } } return sectionStateActuallyChanged; }
  2474.  
  2475. function initializeScript() {
  2476. console.log(LOG_PREFIX + " Initializing script...");
  2477. debouncedSaveSettings = Utils.debounce(() => SettingsManager.save('Debounced Save'), 800);
  2478. try {
  2479. addGlobalStyles(); NotificationManager.init(); LocalizationService.initializeBaseLocale();
  2480. SettingsManager.initialize( defaultSettings, applySettings, buildSidebarUI, applySectionCollapseStates, _initMenuCommands, renderSectionOrderList );
  2481. setupSystemThemeListener(); buildSidebarSkeleton();
  2482. DragManager.init( sidebar, sidebar.querySelector(`.${CSS.DRAG_HANDLE}`), SettingsManager, debouncedSaveSettings );
  2483. const initialSettings = SettingsManager.getCurrentSettings();
  2484. DragManager.setDraggable(initialSettings.draggableHandleEnabled, sidebar, sidebar.querySelector(`.${CSS.DRAG_HANDLE}`));
  2485. applySettings(initialSettings); buildSidebarUI(); bindSidebarEvents(); _initMenuCommands();
  2486. console.log(`${LOG_PREFIX} Script initialization complete. Final effective locale: ${LocalizationService.getCurrentLocale()}`);
  2487. } catch (error) {
  2488. console.error(`${LOG_PREFIX} [initializeScript] CRITICAL ERROR DURING INITIALIZATION:`, error, error.stack);
  2489. const scriptNameForAlert = (typeof _ === 'function' && _('scriptName') && !(_('scriptName').startsWith('[ERR:'))) ? _('scriptName') : SCRIPT_INTERNAL_NAME;
  2490. if (typeof NotificationManager !== 'undefined' && NotificationManager.show) { NotificationManager.show('alert_init_fail', { scriptName: scriptNameForAlert, error: error.message }, 'error', 0); }
  2491. else { _showGlobalMessage('alert_init_fail', { scriptName: scriptNameForAlert, error: error.message }, 'error', 0); }
  2492. if(sidebar && sidebar.remove) sidebar.remove(); const settingsOverlayEl = document.getElementById(IDS.SETTINGS_OVERLAY); if(settingsOverlayEl) settingsOverlayEl.remove(); ModalManager.hide();
  2493. }
  2494. }
  2495.  
  2496. if (document.getElementById(IDS.SIDEBAR)) { console.warn(`${LOG_PREFIX} Sidebar with ID "${IDS.SIDEBAR}" already exists. Skipping initialization.`); return; }
  2497. const dependenciesReady = { styles: false, i18n: false }; let initializationAttempted = false; let timeoutFallback;
  2498. function checkDependenciesAndInitialize() { if (initializationAttempted) return; if (dependenciesReady.styles && dependenciesReady.i18n) { console.log(`${LOG_PREFIX} All dependencies ready. Initializing script.`); clearTimeout(timeoutFallback); initializationAttempted = true; if (document.readyState === 'complete' || document.readyState === 'interactive' || document.readyState === 'loaded') { initializeScript(); } else { window.addEventListener('DOMContentLoaded', initializeScript, { once: true }); } } }
  2499. document.addEventListener('gscsStylesLoaded', function stylesLoadedHandler() { console.log(`${LOG_PREFIX} Event "gscsStylesLoaded" received.`); dependenciesReady.styles = true; checkDependenciesAndInitialize(); }, { once: true });
  2500. document.addEventListener('gscsi18nLoaded', function i18nLoadedHandler() { console.log(`${LOG_PREFIX} Event "gscsi18nLoaded" received.`); dependenciesReady.i18n = true; checkDependenciesAndInitialize(); }, { once: true });
  2501. timeoutFallback = setTimeout(() => { if (initializationAttempted) return; console.log(`${LOG_PREFIX} Fallback: Checking dependencies after timeout.`); if (typeof window.GSCS_Namespace !== 'undefined') { if (typeof window.GSCS_Namespace.stylesText === 'string' && window.GSCS_Namespace.stylesText.trim() !== '' && !dependenciesReady.styles) { console.log(`${LOG_PREFIX} Fallback: Styles found via namespace.`); dependenciesReady.styles = true; } if (typeof window.GSCS_Namespace.i18nPack === 'object' && Object.keys(window.GSCS_Namespace.i18nPack.translations || {}).length > 0 && !dependenciesReady.i18n) { console.log(`${LOG_PREFIX} Fallback: i18n pack found via namespace.`); dependenciesReady.i18n = true; } } if (dependenciesReady.styles && dependenciesReady.i18n) { checkDependenciesAndInitialize(); } else { console.error(`${LOG_PREFIX} Fallback: Dependencies still not fully loaded after timeout. Styles: ${dependenciesReady.styles}, i18n: ${dependenciesReady.i18n}.`); if (!initializationAttempted) { console.warn(`${LOG_PREFIX} Attempting to initialize with potentially incomplete dependencies due to fallback timeout.`); if (!dependenciesReady.styles) { console.warn(`${LOG_PREFIX} Styles dependency forced true in fallback.`); dependenciesReady.styles = true; } if (!dependenciesReady.i18n) { console.warn(`${LOG_PREFIX} i18n dependency forced true in fallback.`); dependenciesReady.i18n = true; } checkDependenciesAndInitialize(); } } }, 2000);
  2502. if (document.readyState === 'complete' || document.readyState === 'interactive' || document.readyState === 'loaded') { if (typeof window.GSCS_Namespace !== 'undefined') { if (typeof window.GSCS_Namespace.stylesText === 'string' && window.GSCS_Namespace.stylesText.trim() !== '' && !dependenciesReady.styles) { dependenciesReady.styles = true; } if (typeof window.GSCS_Namespace.i18nPack === 'object' && Object.keys(window.GSCS_Namespace.i18nPack.translations || {}).length > 0 && !dependenciesReady.i18n) { dependenciesReady.i18n = true; } } if (dependenciesReady.styles && dependenciesReady.i18n && !initializationAttempted) { checkDependenciesAndInitialize(); } }
  2503. })();

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址