├── .editorconfig ├── .eslintignore ├── .eslintrc.cjs ├── .github └── ISSUE_TEMPLATE │ ├── bug-报告-bug-report-.md │ └── 功能请求报告-feature-request-report-.md ├── .gitignore ├── .npmrc ├── .prettierrc.mjs ├── LICENSE ├── README.md ├── docs └── screenshots │ └── interface.png ├── package.json ├── pnpm-lock.yaml ├── src ├── App.tsx ├── assets │ ├── scss │ │ ├── app.module.scss │ │ ├── index.scss │ │ ├── vars.module.scss │ │ └── vars.module.scss.d.ts │ └── theme │ │ └── vars │ │ └── color.ts ├── components │ ├── dataDisplay │ │ ├── chip │ │ │ └── Chip │ │ │ │ └── index.tsx │ │ └── icons │ │ │ └── NativeIcon │ │ │ └── types.ts │ └── inputs │ │ └── button │ │ ├── FuncIconButton │ │ └── index.tsx │ │ └── IconButton │ │ └── index.tsx ├── config │ └── index.ts ├── hooks │ ├── useLocalStorage.ts │ └── useSettingsContext.ts ├── index.tsx ├── sections │ ├── ConsoleSection │ │ ├── index.tsx │ │ └── types.ts │ └── SettingsSection │ │ └── index.tsx ├── server │ ├── core.ts │ └── topic.ts ├── store │ └── context │ │ └── settings │ │ └── settingsProvider.tsx ├── types │ ├── globals.d.ts │ └── monkey.d.ts ├── utils │ ├── core.ts │ ├── storage.ts │ └── time.ts └── vite-env.d.ts ├── tsconfig.json ├── tsconfig.node.json └── vite.config.ts /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | charset = utf-8 5 | end_of_line = lf 6 | indent_style = space 7 | indent_size = 2 8 | trim_trailing_whitespace = true 9 | insert_final_newline = true 10 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | dist/ 2 | public/ 3 | node_modules/ 4 | !src/**/*.ts 5 | !src/**/*.tsx 6 | **/*.d.ts 7 | **/*.js 8 | **/*.config.ts 9 | -------------------------------------------------------------------------------- /.eslintrc.cjs: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: { 4 | browser: true, 5 | es2024: true, 6 | }, 7 | extends: ['airbnb', 'airbnb-typescript', 'airbnb/hooks', 'prettier'], 8 | plugins: ['simple-import-sort', '@typescript-eslint', 'prettier'], 9 | parser: '@typescript-eslint/parser', 10 | parserOptions: { 11 | ecmaFeatures: { 12 | jsx: true, 13 | }, 14 | ecmaVersion: 'latest', 15 | sourceType: 'module', 16 | project: './tsconfig.json', 17 | warnOnUnsupportedTypeScriptVersion: false, 18 | }, 19 | settings: { 20 | 'import/parsers': { 21 | '@typescript-eslint/parser': ['.ts', '.tsx'], 22 | }, 23 | 'import/resolver': { 24 | typescript: { 25 | alwaysTryTypes: true, 26 | project: './tsconfig.json', 27 | }, 28 | }, 29 | }, 30 | rules: { 31 | '@typescript-eslint/no-unused-vars': 'off', 32 | 'arrow-body-style': [ 33 | 'off', 34 | 'as-needed', 35 | { 36 | requireReturnForObjectLiteral: true, 37 | }, 38 | ], 39 | 'import/extensions': [ 40 | 'off', 41 | 'never', 42 | { 43 | ignorePackages: true, 44 | scss: 'ignorePackages', 45 | svg: 'ignorePackages', 46 | }, 47 | ], 48 | 'import/first': 'error', 49 | 'import/newline-after-import': 'error', 50 | // 'import/no-cycle': 'off', 51 | 'import/no-duplicates': [ 52 | 'error', 53 | { 54 | considerQueryString: true, 55 | 'prefer-inline': false, 56 | }, 57 | ], 58 | 'react/jsx-props-no-spreading': [ 59 | 'off', 60 | { 61 | html: 'ignore', // "ignore" | "enforce" 62 | custom: 'ignore', // "ignore" | "enforce" 63 | explicitSpread: 'ignore', // "ignore" | "enforce" 64 | exceptions: ['Image', 'img'], 65 | }, 66 | ], 67 | 'react-hooks/rules-of-hooks': [ 68 | 'off', 69 | ], 70 | 'import/no-extraneous-dependencies': [ 71 | 'off', 72 | { 73 | devDependencies: false, 74 | optionalDependencies: true, 75 | peerDependencies: true, 76 | // includeInternal: false, 77 | // includeTypes: false, 78 | }, 79 | ], 80 | // 'import/no-named-as-default': 'off', 81 | // 'import/no-relative-packages': 'off', 82 | // 'import/no-self-import': 'off', 83 | // 'import/no-useless-path-segments': 'off', 84 | // 'import/order': 'off', 85 | 'import/prefer-default-export': [ 86 | 'off', 87 | { 88 | target: 'single', 89 | }, 90 | ], 91 | // 'jsx-a11y/control-has-associated-label': 'off', 92 | // 'jsx-a11y/label-has-associated-control': 'off', 93 | 'no-console': 'off', 94 | // 'react/destructuring-assignment': 'off', 95 | 'react/require-default-props': 'off', 96 | // "react/react-in-jsx-scope": "off", 97 | 'simple-import-sort/imports': 'error', 98 | 'simple-import-sort/exports': 'error', 99 | }, 100 | }; 101 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug-报告-bug-report-.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug 报告(Bug Report) 3 | about: 创建报告以帮助我们改进(Create a report to help us improve) 4 | title: "[BUG]" 5 | labels: bug 6 | assignees: delph1s 7 | 8 | --- 9 | 10 | **问题描述(Issue Description)** 11 | 简短而清晰地描述问题。(Briefly describe the issue.) 12 | 13 | [*描述(Description)*] 14 | 15 | **复现步骤(Steps to Reproduce)** 16 | 请列出重现问题的步骤。(Please list the steps to reproduce the issue.) 17 | 18 | 重现该行为的步骤(Steps to reproduce the behavior): 19 | 1. [*第一步(Step 1)*] 20 | 2. [*第二步(Step 2)*] 21 | 3. [*第三步(Step 3)*] 22 | 4. [*请看错误(See error)*] 23 | 24 | **预期行为(Expected Behavior)** 25 | 描述你期望发生的事情。(Describe what you expected to happen.) 26 | 27 | [*预期(Expected)*] 28 | 29 | **实际行为(Actual Behavior)** 30 | 描述实际发生了什么。(Describe what actually happened.) 31 | 32 | [*实际(Actual)*] 33 | 34 | **屏幕截图(Screenshots)** 35 | 如果适用,请添加屏幕截图来帮助解释您的问题。(If applicable, add screenshots to help explain your problem.) 36 | 37 | [*图片 (Pictures)*] 38 | 39 | **环境信息(Environment Information)** 40 | 41 | - 设备(OS):[e.g. iphone 999 pro max ultra] 42 | - 操作系统(OS):[e.g. macOS Sonoma 14.X] 43 | - 浏览器(Browser):[e.g. chrome, safari] 44 | - 软件版本(Software Version):[e.g. 0.1.0] 45 | 46 | **其他备注(Additional Context)** 47 | 在此处添加问题的其他上下文。(Add any other context about the problem here.) 48 | 49 | [*其他(Additional)*] 50 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/功能请求报告-feature-request-report-.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: 功能请求报告(Feature Request Report) 3 | about: 为此项目提出建议(Suggest an idea for this project) 4 | title: "[FEATURE]" 5 | labels: enhancement 6 | assignees: delph1s 7 | 8 | --- 9 | 10 | **功能请求描述(Feature Request Description)** 11 | 简短而清晰地描述你希望添加的功能。(Briefly describe the feature you would like to add.) 12 | 13 | [*描述(Description)*] 14 | 15 | **功能价值(Value of Feature)** 16 | 描述这个功能对用户或项目的潜在价值。(Describe the potential value of the feature to the users or the project.) 17 | 18 | [*价值(Value)*] 19 | 20 | **实现建议(Implementation Suggestion)** 21 | 如果有,提供一种或多种实现该功能的方法。(If any, provide one or more suggestions for how this feature could be implemented.) 22 | 23 | [*实现建议(Implementation Suggestion)*] 24 | 25 | **可能的挑战(Potential Challenges)** 26 | 描述实现此功能可能遇到的挑战或限制。(Describe any potential challenges or limitations in implementing this feature.) 27 | 28 | [*挑战(Challenges)*] 29 | 30 | **替代方案 (Alternative Solutions)** 31 | 如果有,描述任何你考虑过的替代解决方案。(If any, describe any alternative solutions you have considered.) 32 | 33 | [*替代方案(Alternatives)*] 34 | 35 | **其他备注(Additional Context)** 36 | 在此处添加任何其他上下文或屏幕截图来进一步说明你的功能请求。(Add any other context or screenshots about the feature request here.) 37 | 38 | [*其他(Additional)*] 39 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ### project template 2 | /dist 3 | /release 4 | 5 | ### Jetbrains template 6 | 7 | /.idea 8 | 9 | ### Linux template 10 | *~ 11 | 12 | # temporary files which can be created if a process still has a handle open of a deleted file 13 | .fuse_hidden* 14 | 15 | # KDE directory preferences 16 | .directory 17 | 18 | # Linux trash folder which might appear on any partition or disk 19 | .Trash-* 20 | 21 | # .nfs files are created when an open file is removed but is still being accessed 22 | .nfs* 23 | 24 | ### Node template 25 | # Logs 26 | logs 27 | *.log 28 | npm-debug.log* 29 | yarn-debug.log* 30 | yarn-error.log* 31 | lerna-debug.log* 32 | .pnpm-debug.log* 33 | 34 | # Diagnostic reports (https://nodejs.org/api/report.html) 35 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 36 | 37 | # Runtime data 38 | pids 39 | *.pid 40 | *.seed 41 | *.pid.lock 42 | 43 | # Directory for instrumented libs generated by jscoverage/JSCover 44 | lib-cov 45 | 46 | # Coverage directory used by tools like istanbul 47 | coverage 48 | *.lcov 49 | 50 | # nyc test coverage 51 | .nyc_output 52 | 53 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 54 | .grunt 55 | 56 | # Bower dependency directory (https://bower.io/) 57 | bower_components 58 | 59 | # node-waf configuration 60 | .lock-wscript 61 | 62 | # Compiled binary addons (https://nodejs.org/api/addons.html) 63 | build/Release 64 | 65 | # Dependency directories 66 | node_modules/ 67 | jspm_packages/ 68 | 69 | # Snowpack dependency directory (https://snowpack.dev/) 70 | web_modules/ 71 | 72 | # TypeScript cache 73 | *.tsbuildinfo 74 | 75 | # Optional npm cache directory 76 | .npm 77 | 78 | # Optional eslint cache 79 | .eslintcache 80 | 81 | # Optional stylelint cache 82 | .stylelintcache 83 | 84 | # Microbundle cache 85 | .rpt2_cache/ 86 | .rts2_cache_cjs/ 87 | .rts2_cache_es/ 88 | .rts2_cache_umd/ 89 | 90 | # Optional REPL history 91 | .node_repl_history 92 | 93 | # Output of 'npm pack' 94 | *.tgz 95 | 96 | # Yarn Integrity file 97 | .yarn-integrity 98 | 99 | # dotenv environment variable files 100 | .env 101 | .env.development.local 102 | .env.test.local 103 | .env.production.local 104 | .env.local 105 | 106 | # parcel-bundler cache (https://parceljs.org/) 107 | .cache 108 | .parcel-cache 109 | 110 | # Next.js build output 111 | .next 112 | out 113 | 114 | # Nuxt.js build / generate output 115 | .nuxt 116 | dist 117 | 118 | # Gatsby files 119 | .cache/ 120 | # Comment in the public line in if your project uses Gatsby and not Next.js 121 | # https://nextjs.org/blog/next-9-1#public-directory-support 122 | # public 123 | 124 | # vuepress build output 125 | .vuepress/dist 126 | 127 | # vuepress v2.x temp and cache directory 128 | .temp 129 | .cache 130 | 131 | # Docusaurus cache and generated files 132 | .docusaurus 133 | 134 | # Serverless directories 135 | .serverless/ 136 | 137 | # FuseBox cache 138 | .fusebox/ 139 | 140 | # DynamoDB Local files 141 | .dynamodb/ 142 | 143 | # TernJS port file 144 | .tern-port 145 | 146 | # Stores VSCode versions used for testing VSCode extensions 147 | .vscode-test 148 | 149 | # yarn v2 150 | .yarn/cache 151 | .yarn/unplugged 152 | .yarn/build-state.yml 153 | .yarn/install-state.gz 154 | .pnp.* 155 | 156 | ### react template 157 | .DS_* 158 | *.log 159 | logs 160 | **/*.backup.* 161 | **/*.back.* 162 | 163 | node_modules 164 | bower_components 165 | 166 | *.sublime* 167 | 168 | psd 169 | thumb 170 | sketch 171 | 172 | ### Windows template 173 | # Windows thumbnail cache files 174 | Thumbs.db 175 | Thumbs.db:encryptable 176 | ehthumbs.db 177 | ehthumbs_vista.db 178 | 179 | # Dump file 180 | *.stackdump 181 | 182 | # Folder config file 183 | [Dd]esktop.ini 184 | 185 | # Recycle Bin used on file shares 186 | $RECYCLE.BIN/ 187 | 188 | # Windows Installer files 189 | *.cab 190 | *.msi 191 | *.msix 192 | *.msm 193 | *.msp 194 | 195 | # Windows shortcuts 196 | *.lnk 197 | 198 | ### macOS template 199 | # General 200 | .DS_Store 201 | .AppleDouble 202 | .LSOverride 203 | 204 | # Icon must end with two \r 205 | Icon 206 | 207 | # Thumbnails 208 | ._* 209 | 210 | # Files that might appear in the root of a volume 211 | .DocumentRevisions-V100 212 | .fseventsd 213 | .Spotlight-V100 214 | .TemporaryItems 215 | .Trashes 216 | .VolumeIcon.icns 217 | .com.apple.timemachine.donotpresent 218 | 219 | # Directories potentially created on remote AFP share 220 | .AppleDB 221 | .AppleDesktop 222 | Network Trash Folder 223 | Temporary Items 224 | .apdisk 225 | 226 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | hoist=false 2 | -------------------------------------------------------------------------------- /.prettierrc.mjs: -------------------------------------------------------------------------------- 1 | export default { 2 | printWidth: 120, 3 | tabWidth: 2, 4 | semi: true, 5 | useTabs: false, 6 | singleQuote: true, 7 | jsxSingleQuote: false, 8 | trailingComma: 'all', 9 | bracketSpacing: true, 10 | bracketSameLine: false, 11 | arrowParens: 'avoid', 12 | insertPragma: false, 13 | endOfLine: 'auto', 14 | htmlWhitespaceSensitivity: 'ignore', 15 | vueIndentScriptAndStyle: false, 16 | jsxBracketSameLine: false, 17 | }; 18 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Linux.do 蓝点消除计划 2 | 3 | ## Screenshots 4 | 5 | ![interface](docs/screenshots/interface.png) 6 | -------------------------------------------------------------------------------- /docs/screenshots/interface.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/delph1s/linuxdo-browse/bc6bdabce92631668ae14689814855b58e4b9573/docs/screenshots/interface.png -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "linuxdo-browse", 3 | "private": true, 4 | "version": "0.0.1-alpha.4", 5 | "type": "module", 6 | "scripts": { 7 | "dev": "vite", 8 | "build": "tsc && vite build", 9 | "preview": "vite preview", 10 | "lint": "eslint ." 11 | }, 12 | "peerDependencies": { 13 | "react": "18.3.1", 14 | "react-dom": "18.3.1" 15 | }, 16 | "dependencies": { 17 | "dayjs": "1.11.13", 18 | "lodash": "4.17.21" 19 | }, 20 | "devDependencies": { 21 | "@types/lodash": "4.17.15", 22 | "@types/node": "22.13.17", 23 | "@types/react": "19.0.14", 24 | "@types/react-dom": "19.1.1", 25 | "@typescript-eslint/eslint-plugin": "7.18.0", 26 | "@typescript-eslint/parser": "7.18.0", 27 | "@vitejs/plugin-react": "4.3.4", 28 | "eslint": "8.57.1", 29 | "eslint-config-airbnb": "19.0.4", 30 | "eslint-config-airbnb-typescript": "18.0.0", 31 | "eslint-config-prettier": "9.1.0", 32 | "eslint-import-resolver-typescript": "3.10.0", 33 | "eslint-plugin-import": "2.31.0", 34 | "eslint-plugin-jsx-a11y": "6.10.2", 35 | "eslint-plugin-prettier": "5.2.6", 36 | "eslint-plugin-react": "7.37.5", 37 | "eslint-plugin-react-hooks": "4.6.2", 38 | "eslint-plugin-simple-import-sort": "12.1.1", 39 | "prettier": "3.5.3", 40 | "sass": "1.86.3", 41 | "type-fest": "4.39.1", 42 | "typescript": "5.8.3", 43 | "vite": "5.4.17", 44 | "vite-plugin-monkey": "5.0.8", 45 | "vite-tsconfig-paths": "5.1.4" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/App.tsx: -------------------------------------------------------------------------------- 1 | import styles from '@assets/scss/vars.module.scss'; 2 | import FuncIconButton from '@components/inputs/button/FuncIconButton'; 3 | import IconButton from '@components/inputs/button/IconButton'; 4 | import { useSettingsContext } from '@hooks/useSettingsContext'; 5 | import ConsoleSection from '@sections/ConsoleSection'; 6 | import type { LogItemType, StatsDataType, TaskItemType } from '@sections/ConsoleSection/types'; 7 | import SettingsSection from '@sections/SettingsSection'; 8 | import { getCsrfToken } from '@server/core'; 9 | import { getTopicList, getTopicTrack, TopicData } from '@server/topic'; 10 | import { ensureNativeMethods, genRandId, isTimingsUrl, isTopicUrl, randInt, randSleep } from '@utils/core'; 11 | import { dayjs } from '@utils/time'; 12 | import nativeDayjs from 'dayjs'; 13 | import _ from 'lodash'; 14 | import React, { useCallback, useEffect, useRef, useState } from 'react'; 15 | 16 | type ContentType = 'settings' | 'console'; 17 | 18 | function App() { 19 | const settings = useSettingsContext(); 20 | 21 | // XMLHttpRequest 拦截 22 | const nativeXHROpen = useRef(XMLHttpRequest.prototype.open); 23 | const nativeXHRSend = useRef(XMLHttpRequest.prototype.send); 24 | 25 | // csrf token store 26 | const csrfTokenRef = useRef(''); 27 | const processingRef = useRef(false); 28 | 29 | // Queue & Log Dialog open state 30 | const [taskQueue, setTaskQueue] = useState([]); 31 | const [logs, setLogs] = useState([]); 32 | const [lastTaskTime, setLastTaskTime] = useState(dayjs('1970-01-01 00:00:00')); 33 | const [statsData, setStatsData] = useState({ 34 | totalSuccess: 0, 35 | totalFailed: 0, 36 | totalReadingTime: 0, 37 | }); 38 | const [isDialogOpen, setIsDialogOpen] = useState(false); 39 | // Enable Assistant 40 | const [enableBrowseAssist, setEnableBrowseAssist] = useState(false); 41 | // Switch Content 42 | const [activeContent, setActiveContent] = useState('console'); 43 | const [isAnimating, setIsAnimating] = useState(false); 44 | 45 | /** 46 | * 切换 dialog 内容 47 | * 48 | * @param t 49 | */ 50 | const switchContent = (t: ContentType) => { 51 | if (t !== activeContent && !isAnimating) { 52 | setIsAnimating(true); 53 | setTimeout(() => { 54 | setActiveContent(t); 55 | setTimeout(() => { 56 | setIsAnimating(false); 57 | }, styles.dialogBodySwitchDuration); // 第二个页面出现的延迟 58 | }, styles.dialogBodySwitchDuration); // 等待第一个页面消失 59 | } 60 | }; 61 | 62 | /** 63 | * 修改 css 64 | * 65 | * @param t 66 | */ 67 | const switchContentCSS = (t: ContentType) => { 68 | if (activeContent === t) { 69 | if (isAnimating) { 70 | return 'animating'; 71 | } 72 | return 'active'; 73 | } 74 | return ''; 75 | }; 76 | 77 | /** 78 | * 添加日志 79 | * 80 | * @param level 81 | * @param message 82 | */ 83 | const addLog = useCallback( 84 | (level: LogItemType['level'], message: LogItemType['message']) => { 85 | setLogs(prevState => { 86 | let nextState; 87 | if (prevState.length >= settings.maxLogLineNum) { 88 | nextState = prevState.slice(1); 89 | } else { 90 | nextState = prevState; 91 | } 92 | return [...nextState, { logId: genRandId(), time: dayjs().format('YYYY-MM-DD HH:mm:ss'), level, message }]; 93 | }); 94 | }, 95 | [settings.maxLogLineNum], 96 | ); 97 | 98 | /** 99 | * 清理日志 100 | */ 101 | const clearLogs = useCallback(() => { 102 | setLogs([]); 103 | addLog('info', '日志已清除'); 104 | }, [addLog]); 105 | 106 | const changeTaskStatus = ( 107 | currentTask: TaskItemType, 108 | prevState: TaskItemType[], 109 | newStatus: TaskItemType['status'], 110 | ) => { 111 | const nextState = prevState; 112 | const currentItemIndex = prevState.findIndex(value => { 113 | return currentTask.topicId === value.topicId; 114 | }); 115 | if (currentItemIndex !== -1) { 116 | nextState[currentItemIndex].status = newStatus; 117 | } 118 | return nextState; 119 | }; 120 | 121 | /** 122 | * 分批处理帖子编号 123 | */ 124 | const genReadingPostBatches = (postNums: number[], batchSize: number): number[][] => { 125 | const batches: number[][] = []; 126 | for (let i = 0; i < postNums.length; i += batchSize) { 127 | batches.push(postNums.slice(i, i + batchSize)); 128 | } 129 | return batches; 130 | }; 131 | 132 | /** 133 | * 构建请求体 134 | */ 135 | const genReadingRequestBody = (topicId: string | number, postNums: number[]): string => { 136 | const readTime = randInt(60000, 61000); 137 | const postParams = postNums.filter(num => num !== 0).map(num => `timings%5B${num}%5D=${readTime}`); 138 | 139 | return [...postParams, `topic_time=${readTime}`, `topic_id=${topicId}`].join('&'); 140 | }; 141 | 142 | const handleReadingPosts = useCallback( 143 | async (task: TaskItemType) => { 144 | const { topicId, postNums, csrfToken, maxReadPosts, actionType, status } = task; 145 | const trackTopicId = await getTopicTrack(topicId, csrfToken); 146 | 147 | // 分批处理帖子 148 | const readingPostBatches = genReadingPostBatches(postNums, maxReadPosts); 149 | 150 | // eslint-disable-next-line no-restricted-syntax 151 | for (const readingPostBatch of readingPostBatches) { 152 | let retryCount = 0; 153 | let success = false; 154 | 155 | while (!success && retryCount <= settings.maxRetryTimes) { 156 | try { 157 | const readingRequestBody = genReadingRequestBody(topicId, readingPostBatch); 158 | // eslint-disable-next-line no-await-in-loop 159 | const response = await fetch('https://linux.do/topics/timings', { 160 | method: 'POST', 161 | headers: { 162 | 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8', 163 | 'discourse-background': 'true', 164 | 'discourse-logged-in': 'true', 165 | 'discourse-present': 'true', 166 | 'x-csrf-token': csrfToken, 167 | 'x-requested-with': 'XMLHttpRequest', 168 | 'x-silence-logger': 'true', 169 | }, 170 | referrer: `https://linux.do/t/topic/${topicId}/1`, 171 | body: readingRequestBody, 172 | mode: 'cors', 173 | credentials: 'include', 174 | }); 175 | 176 | if (response.ok) { 177 | addLog( 178 | 'success', 179 | `已完成话题[${topicId}]第${readingPostBatch[0]}至${readingPostBatch[readingPostBatch.length - 1]}层阅读`, 180 | ); 181 | success = true; 182 | retryCount = 0; 183 | // eslint-disable-next-line no-await-in-loop 184 | await randSleep(1000, 2000); // 成功后的冷却时间 185 | } else if (response.status >= 400 && response.status < 600) { 186 | retryCount += 1; 187 | addLog( 188 | 'warning', 189 | `阅读话题[${topicId}]出现错误(${response.status})!正在重试(${retryCount}/${settings.maxRetryTimes})……`, 190 | ); 191 | setTaskQueue(prevState => { 192 | return changeTaskStatus(task, prevState, 'retrying'); 193 | }); 194 | // eslint-disable-next-line no-await-in-loop 195 | await randSleep(3000, 5000); 196 | } else { 197 | throw new Error(`HTTP ${response.status}: ${response.statusText}`); 198 | } 199 | } catch (error: any) { 200 | console.error(error); 201 | retryCount += 1; 202 | addLog('error', `阅读话题[${topicId}]发生未知错误: ${error.message}`); 203 | // eslint-disable-next-line no-await-in-loop 204 | await randSleep(3000, 5000); 205 | } 206 | } 207 | 208 | // 如果当前批次处理失败,直接返回错误 209 | if (!success) { 210 | return { topicId, error: true, detail: '超过最大重试次数' }; 211 | } 212 | } 213 | 214 | return { topicId, error: false, detail: '已完成阅读' }; 215 | }, 216 | [addLog, settings.maxRetryTimes], 217 | ); 218 | 219 | /** 220 | * 执行队列任务 221 | */ 222 | const processQueue = useCallback(async () => { 223 | if (taskQueue.length > 0) { 224 | const task = taskQueue[0]; 225 | addLog('info', `正在阅读:${task.topicId}`); 226 | 227 | setTaskQueue(prevState => { 228 | processingRef.current = true; 229 | return changeTaskStatus(task, prevState, 'processing'); 230 | }); 231 | 232 | try { 233 | const readingRes = await handleReadingPosts(task); 234 | 235 | const finishTime = dayjs(); 236 | const timeDiff = finishTime.diff(lastTaskTime); 237 | 238 | if (readingRes.error) { 239 | setStatsData(prevState => { 240 | return { 241 | ...prevState, 242 | totalFailed: prevState.totalFailed + 1, 243 | }; 244 | }); 245 | setTaskQueue(prevState => { 246 | return changeTaskStatus(task, prevState, 'failed'); 247 | }); 248 | addLog('error', readingRes.detail); 249 | } else { 250 | setStatsData(prevState => { 251 | return { 252 | ...prevState, 253 | totalSuccess: prevState.totalSuccess + 1, 254 | totalReadingTime: prevState.totalReadingTime + Math.min(timeDiff, 60000), 255 | }; 256 | }); 257 | setLastTaskTime(finishTime); 258 | setTaskQueue(prevState => { 259 | return changeTaskStatus(task, prevState, 'completed'); 260 | }); 261 | addLog('success', `任务已完成:${task.topicId}`); 262 | } 263 | } catch (err: any) { 264 | console.error(err); 265 | setStatsData(prevState => { 266 | return { 267 | ...prevState, 268 | totalFailed: prevState.totalFailed + 1, 269 | }; 270 | }); 271 | setTaskQueue(prevState => { 272 | return changeTaskStatus(task, prevState, 'failed'); 273 | }); 274 | addLog('error', `处理任务时发生错误:${err.message}`); 275 | } 276 | 277 | // 删除已完成任务 278 | setTaskQueue(prevState => { 279 | const nextState = prevState.filter(t => t.taskId !== task.taskId); 280 | processingRef.current = false; 281 | return nextState; 282 | }); 283 | } 284 | }, [addLog, handleReadingPosts, lastTaskTime, taskQueue]); 285 | 286 | const addTask = useCallback( 287 | ({ topicId, postNums, csrfToken, maxReadPosts, actionType }: Omit) => { 288 | if (enableBrowseAssist) { 289 | setTaskQueue(prevState => { 290 | const isDuplicate = prevState.some(task => task.topicId === topicId); 291 | 292 | if (!isDuplicate) { 293 | const nextState: TaskItemType[] = [ 294 | ...prevState, 295 | { 296 | taskId: genRandId(), 297 | topicId, 298 | postNums, 299 | csrfToken, 300 | maxReadPosts, 301 | actionType, 302 | status: 'pending', 303 | }, 304 | ]; 305 | addLog('info', `任务已添加,目前队列长度:${nextState.length}`); 306 | 307 | return nextState; 308 | } 309 | 310 | return prevState; 311 | }); 312 | } 313 | }, 314 | [addLog, enableBrowseAssist], 315 | ); 316 | 317 | const addInitTask = useCallback(async () => { 318 | let csrfToken; 319 | if (csrfTokenRef.current) { 320 | csrfToken = csrfTokenRef.current; 321 | } else { 322 | csrfToken = await getCsrfToken(settings.getCsrfTokenFromHtml); 323 | } 324 | 325 | // const unseenTopics = await getTopicList("https://linux.do/unseen.json?order=created&ascending=true", csrfToken); 326 | // const unreadTopics = await getTopicList("https://linux.do/unread.json?order=created&ascending=true", csrfToken); 327 | // const newTopics = await getTopicList("https://linux.do/new.json?order=created&ascending=true", csrfToken); 328 | 329 | let unseenTopics = await getTopicList('https://linux.do/unseen.json?order=created&ascending=true', csrfToken); 330 | if (unseenTopics.length === 0) { 331 | unseenTopics = await getTopicList('https://linux.do/unread.json?order=created&ascending=true', csrfToken); 332 | } 333 | if (unseenTopics.length === 0) { 334 | unseenTopics = await getTopicList('https://linux.do/new.json?order=created&ascending=true', csrfToken); 335 | } 336 | if (unseenTopics.length === 0) { 337 | const postNums = Array.from({ length: 500 }, (v, k) => k + 1); 338 | addTask({ 339 | topicId: 111891, 340 | postNums, 341 | csrfToken, 342 | maxReadPosts: settings.singlePostsReading, 343 | actionType: '无限月读', 344 | }); 345 | } else { 346 | unseenTopics.forEach(unseenTopic => { 347 | const highestPostNumber = unseenTopic.highest_post_number; 348 | let lastReadPostNumber; 349 | if (settings.readAllPostsInTopic) { 350 | lastReadPostNumber = 1; 351 | } else { 352 | lastReadPostNumber = unseenTopic.last_read_post_number || 1; 353 | } 354 | const postNums = Array.from( 355 | { length: highestPostNumber - lastReadPostNumber + 1 }, 356 | (v, k) => k + lastReadPostNumber, 357 | ); 358 | addTask({ 359 | topicId: unseenTopic.id, 360 | postNums, 361 | csrfToken, 362 | maxReadPosts: settings.singlePostsReading, 363 | actionType: '清理未读', 364 | }); 365 | }); 366 | } 367 | // const windowPeriodTopicSelected = settings.windowPeriodTopics[randInt(0, settings.windowPeriodTopics.length - 1)]; 368 | // const [windowPeriodTopicId, windowPeriodTopicNums] = windowPeriodTopicSelected; 369 | // const postNums = Array.from({ length: windowPeriodTopicNums }, (v, k) => k + 1); 370 | // addTask({ 371 | // topicId: windowPeriodTopicId, 372 | // postNums, 373 | // csrfToken, 374 | // maxReadPosts: settings.singlePostsReading, 375 | // actionType: '无限月读', 376 | // }); 377 | }, [addTask, settings.getCsrfTokenFromHtml, settings.readAllPostsInTopic, settings.singlePostsReading]); 378 | 379 | /** 380 | * 阅读 topic 381 | * 382 | * @param topicData 383 | */ 384 | const readTopic = useCallback( 385 | async (topicData: TopicData) => { 386 | let csrfToken; 387 | if (csrfTokenRef.current) { 388 | csrfToken = csrfTokenRef.current; 389 | } else { 390 | csrfToken = await getCsrfToken(settings.getCsrfTokenFromHtml); 391 | } 392 | const highestPostNumber = topicData.highest_post_number; 393 | let lastReadPostNumber; 394 | // TODO: 需要修复修改后不生效的 bug 395 | console.log(settings.readAllPostsInTopic); 396 | if (settings.readAllPostsInTopic) { 397 | lastReadPostNumber = 1; 398 | } else { 399 | lastReadPostNumber = topicData.last_read_post_number || 1; 400 | } 401 | const postNums = Array.from( 402 | { length: highestPostNumber - lastReadPostNumber + 1 }, 403 | (v, k) => k + lastReadPostNumber, 404 | ); 405 | addTask({ 406 | topicId: topicData.id, 407 | postNums, 408 | csrfToken, 409 | maxReadPosts: settings.singlePostsReading, 410 | actionType: '主动出击', 411 | }); 412 | }, 413 | [addTask, settings.getCsrfTokenFromHtml, settings.readAllPostsInTopic, settings.singlePostsReading], 414 | ); 415 | 416 | /** 417 | * 拦截 topic url 逻辑 418 | * 419 | * @param request XMLHttpRequest 对象 420 | */ 421 | const handleProcessTopic = (request: XMLHttpRequest) => { 422 | try { 423 | const topicData = JSON.parse(request.response); 424 | readTopic(topicData); 425 | } catch (err) { 426 | console.error(err); 427 | addLog('error', '未知错误,请查看控制台!'); 428 | } 429 | }; 430 | 431 | const interceptXHR = (customOpen: VoidFunction, customSend: VoidFunction) => {}; 432 | 433 | const enableXMLHttpRequestHooks = () => { 434 | // @ts-ignore 435 | XMLHttpRequest.prototype.open = function (method, url, async, username, password) { 436 | if (typeof url === 'string' && isTimingsUrl(url)) { 437 | return; 438 | } 439 | if (url instanceof URL && isTimingsUrl(url.pathname)) { 440 | return; 441 | } 442 | // @ts-ignore 443 | // eslint-disable-next-line no-underscore-dangle,react/no-this-in-sfc 444 | this._custom_storage = { method, url }; 445 | // @ts-ignore 446 | // eslint-disable-next-line prefer-rest-params,consistent-return 447 | return nativeXHROpen.current.apply(this, arguments); 448 | }; 449 | 450 | XMLHttpRequest.prototype.send = function (data) { 451 | // @ts-ignore 452 | // eslint-disable-next-line react/no-this-in-sfc 453 | this.addEventListener( 454 | 'readystatechange', 455 | function () { 456 | // @ts-ignore 457 | // eslint-disable-next-line react/no-this-in-sfc 458 | if (this.readyState === 4) { 459 | // @ts-ignore 460 | // eslint-disable-next-line no-underscore-dangle,react/no-this-in-sfc 461 | if (isTopicUrl(this._custom_storage.url) && this._custom_storage.method === 'GET') { 462 | // @ts-ignore 463 | handleProcessTopic(this); 464 | } 465 | } 466 | }, 467 | false, 468 | ); 469 | // @ts-ignore 470 | // eslint-disable-next-line prefer-rest-params 471 | return nativeXHRSend.current.apply(this, arguments); 472 | }; 473 | }; 474 | 475 | const disableXMLHttpRequestHooks = () => { 476 | XMLHttpRequest.prototype.open = nativeXHROpen.current; 477 | XMLHttpRequest.prototype.send = nativeXHRSend.current; 478 | // console.log(XMLHttpRequest.prototype.open); 479 | // console.log(XMLHttpRequest.prototype.send); 480 | }; 481 | 482 | useEffect(() => { 483 | const start = () => { 484 | enableXMLHttpRequestHooks(); 485 | addLog('success', '助手已开启'); 486 | addLog('success', '未读拦截已开启'); 487 | }; 488 | 489 | const stop = () => { 490 | disableXMLHttpRequestHooks(); 491 | if (taskQueue.length > 1) { 492 | addLog('warning', '正在删除多余任务,仅保留最后进行的任务'); 493 | setTaskQueue(prevState => prevState.slice(0, 1)); 494 | } 495 | addLog('error', '助手已停止'); 496 | }; 497 | 498 | if (enableBrowseAssist) { 499 | start(); 500 | } else { 501 | stop(); 502 | } 503 | // eslint-disable-next-line react-hooks/exhaustive-deps 504 | }, [enableBrowseAssist]); 505 | 506 | useEffect(() => { 507 | const processNextTask = async () => { 508 | if (enableBrowseAssist && taskQueue.length > 0 && !processingRef.current) { 509 | await randSleep(3000, 5000); 510 | if (enableBrowseAssist && taskQueue.length > 0 && !processingRef.current) { 511 | await processQueue(); 512 | } 513 | } 514 | }; 515 | 516 | if (enableBrowseAssist) { 517 | processNextTask(); 518 | } 519 | }, [enableBrowseAssist, processQueue, taskQueue, taskQueue.length]); 520 | 521 | useEffect(() => { 522 | const readingInfinite = async () => { 523 | if (enableBrowseAssist && taskQueue.length === 0 && !processingRef.current) { 524 | await randSleep(10000, 15000); 525 | if (enableBrowseAssist && taskQueue.length === 0 && !processingRef.current) { 526 | await addInitTask(); 527 | } 528 | } 529 | }; 530 | 531 | if (enableBrowseAssist) { 532 | readingInfinite(); 533 | } 534 | }, [addInitTask, enableBrowseAssist, taskQueue, taskQueue.length]); 535 | 536 | return ( 537 |
538 | } 542 | onClick={settings.onToggleDialog} 543 | /> 544 |
549 |
550 |

551 | Task Queue & Logs 552 |

553 | setEnableBrowseAssist(prevState => !prevState)} 557 | style={{ flex: 0 }} 558 | icon={enableBrowseAssist ? 'circle-stop' : 'play'} 559 | /> 560 | switchContent('settings')} 564 | style={{ flex: 0 }} 565 | icon="gear" 566 | /> 567 | switchContent('console')} 571 | style={{ flex: 0 }} 572 | icon="code" 573 | /> 574 | 581 |
582 |
583 |
584 | 585 |
586 |
587 | 588 |
589 |
590 |
591 |
592 | ); 593 | } 594 | 595 | export default App; 596 | -------------------------------------------------------------------------------- /src/assets/scss/app.module.scss: -------------------------------------------------------------------------------- 1 | @use "sass:map"; 2 | @use "vars.module"; 3 | 4 | ##{vars.$browseContainer} { 5 | position: fixed; 6 | bottom: 3rem; 7 | right: 1rem; 8 | width: vars.$containerWidth; 9 | border-radius: 0.5rem; 10 | display: block; 11 | z-index: 1000; 12 | opacity: 0; 13 | visibility: hidden; 14 | transition: all 0.3s ease-in-out; 15 | } 16 | 17 | ##{vars.$browseContainer}.open { 18 | bottom: 4rem; 19 | opacity: 1; 20 | visibility: visible; 21 | } 22 | 23 | ##{vars.$browseButton} { 24 | z-index: 1001; 25 | position: fixed; 26 | bottom: 1rem; 27 | right: 1rem; 28 | } 29 | 30 | .#{vars.$chipName} { 31 | font-size: vars.$chipFontSize; 32 | line-height: 1rem; 33 | padding: .25rem .5rem; 34 | border-radius: .25rem; 35 | 36 | @each $name, $color in vars.$chipThemeColor { 37 | &.#{vars.$chipName}-#{$name} { 38 | background-color: map.get($color, "background"); 39 | color: map.get($color, "text"); 40 | } 41 | } 42 | } 43 | 44 | .#{vars.$dialogBodyName} { 45 | transition: opacity #{vars.$dialogBodySwitchDuration}ms ease, transform #{vars.$dialogBodySwitchDuration}ms ease; 46 | transform: translateX(30%); 47 | display: none; 48 | opacity: 0; 49 | 50 | &.active { 51 | transform: translateX(0); 52 | display: block; 53 | opacity: 1; 54 | } 55 | 56 | &.animating { 57 | transform: translateX(-30%); 58 | display: block; 59 | opacity: 0; 60 | } 61 | } 62 | 63 | #settings-container { 64 | border: solid 1px var(--primary-low); 65 | 66 | h4 { 67 | background-color: var(--primary-very-low); 68 | padding: .5rem 1rem; 69 | } 70 | 71 | ul { 72 | list-style: none; 73 | margin: 0; 74 | 75 | li { 76 | align-items: center; 77 | display: flex; 78 | flex-wrap: nowrap; 79 | flex-direction: row-reverse; 80 | justify-content: space-between; 81 | border-bottom: 1px solid var(--primary-low); 82 | padding: .25rem 1rem; 83 | } 84 | 85 | span { 86 | border-radius: 3px; 87 | display: inline-flex; 88 | margin: 0 6px; 89 | padding: 2px 1px 4px; 90 | } 91 | 92 | span:first-child { 93 | margin-right: 0; 94 | } 95 | 96 | span:last-child { 97 | margin-left: auto; 98 | } 99 | } 100 | } 101 | -------------------------------------------------------------------------------- /src/assets/scss/index.scss: -------------------------------------------------------------------------------- 1 | @use "vars.module"; 2 | @use "app.module"; 3 | -------------------------------------------------------------------------------- /src/assets/scss/vars.module.scss: -------------------------------------------------------------------------------- 1 | $browseName: "linuxdo-browse"; 2 | $browseContainer: #{$browseName}-container; 3 | $browseButton: #{$browseName}-toggle-button; 4 | 5 | $containerWidth: 32rem; 6 | 7 | // Chip 8 | $chipName: #{$browseName}-chip; 9 | $chipFontSize: 0.75rem; 10 | $chipThemeColor: ( 11 | "primary": ("background": #F8B3CA, "text": #CC084B), 12 | "secondary": ("background": #D7D9E1, "text": #6C757D), 13 | "info": ("background": #AECEF7, "text": #095BC6), 14 | "success": ("background": #BCE2BE, "text": #339537), 15 | "warning": ("background": #FFD59F, "text": #C87000), 16 | "error": ("background": #FCD3D0, "text": #F61200), 17 | "light": ("background": #FFFFFF, "text": #C7D3DE), 18 | "dark": ("background": #8097BF, "text": #1E2E4A), 19 | ); 20 | 21 | // Dialog 22 | $dialogName: #{$browseName}-dialog; 23 | $dialogBodyName: #{$dialogName}-body; 24 | $dialogBodySwitchDuration: 150; 25 | 26 | :export { 27 | browseName: $browseName; 28 | browseContainer: $browseContainer; 29 | browseButton: $browseButton; 30 | chipName: $chipName; 31 | dialogName: $dialogName; 32 | dialogBodyName: $dialogBodyName; 33 | dialogBodySwitchDuration: $dialogBodySwitchDuration; 34 | } 35 | -------------------------------------------------------------------------------- /src/assets/scss/vars.module.scss.d.ts: -------------------------------------------------------------------------------- 1 | export type globalScssType = { 2 | browseName: string; 3 | browseContainer: string; 4 | browseButton: string; 5 | chipName: string; 6 | dialogName: string; 7 | dialogBodyName: string; 8 | dialogBodySwitchDuration: number; 9 | }; 10 | export const styles: globalScssType; 11 | export default styles; 12 | -------------------------------------------------------------------------------- /src/assets/theme/vars/color.ts: -------------------------------------------------------------------------------- 1 | export type ColorScheme = 'primary' | 'secondary' | 'info' | 'success' | 'warning' | 'error' | 'light' | 'dark'; 2 | -------------------------------------------------------------------------------- /src/components/dataDisplay/chip/Chip/index.tsx: -------------------------------------------------------------------------------- 1 | import styles from '@assets/scss/vars.module.scss'; 2 | import { ColorScheme } from '@assets/theme/vars/color'; 3 | import React, { HTMLAttributes } from 'react'; 4 | import { Merge } from 'type-fest'; 5 | 6 | type ChipProps = Merge< 7 | HTMLAttributes, 8 | { 9 | label?: string; 10 | color?: ColorScheme; 11 | } 12 | >; 13 | 14 | function Chip({ label, color = 'primary', ...restProps }: ChipProps) { 15 | return ( 16 | 17 | {label} 18 | 19 | ); 20 | } 21 | 22 | export default Chip; 23 | -------------------------------------------------------------------------------- /src/components/dataDisplay/icons/NativeIcon/types.ts: -------------------------------------------------------------------------------- 1 | export type IconNameType = | 2 | 'play' | // 播放 3 | 'stop-circle' | // 圆形停止 4 | 'far-trash-alt' | // 垃圾桶 5 | 'cog' | // 设置 6 | 'times' | // 乘 7 | 'code' | // 代码 8 | 'history'; 9 | -------------------------------------------------------------------------------- /src/components/inputs/button/FuncIconButton/index.tsx: -------------------------------------------------------------------------------- 1 | import { IconNameType } from '@components/dataDisplay/icons/NativeIcon/types'; 2 | import React, { ButtonHTMLAttributes, ReactNode, useMemo } from 'react'; 3 | import { Merge } from 'type-fest'; 4 | 5 | type IconButtonProps = Merge< 6 | ButtonHTMLAttributes, 7 | { 8 | changeMe?: 'changeMe'; 9 | icon?: ReactNode | IconNameType; 10 | } 11 | >; 12 | 13 | function FuncIconButton({ changeMe = 'changeMe', icon, ...restProps }: IconButtonProps) { 14 | const iconElement = typeof icon === 'string' ? : icon; 15 | 16 | return ( 17 | 28 | ); 29 | } 30 | 31 | export default FuncIconButton; 32 | -------------------------------------------------------------------------------- /src/components/inputs/button/IconButton/index.tsx: -------------------------------------------------------------------------------- 1 | import { IconNameType } from '@components/dataDisplay/icons/NativeIcon/types'; 2 | import React, { ButtonHTMLAttributes, ReactNode, useMemo } from 'react'; 3 | import { Merge } from 'type-fest'; 4 | 5 | type IconButtonProps = Merge, { 6 | changeMe?: 'changeMe'; 7 | icon?: ReactNode | IconNameType; 8 | }>; 9 | 10 | function IconButton({ changeMe = 'changeMe', icon, ...restProps }: IconButtonProps) { 11 | const iconElement = typeof icon === 'string' ? : icon; 12 | 13 | return ( 14 | 30 | ); 31 | } 32 | 33 | export default IconButton; 34 | -------------------------------------------------------------------------------- /src/config/index.ts: -------------------------------------------------------------------------------- 1 | export const DEFAULT_APP_SETTINGS = { 2 | readAllPostsInTopic: false, // 是否阅读主题所有帖子,false 从最后的内容开始看 3 | singlePostsReading: 1000, // 单次阅读帖子数,控制 timings 请求 body 行为 4 | maxRetryTimes: 10, // 最大重试次数 5 | windowPeriodTopics: [[26306, 200]], // 空窗期随机阅读的帖子列表,[[, <阅读楼层数>]] 6 | getCsrfTokenFromHtml: true, // 是否从 html 中获取 csrf token 7 | maxLogLineNum: 100, // 日志最大条数 8 | uiWidth: "36rem", // ui 宽度 9 | uiQueueHeight: "100px", // ui 任务队列高度 10 | uiLogHeight: "400px", // ui 日志高度 11 | uiTagFontSize: "0.75rem", // ui 标签字体大小 12 | uiQueueFontSize: "0.75rem", // ui 队列字体大小 13 | uiLogFontSize: "0.75rem", // ui 日志字体大小 14 | }; 15 | 16 | export const APP_SETTINGS_KEY = "linuxdo-browse-app-settings"; 17 | -------------------------------------------------------------------------------- /src/hooks/useLocalStorage.ts: -------------------------------------------------------------------------------- 1 | import { localStorageGetItem } from '@utils/storage'; 2 | import { isEqual } from 'lodash'; 3 | import { useCallback, useEffect, useMemo, useState } from 'react'; 4 | 5 | /** 6 | * 获取存储数据 7 | * 8 | * @param key 键 9 | */ 10 | export const getStorage = (key: string) => { 11 | try { 12 | const result = localStorageGetItem(key); 13 | 14 | if (result) { 15 | return JSON.parse(result); 16 | } 17 | } catch (error) { 18 | console.error('Error while getting from storage:', error); 19 | } 20 | 21 | return null; 22 | }; 23 | 24 | /** 25 | * 设置存储数据 26 | * 27 | * @param key 键 28 | * @param value 值 29 | */ 30 | export const setStorage = (key: string, value: T) => { 31 | try { 32 | const serializedValue = JSON.stringify(value); 33 | window.localStorage.setItem(key, serializedValue); 34 | } catch (error) { 35 | console.error('Error while setting storage:', error); 36 | } 37 | }; 38 | 39 | /** 40 | * 删除存储数据 41 | * 42 | * @param key 键 43 | */ 44 | export const removeStorage = (key: string) => { 45 | try { 46 | window.localStorage.removeItem(key); 47 | } catch (error) { 48 | console.error('Error while removing from storage:', error); 49 | } 50 | }; 51 | 52 | export type UseLocalStorageReturn = { 53 | state: T; 54 | canReset: boolean; 55 | resetState: () => void; 56 | setState: (updateState: T | Partial) => void; 57 | setField: (name: keyof T, updateValue: T[keyof T]) => void; 58 | }; 59 | 60 | export const useLocalStorage = (key: string, initialValue: T): UseLocalStorageReturn => { 61 | const [value, setValue] = useState(initialValue); 62 | 63 | const multiValue = initialValue && typeof initialValue === 'object'; 64 | 65 | const canReset = !isEqual(value, initialValue); 66 | 67 | useEffect(() => { 68 | const restoredValue: T = getStorage(key); 69 | 70 | if (restoredValue) { 71 | if (multiValue) { 72 | setValue(prevValue => ({ ...prevValue, ...restoredValue })); 73 | } else { 74 | setValue(restoredValue); 75 | } 76 | } 77 | }, [key, multiValue]); 78 | 79 | const setState = useCallback( 80 | (updateValue: T | Partial) => { 81 | if (multiValue) { 82 | setValue(prevValue => { 83 | setStorage(key, { ...prevValue, ...updateValue }); 84 | return { ...prevValue, ...updateValue }; 85 | }); 86 | } else { 87 | setStorage(key, updateValue as T); 88 | setValue(updateValue as T); 89 | } 90 | }, 91 | [key, multiValue], 92 | ); 93 | 94 | const setField = useCallback( 95 | (name: keyof T, updateValue: T[keyof T]) => { 96 | if (multiValue) { 97 | setState({ [name]: updateValue } as Partial); 98 | } 99 | }, 100 | [multiValue, setState], 101 | ); 102 | 103 | const resetState = useCallback(() => { 104 | setValue(initialValue); 105 | removeStorage(key); 106 | }, [initialValue, key]); 107 | 108 | const memorizedValue = useMemo( 109 | () => ({ 110 | state: value, 111 | setState, 112 | setField, 113 | resetState, 114 | canReset, 115 | }), 116 | [canReset, resetState, setField, setState, value], 117 | ); 118 | 119 | return memorizedValue; 120 | }; 121 | -------------------------------------------------------------------------------- /src/hooks/useSettingsContext.ts: -------------------------------------------------------------------------------- 1 | import { SettingsContext } from '@store/context/settings/settingsProvider'; 2 | import { useContext } from 'react'; 3 | 4 | export function useSettingsContext() { 5 | const context = useContext(SettingsContext); 6 | 7 | if (!context) throw new Error('useSettingsContext must be use inside SettingsProvider'); 8 | 9 | return context; 10 | } 11 | -------------------------------------------------------------------------------- /src/index.tsx: -------------------------------------------------------------------------------- 1 | import '@assets/scss/index.scss'; 2 | 3 | import styles from '@assets/scss/vars.module.scss'; 4 | import { DEFAULT_APP_SETTINGS } from '@config/index'; 5 | import { SettingsProvider } from '@store/context/settings/settingsProvider'; 6 | import React from 'react'; 7 | import ReactDOM from 'react-dom/client'; 8 | 9 | import App from './App'; 10 | 11 | const createLinuxDoBrowse = () => { 12 | const app = document.createElement('div'); 13 | app.setAttribute('id', styles.browseName); 14 | document.body.appendChild(app); 15 | return app; 16 | }; 17 | 18 | ReactDOM.createRoot(createLinuxDoBrowse()).render( 19 | 20 | 21 | 22 | 23 | , 24 | ); 25 | -------------------------------------------------------------------------------- /src/sections/ConsoleSection/index.tsx: -------------------------------------------------------------------------------- 1 | import Chip from '@components/dataDisplay/chip/Chip'; 2 | import FuncIconButton from '@components/inputs/button/FuncIconButton'; 3 | import { useSettingsContext } from '@hooks/useSettingsContext'; 4 | import { LogItemType, StatsDataType, StatusLevelMappingType, TaskItemType } from '@sections/ConsoleSection/types'; 5 | import { formatDuration, formatDurationShort } from '@utils/time'; 6 | import React, { useCallback, useLayoutEffect, useRef, useState } from 'react'; 7 | 8 | type ConsoleSectionProps = { 9 | taskQueue: TaskItemType[]; 10 | logs: LogItemType[]; 11 | statsData: StatsDataType; 12 | onClearLogs: () => void; 13 | }; 14 | 15 | const statusLevelMapping: StatusLevelMappingType = { 16 | pending: 'warning', 17 | processing: 'info', 18 | completed: 'success', 19 | retrying: 'error', 20 | failed: 'error', 21 | }; 22 | 23 | function ConsoleSection({ taskQueue, logs, statsData, onClearLogs, ...restProps }: ConsoleSectionProps) { 24 | const settings = useSettingsContext(); 25 | 26 | const logContainerRef = useRef(null); 27 | const logContainerEndRef = useRef(null); 28 | // 是否需要自动滚动 29 | const [shouldLogContainerAutoScroll, setShouldLogContainerAutoScroll] = useState(true); 30 | 31 | /** 32 | * 判断是否需要滑动日志容器 33 | */ 34 | const handleLogContainerScroll = () => { 35 | if (logContainerRef.current) { 36 | const { scrollTop, scrollHeight, clientHeight } = logContainerRef.current; 37 | const isScrolledToBottom = Math.abs(scrollHeight - scrollTop - clientHeight) < 1; 38 | setShouldLogContainerAutoScroll(isScrolledToBottom); 39 | } 40 | }; 41 | 42 | /** 43 | * 日志容器滑动到最底下 44 | */ 45 | const scrollLogContainerToBottom = useCallback(() => { 46 | if (logContainerEndRef.current) { 47 | requestAnimationFrame(() => { 48 | (logContainerEndRef.current as unknown as HTMLElement).scrollIntoView({ behavior: 'smooth' }); 49 | }); 50 | } 51 | }, []); 52 | 53 | useLayoutEffect(() => { 54 | if (shouldLogContainerAutoScroll) { 55 | scrollLogContainerToBottom(); 56 | } 57 | }, [logs, scrollLogContainerToBottom, shouldLogContainerAutoScroll]); 58 | 59 | return ( 60 | <> 61 |
62 |

Queue

63 |
    64 |
  • 72 | 73 | 74 | 75 | 76 | 81 |
  • 82 | {taskQueue.map((task, i) => ( 83 |
  • 92 | {`[${task.actionType}] ${task.topicId}`} 93 | 94 |
  • 95 | ))} 96 |
97 |
98 |
99 |
100 |

Logs

101 | 108 |
109 |
    114 | {logs.map((log) => ( 115 |
  • 124 | {`${log.time} - ${log.message}`} 125 | 126 |
  • 127 | ))} 128 |
    129 |
130 |
131 | 132 | ); 133 | } 134 | 135 | export default ConsoleSection; 136 | -------------------------------------------------------------------------------- /src/sections/ConsoleSection/types.ts: -------------------------------------------------------------------------------- 1 | export type StatsDataType = { 2 | totalSuccess: number; 3 | totalFailed: number; 4 | totalReadingTime: number; 5 | }; 6 | 7 | export type TaskItemType = { 8 | taskId: string; 9 | topicId: number; 10 | postNums: number[]; 11 | csrfToken: string; 12 | maxReadPosts: number; 13 | actionType: '主动出击' | '无限月读' | '清理未读'; 14 | status: 'pending' | 'processing' | 'completed' | 'retrying' | 'failed'; 15 | }; 16 | 17 | export type LogItemType = { 18 | logId: string; 19 | time: string; 20 | level: 'info' | 'success' | 'warning' | 'error'; 21 | message: string; 22 | }; 23 | 24 | export type StatusLevelMappingType = Record; 25 | -------------------------------------------------------------------------------- /src/sections/SettingsSection/index.tsx: -------------------------------------------------------------------------------- 1 | import FuncIconButton from '@components/inputs/button/FuncIconButton'; 2 | import { useSettingsContext } from '@hooks/useSettingsContext'; 3 | import React from 'react'; 4 | 5 | type SettingsSectionProps = { 6 | changeMe?: 'changeMe'; 7 | }; 8 | 9 | function SettingsSection({ changeMe = 'changeMe', ...restProps }: SettingsSectionProps) { 10 | const settings = useSettingsContext(); 11 | 12 | return ( 13 |
14 |
15 |

Settings

16 | 24 |
25 |
    26 |
  • 27 | 28 | { 31 | settings.onUpdateField('readAllPostsInTopic', event.target.checked); 32 | }} 33 | checked={settings.readAllPostsInTopic} 34 | /> 35 | 36 | 阅读主题所有回复 37 |
  • 38 |
39 |
40 | ); 41 | } 42 | 43 | export default SettingsSection; 44 | -------------------------------------------------------------------------------- /src/server/core.ts: -------------------------------------------------------------------------------- 1 | import { SettingsContextValue } from '@store/context/settings/settingsProvider'; 2 | 3 | /** 4 | * 获取预加载数据 5 | */ 6 | export const getPreloadedData = () => { 7 | const preloadedDataElement = document.querySelector('#data-preloaded'); 8 | if (!preloadedDataElement) throw new Error('Preloaded data element not found'); 9 | return JSON.parse(preloadedDataElement.getAttribute('data-preloaded') || '{}'); 10 | }; 11 | 12 | /** 13 | * 获取用户名 14 | */ 15 | export const getUsername = () => { 16 | const preloadedData = getPreloadedData(); 17 | return JSON.parse(preloadedData.currentUser).username; 18 | }; 19 | 20 | /** 21 | * 获取 csrf token 22 | */ 23 | export const getCsrfToken = async (getCsrfTokenFromHtml: boolean) => { 24 | if (getCsrfTokenFromHtml) { 25 | const csrfTokenElement = document.querySelector('meta[name="csrf-token"]'); 26 | if (!csrfTokenElement) throw new Error('CSRF token element not found'); 27 | return csrfTokenElement.getAttribute('content') || ''; 28 | } 29 | 30 | const response = await fetch('https://linux.do/session/csrf', { 31 | headers: { 32 | 'x-csrf-token': 'undefined', 33 | 'x-requested-with': 'XMLHttpRequest', 34 | }, 35 | method: 'GET', 36 | mode: 'cors', 37 | credentials: 'include', 38 | }).then(res => res.json()); 39 | 40 | if (!response || !response.csrf) throw new Error('CSRF token not fetched'); 41 | return response.csrf; 42 | }; 43 | -------------------------------------------------------------------------------- /src/server/topic.ts: -------------------------------------------------------------------------------- 1 | export type TopicData = { 2 | id: number; 3 | highest_post_number: number; 4 | last_read_post_number?: number; 5 | }; 6 | 7 | // 用户相关接口 8 | type User = { 9 | id: number; 10 | username: string; 11 | name: string; 12 | avatar_template: string; 13 | trust_level: number; 14 | animated_avatar: string | null; 15 | primary_group_name?: string; 16 | flair_name?: string; 17 | flair_url?: string; 18 | flair_bg_color?: string; 19 | flair_color?: string; 20 | flair_group_id?: number; 21 | admin?: boolean; 22 | moderator?: boolean; 23 | }; 24 | 25 | type Group = { 26 | id: number; 27 | name: string; 28 | flair_url: string | null; 29 | flair_bg_color: string; 30 | flair_color: string; 31 | }; 32 | 33 | type Poster = { 34 | extras: string | null; 35 | description: string; 36 | user_id: number; 37 | primary_group_id: number | null; 38 | flair_group_id: number | null; 39 | }; 40 | 41 | type Topic = { 42 | id: number; 43 | title: string; 44 | fancy_title: string; 45 | slug: string; 46 | posts_count: number; 47 | reply_count: number; 48 | highest_post_number: number; 49 | image_url: string | null; 50 | created_at: string; 51 | last_posted_at: string; 52 | bumped: boolean; 53 | bumped_at: string; 54 | archetype: string; 55 | unseen: boolean; 56 | last_read_post_number?: number; 57 | unread?: number; 58 | new_posts?: number; 59 | unread_posts?: number; 60 | pinned: boolean; 61 | unpinned: null; 62 | visible: boolean; 63 | closed: boolean; 64 | archived: boolean; 65 | notification_level?: number; 66 | bookmarked?: boolean; 67 | liked?: boolean; 68 | tags: string[]; 69 | tags_descriptions: Record; 70 | views: number; 71 | like_count: number; 72 | has_summary: boolean; 73 | last_poster_username: string | null; 74 | category_id: number; 75 | pinned_globally: boolean; 76 | featured_link: null; 77 | has_accepted_answer: boolean; 78 | can_have_answer: boolean; 79 | can_vote: boolean; 80 | posters: Poster[]; 81 | }; 82 | 83 | type TopicList = { 84 | can_create_topic: boolean; 85 | more_topics_url: string; 86 | per_page: number; 87 | top_tags: string[]; 88 | topics: Topic[]; 89 | }; 90 | 91 | export type TopicListData = { 92 | users: User[]; 93 | primary_groups: Group[]; 94 | flair_groups: Group[]; 95 | topic_list: TopicList; 96 | }; 97 | 98 | export const getTopicList = async (url: string, csrfToken: string) => { 99 | const response = await fetch(url, { 100 | headers: { 101 | accept: 'application/json, text/javascript, */*; q=0.01', 102 | 'x-csrf-token': csrfToken, 103 | 'x-requested-with': 'XMLHttpRequest', 104 | }, 105 | body: null, 106 | method: 'GET', 107 | mode: 'cors', 108 | credentials: 'include', 109 | }) 110 | .then(res => res.json()) 111 | .then((res: TopicListData) => { 112 | return res.topic_list.topics; 113 | }) 114 | .catch(err => { 115 | console.error(err); 116 | return []; 117 | }); 118 | 119 | return response; 120 | }; 121 | 122 | export const getTopicTrack = async (topicId: number, csrfToken: string) => { 123 | const response = await fetch(`https://linux.do/t/${topicId}/1.json?track_visit=true&forceLoad=true`, { 124 | headers: { 125 | accept: 'application/json, text/javascript, */*; q=0.01', 126 | 'accept-language': 'en-US,en;q=0.9', 127 | 'discourse-logged-in': 'true', 128 | 'discourse-present': 'true', 129 | 'discourse-track-view': 'true', 130 | 'discourse-track-view-topic-id': `${topicId}`, 131 | 'x-csrf-token': csrfToken, 132 | 'x-requested-with': 'XMLHttpRequest', 133 | }, 134 | body: null, 135 | method: 'GET', 136 | mode: 'cors', 137 | credentials: 'include', 138 | }) 139 | .then(res => res.json()) 140 | .then((res: any) => { 141 | return res.id; 142 | }) 143 | .catch(err => { 144 | console.error(err); 145 | return []; 146 | }); 147 | 148 | return response; 149 | }; 150 | -------------------------------------------------------------------------------- /src/store/context/settings/settingsProvider.tsx: -------------------------------------------------------------------------------- 1 | import { useLocalStorage } from '@hooks/useLocalStorage'; 2 | import { APP_SETTINGS_KEY } from '@src/config'; 3 | import React, { createContext, ReactNode, useCallback, useMemo, useReducer, useState } from 'react'; 4 | import { Merge } from 'type-fest'; 5 | 6 | // State 类型定义 7 | export type SettingsState = { 8 | readAllPostsInTopic: boolean; // 是否阅读主题所有帖子,false 从最后的内容开始看 9 | singlePostsReading: number; // 单次阅读帖子数,控制 timings 请求 body 行为 10 | maxRetryTimes: number; // 最大重试次数 11 | windowPeriodTopics: number[][]; // 空窗期随机阅读的帖子列表,[[, <阅读楼层数>]] 12 | getCsrfTokenFromHtml: boolean; // 是否从 html 中获取 csrf token 13 | maxLogLineNum: number; // 日志最大条数 14 | uiWidth: number | string; // ui 宽度 15 | uiQueueHeight: number | string; // ui 任务队列高度 16 | uiLogHeight: number | string; // ui 日志高度 17 | uiTagFontSize: number | string; // ui 标签字体大小 18 | uiQueueFontSize: number | string; // ui 队列字体大小 19 | uiLogFontSize: number | string; // ui 日志字体大小 20 | }; 21 | 22 | // Action 类型定义 23 | type SettingsAction = 24 | | { type: 'RESET'; payload: SettingsState } 25 | | { type: 'UPDATE_ALL'; payload: Partial } 26 | | { type: 'UPDATE_FIELD'; payload: { field: keyof SettingsState; value: SettingsState[keyof SettingsState] } }; 27 | 28 | // Reducer 函数 29 | function settingsReducer(state: SettingsState, action: SettingsAction): SettingsState { 30 | switch (action.type) { 31 | case 'RESET': 32 | return action.payload; 33 | case 'UPDATE_ALL': 34 | return { ...state, ...action.payload }; 35 | case 'UPDATE_FIELD': 36 | return { 37 | ...state, 38 | [action.payload.field]: action.payload.value, 39 | }; 40 | default: 41 | return state; 42 | } 43 | } 44 | 45 | export type SettingsCaches = 'localStorage'; 46 | 47 | export type SettingsProviderProps = { 48 | settings: SettingsState; 49 | children: ReactNode; 50 | caches?: SettingsCaches; 51 | }; 52 | 53 | export type SettingsContextValue = Merge< 54 | SettingsState, 55 | { 56 | canReset: boolean; 57 | onReset: VoidFunction; 58 | onUpdate: (updateValue: Partial) => void; 59 | onUpdateField: (name: keyof SettingsState, updateValue: SettingsState[keyof SettingsState]) => void; 60 | // Dialog 61 | openDialog: boolean; 62 | onCloseDialog: VoidFunction; 63 | onToggleDialog: VoidFunction; 64 | } 65 | >; 66 | 67 | export const SettingsContext = createContext(null); 68 | 69 | export const SettingsConsumer = SettingsContext.Consumer; 70 | 71 | export function SettingsProvider({ settings, children, caches = 'localStorage' }: SettingsProviderProps) { 72 | // 使用 useReducer 73 | const [state, dispatch] = useReducer(settingsReducer, settings); 74 | const localStorage = useLocalStorage(APP_SETTINGS_KEY, settings); 75 | // const values = caches === 'localStorage' ? localStorage : localStorage; 76 | const values = localStorage; 77 | 78 | // 包装 dispatch 函数 79 | const onReset = useCallback(() => { 80 | dispatch({ type: 'RESET', payload: settings }); 81 | values.resetState(); 82 | }, [settings, values]); 83 | 84 | const onUpdate = useCallback((updateValue: Partial) => { 85 | dispatch({ type: 'UPDATE_ALL', payload: updateValue }); 86 | values.setState(updateValue); 87 | }, [values]); 88 | 89 | const onUpdateField = useCallback((field: keyof SettingsState, value: SettingsState[keyof SettingsState]) => { 90 | dispatch({ type: 'UPDATE_FIELD', payload: { field, value } }); 91 | values.setField(field, value); 92 | }, [values]); 93 | 94 | const [openDialog, setOpenDialog] = useState(false); 95 | 96 | const onToggleDialog = useCallback(() => { 97 | setOpenDialog(prevState => !prevState); 98 | }, []); 99 | 100 | const onCloseDialog = useCallback(() => { 101 | setOpenDialog(false); 102 | }, []); 103 | 104 | const memorizedValue = useMemo( 105 | () => ({ 106 | ...state, 107 | canReset: values.canReset, 108 | onReset, 109 | onUpdate, 110 | onUpdateField, 111 | openDialog, 112 | onCloseDialog, 113 | onToggleDialog, 114 | }), 115 | [ 116 | state, 117 | values.canReset, 118 | onReset, 119 | onUpdate, 120 | onUpdateField, 121 | openDialog, 122 | onCloseDialog, 123 | onToggleDialog, 124 | ], 125 | ); 126 | 127 | return {children}; 128 | } 129 | -------------------------------------------------------------------------------- /src/types/globals.d.ts: -------------------------------------------------------------------------------- 1 | interface Window { 2 | unsafeWindow?: Window; 3 | } 4 | 5 | interface XMLHttpRequest { 6 | _custom_storage: { 7 | method: string; 8 | url: string | URL; 9 | }; 10 | } 11 | -------------------------------------------------------------------------------- /src/types/monkey.d.ts: -------------------------------------------------------------------------------- 1 | declare module 'clientMonkey' { 2 | export * from 'vite-plugin-monkey/dist/client'; 3 | } 4 | -------------------------------------------------------------------------------- /src/utils/core.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * 获取随机整数 3 | * 4 | * @param start 范围开始 5 | * @param end 范围结束 6 | * @returns 范围内随机整数 7 | */ 8 | export const randInt = (start: number, end: number): number => { 9 | return Math.floor(Math.random() * (end - start + 1)) + start; 10 | }; 11 | 12 | /** 13 | * 随机睡眠(毫秒) 14 | * 15 | * @param start 范围开始 16 | * @param end 范围结束 17 | */ 18 | export const randSleep = async (start: number = 2000, end: number = 3000): Promise => { 19 | // 生成随机整数 randSleepTime,范围在 start 到 end 之间 20 | const randSleepTime = randInt(start, end); 21 | // 睡眠时间 22 | return new Promise((resolve, reject) => { 23 | setTimeout(resolve, randSleepTime); 24 | }); 25 | }; 26 | 27 | /** 28 | * 检查是否为原生方法 29 | * 30 | * @param func 方法 31 | * @returns 是否为原生方法 32 | */ 33 | export const isNativeFunction = (func: any): boolean => { 34 | if (typeof func !== 'function') { 35 | return false; 36 | } 37 | 38 | // 获取函数的字符串表示形式 39 | const funcString = func.toString(); 40 | 41 | // 检查字符串是否包含 "[native code]" 42 | return funcString.includes('[native code]'); 43 | }; 44 | 45 | /** 46 | * 是否为原生方法,不是则抛出异常 47 | * 48 | * @param func 方法 49 | * @returns 方法 50 | */ 51 | export const ensureNativeMethods = (func: any) => { 52 | if (isNativeFunction(func)) { 53 | return func; 54 | } 55 | 56 | throw new Error(`${func.name} is not native`); 57 | }; 58 | 59 | /** 60 | * 匹配地址 61 | * 62 | * @param url 地址 63 | * @param pattern 模式 64 | */ 65 | export const matchUrl = (url: string | URL, pattern: RegExp) => { 66 | if (typeof url === 'string') { 67 | return pattern.test(url); 68 | } 69 | return false; 70 | }; 71 | 72 | /** 73 | * 匹配话题地址 74 | * 75 | * @param url 地址 76 | */ 77 | export const isTopicUrl = (url: string | URL) => { 78 | // const pattern = /^https:\/\/linux\.do\/t\/[a-zA-Z0-9_-]+\.json($|\?)/; 79 | const patternTopic = /^\/t\/[0-9]+\.json($|\?)/; 80 | const patternPost = /^\/t\/[0-9]+\/[0-9]+\.json($|\?)/; 81 | return matchUrl(url, patternPost) || matchUrl(url, patternTopic); 82 | }; 83 | 84 | /** 85 | * 匹配计时地址 86 | * 87 | * @param url 地址 88 | */ 89 | export const isTimingsUrl = (url: string) => { 90 | const patternTimings = '/topics/timings'; 91 | return url === patternTimings; 92 | }; 93 | 94 | /** 95 | * 匹配拉取地址 96 | * 97 | * @param url 地址 98 | */ 99 | export const isPollUrl = (url: string) => { 100 | const patternPoll = /^\/message-bus\/[a-z0-9]+\/poll(\?.*)?$/; 101 | return matchUrl(url, patternPoll); 102 | }; 103 | 104 | /** 105 | * 创建随机 id 106 | * 107 | * @param length 长度 108 | */ 109 | export const genRandId = (length = 10) => { 110 | const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; 111 | let result = ''; 112 | for (let i = 0; i < length; i += 1) { 113 | result += chars.charAt(Math.floor(Math.random() * chars.length)); 114 | } 115 | return result; 116 | }; 117 | -------------------------------------------------------------------------------- /src/utils/storage.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * 检查 local storage 是否存在 3 | */ 4 | export const localStorageAvailable = () => { 5 | try { 6 | const key = '__some_random_key_you_are_not_going_to_use__'; 7 | window.localStorage.setItem(key, key); 8 | window.localStorage.removeItem(key); 9 | return true; 10 | } catch (error) { 11 | return false; 12 | } 13 | }; 14 | 15 | /** 16 | * 获取 local storage 中的数据 17 | * 18 | * @param key 键 19 | * @param defaultValue 默认值 20 | */ 21 | export const localStorageGetItem = (key: string, defaultValue = '') => { 22 | const storageAvailable = localStorageAvailable(); 23 | 24 | let value; 25 | 26 | if (storageAvailable) { 27 | value = localStorage.getItem(key) || defaultValue; 28 | } 29 | 30 | return value; 31 | }; 32 | -------------------------------------------------------------------------------- /src/utils/time.ts: -------------------------------------------------------------------------------- 1 | import dayjs from 'dayjs'; 2 | import duration from 'dayjs/plugin/duration'; 3 | 4 | dayjs.extend(duration); 5 | 6 | /** 7 | * 转可读时间 8 | * 9 | * @param t 时长(单位:ms) 10 | */ 11 | export const formatDuration = (t: number) => { 12 | const diff = dayjs.duration(t); 13 | 14 | const years = diff.years(); 15 | const days = diff.days(); 16 | const hours = diff.hours(); 17 | const minutes = diff.minutes(); 18 | const seconds = diff.seconds(); 19 | const ms = diff.milliseconds(); 20 | 21 | const result = []; 22 | 23 | if (years > 0) result.push(`${years}年`); 24 | if (days > 0) result.push(`${days}天`); 25 | if (hours > 0) result.push(`${hours}小时`); 26 | if (minutes > 0) result.push(`${minutes}分钟`); 27 | if (seconds > 0) result.push(`${seconds}秒`); 28 | if (ms > 0) result.push(`${ms}毫秒`); 29 | 30 | return result.join(''); 31 | }; 32 | 33 | /** 34 | * 转短可读时间 35 | * 36 | * @param t 时长(单位:ms) 37 | */ 38 | export const formatDurationShort = (t: number) => { 39 | const diff = dayjs.duration(t); 40 | 41 | const years = diff.years(); 42 | const days = diff.days(); 43 | const hours = diff.hours(); 44 | const minutes = diff.minutes(); 45 | const seconds = diff.seconds(); 46 | const ms = diff.milliseconds(); 47 | 48 | if (years > 0) return `${years}年`; 49 | if (days > 0) return `${days}天`; 50 | if (hours > 0) return `${hours}小时`; 51 | if (minutes > 0) return `${minutes}分钟`; 52 | if (seconds > 0) return `${seconds}秒`; 53 | if (ms > 0) return `${ms}毫秒`; 54 | 55 | return '0秒'; 56 | }; 57 | 58 | export { dayjs }; 59 | -------------------------------------------------------------------------------- /src/vite-env.d.ts: -------------------------------------------------------------------------------- 1 | /// 2 | /// 3 | //// 4 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "typeRoots": [ 4 | "node_modules/@types", 5 | "src/types" 6 | ], 7 | "target": "ESNext", 8 | "useDefineForClassFields": true, 9 | "lib": [ 10 | "DOM", 11 | "DOM.Iterable", 12 | "ESNext" 13 | ], 14 | "allowJs": false, 15 | "skipLibCheck": true, 16 | "esModuleInterop": false, 17 | "allowSyntheticDefaultImports": true, 18 | "strict": true, 19 | "forceConsistentCasingInFileNames": true, 20 | "module": "ESNext", 21 | "moduleResolution": "Node", 22 | "resolveJsonModule": true, 23 | "isolatedModules": true, 24 | "noEmit": true, 25 | "jsx": "react-jsx", 26 | "paths": { 27 | "@src/*": [ 28 | "./src/*" 29 | ], 30 | "@assets/*": [ 31 | "./src/assets/*" 32 | ], 33 | "@components/*": [ 34 | "./src/components/*" 35 | ], 36 | "@config/*": [ 37 | "./src/config/*" 38 | ], 39 | "@core/*": [ 40 | "./src/core/*" 41 | ], 42 | "@hooks/*": [ 43 | "./src/hooks/*" 44 | ], 45 | "@lib/*": [ 46 | "./src/lib/*" 47 | ], 48 | "@sections/*": [ 49 | "./src/sections/*" 50 | ], 51 | "@server/*": [ 52 | "./src/server/*" 53 | ], 54 | "@store/*": [ 55 | "./src/store/*" 56 | ], 57 | "@gTypes/*": [ 58 | "./src/types/*" 59 | ], 60 | "@utils/*": [ 61 | "./src/utils/*" 62 | ] 63 | } 64 | }, 65 | "include": [ 66 | "src" 67 | ], 68 | "references": [ 69 | { 70 | "path": "./tsconfig.node.json" 71 | } 72 | ] 73 | } 74 | -------------------------------------------------------------------------------- /tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "composite": true, 4 | "module": "ESNext", 5 | "moduleResolution": "Node", 6 | "allowSyntheticDefaultImports": true 7 | }, 8 | "include": ["vite.config.ts"] 9 | } -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from 'vite'; 2 | import react from '@vitejs/plugin-react'; 3 | import monkey, { cdn } from 'vite-plugin-monkey'; 4 | import tsconfigPaths from 'vite-tsconfig-paths'; 5 | // import path from "path"; 6 | 7 | // https://vitejs.dev/config/ 8 | export default defineConfig({ 9 | css: { 10 | preprocessorOptions: { 11 | scss: { 12 | api: 'modern-compiler' // or "modern", 13 | }, 14 | }, 15 | }, 16 | plugins: [ 17 | react(), 18 | tsconfigPaths(), 19 | monkey({ 20 | entry: 'src/index.tsx', // userscript entry file path 21 | userscript: { 22 | // name: 'linuxdo-browse', 23 | namespace: 'linuxdo-browse', 24 | // version: '0.1.0', 25 | author: 'delph1s', 26 | description: 'LinuxDo蓝点消除计划', 27 | // homepage: '', 28 | homepageURL: 'https://github.com/delph1s/linuxdo-browse', 29 | // website: '', 30 | // source: '', 31 | // icon: '', 32 | iconURL: 'https://cdn.linux.do/uploads/default/original/3X/9/d/9dd49731091ce8656e94433a26a3ef36062b3994.png', 33 | // defaulticon: '', 34 | // icon64: '', 35 | // icon64URL: '', 36 | // updateURL: '', 37 | // downloadURL: '', 38 | // supportURL: '', 39 | // include: [], 40 | match: ['*://linux.do/', '*://linux.do/*'], 41 | // 'exclude-match': ['*://linux.do/*.json'], 42 | exclude: ['*://linux.do/*.json'], 43 | // require: [], 44 | // resource: {}, 45 | // connect: [ 46 | // 'connect.linux.do', 47 | // ], 48 | // sandbox: 'raw', 49 | // antifeature: [], 50 | // noframes: false, 51 | // webRequest: [], 52 | // 'inject-into': 'page', 53 | // unwrap: false, 54 | // greasyfork 55 | license: 'GPLv2', 56 | // contributionURL: '', 57 | // contributionAmount: '1', 58 | // compatible: '', 59 | // incompatible: '', 60 | 'run-at': 'document-end', 61 | grant: [ 62 | // 'GM_cookie', 63 | // 'GM_xmlhttpRequest', 64 | ], 65 | }, 66 | // format: { 67 | // generate: uOptions => { 68 | // console.log(uOptions.userscript); 69 | // if (uOptions.mode === 'serve') { 70 | // return '测试'; 71 | // } 72 | // if (uOptions.mode === 'build') { 73 | // return '打包' 74 | // } 75 | // if (uOptions.mode === 'meta') { 76 | // return '元' 77 | // } 78 | // } 79 | // }, 80 | // clientAlias: 'monkeyClient', 81 | server: { 82 | open: false, 83 | prefix: name => { 84 | return `${name}-dev`; 85 | }, 86 | mountGmApi: false, 87 | }, 88 | build: { 89 | // fileName: 'linuxdo-browse', 90 | metaFileName: true, 91 | externalGlobals: { 92 | react: cdn.npmmirror('React', 'umd/react.production.min.js'), 93 | 'react-dom': cdn.npmmirror('ReactDOM', 'umd/react-dom.production.min.js'), 94 | dayjs: cdn.npmmirror('dayjs', 'dayjs.min.js'), 95 | 'dayjs/plugin/duration': cdn.npmmirror( 96 | 'dayjs_plugin_duration', 97 | 'plugin/duration.js', 98 | ), 99 | lodash: cdn.npmmirror('_', 'lodash.min.js'), 100 | // ahooks use these 101 | 'lodash/throttle': '_.throttle', 102 | 'lodash/debounce': '_.debounce', 103 | 'lodash/isEqual': '_.isEqual', 104 | }, 105 | autoGrant: true, 106 | // externalResource: {}, 107 | // systemjs: 'inline', 108 | // cssSideEffects: css => { 109 | // return (css) => { 110 | // console.log(css); 111 | // } 112 | // } 113 | }, 114 | }), 115 | ], 116 | build: { 117 | minify: false, // greasyfork 要求可读代码 118 | }, 119 | }); 120 | --------------------------------------------------------------------------------