├── src ├── index.scss ├── icon.png ├── libs │ ├── b3-typography.svelte │ ├── components │ │ ├── b3-typography.svelte │ │ ├── Form │ │ │ ├── index.ts │ │ │ ├── form-wrap.svelte │ │ │ └── form-input.svelte │ │ └── setting-panel.svelte │ ├── index.d.ts │ ├── promise-pool.ts │ ├── const.ts │ ├── setting-item.svelte │ ├── setting-panel.svelte │ ├── dialog.ts │ └── setting-utils.ts ├── assets │ └── formatPainter_mouse2.png ├── index.css ├── defaultSettings.ts ├── types │ ├── api.d.ts │ └── index.d.ts ├── components │ └── LoadingDialog.svelte ├── hello.svelte ├── utils │ └── i18n.ts ├── setting-example.svelte ├── index.ts └── api.ts ├── .eslintignore ├── scripts ├── .gitignore ├── elevate.ps1 ├── make_install.js ├── make_dev_link.js ├── make_dev_copy.js ├── update_version.js └── utils.js ├── icon.png ├── preview.png ├── assets └── formatPainter_mouse2.png ├── .gitignore ├── public └── i18n │ ├── zh_CN.json │ ├── en_US.json │ └── README.md ├── index.css ├── tsconfig.node.json ├── release.sh ├── .eslintrc.js ├── svelte.config.js ├── README_zh_CN.md ├── plugin.json ├── package.json ├── tsconfig.json ├── .github └── workflows │ └── release.yml ├── README.md ├── yaml-plugin.js ├── CHANGELOG.md ├── webpack.config.js ├── vite.config.ts ├── index.js └── LICENSE /src/index.scss: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /.eslintignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | dist 3 | index.js 4 | -------------------------------------------------------------------------------- /scripts/.gitignore: -------------------------------------------------------------------------------- 1 | .venv 2 | build 3 | dist 4 | *.exe 5 | *.spec 6 | -------------------------------------------------------------------------------- /icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Achuan-2/siyuan-plugin-formatPainter/HEAD/icon.png -------------------------------------------------------------------------------- /preview.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Achuan-2/siyuan-plugin-formatPainter/HEAD/preview.png -------------------------------------------------------------------------------- /src/icon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Achuan-2/siyuan-plugin-formatPainter/HEAD/src/icon.png -------------------------------------------------------------------------------- /src/libs/b3-typography.svelte: -------------------------------------------------------------------------------- 1 |
2 | 3 |
-------------------------------------------------------------------------------- /src/libs/components/b3-typography.svelte: -------------------------------------------------------------------------------- 1 |
2 | 3 |
-------------------------------------------------------------------------------- /assets/formatPainter_mouse2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Achuan-2/siyuan-plugin-formatPainter/HEAD/assets/formatPainter_mouse2.png -------------------------------------------------------------------------------- /src/assets/formatPainter_mouse2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Achuan-2/siyuan-plugin-formatPainter/HEAD/src/assets/formatPainter_mouse2.png -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .idea 2 | .vscode 3 | .DS_Store 4 | pnpm-lock.yaml 5 | package-lock.json 6 | package.zip 7 | node_modules 8 | dev 9 | dist 10 | build 11 | tmp 12 | -------------------------------------------------------------------------------- /public/i18n/zh_CN.json: -------------------------------------------------------------------------------- 1 | { 2 | "helloPlugin": "你好,插件!", 3 | "byePlugin": "再见,插件!", 4 | "tips": "格式刷", 5 | "enable": "格式刷已启用,按【Esc键】或者【右下角dock栏按钮】退出格式刷模式", 6 | "disable": "格式刷已关闭", 7 | "closeTips": "关闭格式刷" 8 | } -------------------------------------------------------------------------------- /src/libs/components/Form/index.ts: -------------------------------------------------------------------------------- 1 | import FormInput from './form-input.svelte'; 2 | import FormWrap from './form-wrap.svelte'; 3 | 4 | const Form = { Wrap: FormWrap, Input: FormInput }; 5 | export default Form; 6 | export { FormInput, FormWrap }; 7 | -------------------------------------------------------------------------------- /index.css: -------------------------------------------------------------------------------- 1 | body[data-format-painter-enable="true"] .protyle-wysiwyg { 2 | cursor: url("plugins/siyuan-plugin-formatPainter/assets/formatPainter_mouse2.png"), auto; 3 | } 4 | 5 | body[data-format-painter-enable="false"] .protyle-wysiwyg { 6 | cursor: auto; 7 | } -------------------------------------------------------------------------------- /src/index.css: -------------------------------------------------------------------------------- 1 | body[data-format-painter-enable="true"] .protyle-wysiwyg { 2 | cursor: url("plugins/siyuan-plugin-formatPainter/assets/formatPainter_mouse2.png"), auto; 3 | } 4 | 5 | body[data-format-painter-enable="false"] .protyle-wysiwyg { 6 | cursor: auto; 7 | } -------------------------------------------------------------------------------- /src/defaultSettings.ts: -------------------------------------------------------------------------------- 1 | import { t } from "./utils/i18n"; 2 | 3 | export const getDefaultSettings = () => ({ 4 | textinput: t('settings.textinput.value'), 5 | slider: 0.5, 6 | checkbox: false, 7 | textarea: t('settings.textarea.value'), 8 | select: 'option1', 9 | }); 10 | -------------------------------------------------------------------------------- /tsconfig.node.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "composite": true, 4 | "skipLibCheck": true, 5 | "module": "ESNext", 6 | "moduleResolution": "Node", 7 | "allowSyntheticDefaultImports": true 8 | }, 9 | "include": [ 10 | "vite.config.ts" 11 | ] 12 | } -------------------------------------------------------------------------------- /public/i18n/en_US.json: -------------------------------------------------------------------------------- 1 | { 2 | "helloPlugin": "Hello, Plugin!", 3 | "byePlugin": "Bye, Plugin!", 4 | "tips": "Format Painter ", 5 | "enable": "Format Painter is enabled, press [Esc key] or [dock bar button in the lower right corner] to exit the Format Painter mode", 6 | "disable": "Format Painter is disabled", 7 | "closeTips": "Disable Format Painter" 8 | } -------------------------------------------------------------------------------- /release.sh: -------------------------------------------------------------------------------- 1 | # Change directory to the script's directory 2 | cd "$(dirname $0)" 3 | 4 | # Get version from theme.json 5 | version=v$(grep -oP '(?<="version": ")[^"]+' plugin.json) 6 | 7 | # Commit changes 8 | git add . 9 | git commit -m "🔖 $version" 10 | git push 11 | 12 | # 判断 tag 是否存在 13 | if git rev-parse --quiet --verify $version >/dev/null; then 14 | # 删除本地仓库中的 tag 15 | git tag -d $version 16 | # 删除远程仓库中的 tag 17 | git push origin ":refs/tags/$version" 18 | 19 | fi 20 | 21 | # 创建新的 tag 22 | git tag $version # Create a tag 23 | 24 | # 推送新的 tag 到远程仓库 25 | git push origin --tags 26 | # git archive --format zip --output ../package-$version.zip HEAD # Create a zip archive -------------------------------------------------------------------------------- /.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | root: true, 3 | env: {node: true, browser: true, es6: true}, 4 | parser: "@typescript-eslint/parser", 5 | plugins: [ 6 | "@typescript-eslint", 7 | ], 8 | extends: [ 9 | "eslint:recommended", 10 | "plugin:@typescript-eslint/recommended", 11 | ], 12 | rules: { 13 | semi: [2, "always"], 14 | quotes: [2, "double", {"avoidEscape": true}], 15 | "no-async-promise-executor": "off", 16 | "no-prototype-builtins": "off", 17 | "no-useless-escape": "off", 18 | "no-irregular-whitespace": "off", 19 | "@typescript-eslint/ban-ts-comment": "off", 20 | "@typescript-eslint/no-var-requires": "off", 21 | "@typescript-eslint/explicit-function-return-type": "off", 22 | "@typescript-eslint/explicit-module-boundary-types": "off", 23 | "@typescript-eslint/no-explicit-any": "off", 24 | }, 25 | }; 26 | -------------------------------------------------------------------------------- /svelte.config.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2023-05-19 19:49:13 5 | * @FilePath : /svelte.config.js 6 | * @LastEditTime : 2024-04-19 19:01:55 7 | * @Description : 8 | */ 9 | import { vitePreprocess } from "@sveltejs/vite-plugin-svelte" 10 | 11 | const NoWarns = new Set([ 12 | "a11y-click-events-have-key-events", 13 | "a11y-no-static-element-interactions", 14 | "a11y-no-noninteractive-element-interactions" 15 | ]); 16 | 17 | export default { 18 | // Consult https://svelte.dev/docs#compile-time-svelte-preprocess 19 | // for more information about preprocessors 20 | preprocess: vitePreprocess(), 21 | onwarn: (warning, handler) => { 22 | // suppress warnings on `vite dev` and `vite build`; but even without this, things still work 23 | if (NoWarns.has(warning.code)) return; 24 | handler(warning); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /scripts/elevate.ps1: -------------------------------------------------------------------------------- 1 | # Copyright (c) 2024 by frostime. All Rights Reserved. 2 | # @Author : frostime 3 | # @Date : 2024-09-06 19:15:53 4 | # @FilePath : /scripts/elevate.ps1 5 | # @LastEditTime : 2024-09-06 19:39:13 6 | # @Description : Force to elevate the script to admin privilege. 7 | 8 | param ( 9 | [string]$scriptPath 10 | ) 11 | 12 | $scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Definition 13 | $projectDir = Split-Path -Parent $scriptDir 14 | 15 | if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) { 16 | $args = "-NoProfile -ExecutionPolicy Bypass -File `"" + $MyInvocation.MyCommand.Path + "`" -scriptPath `"" + $scriptPath + "`"" 17 | Start-Process powershell.exe -Verb RunAs -ArgumentList $args -WorkingDirectory $projectDir 18 | exit 19 | } 20 | 21 | Set-Location -Path $projectDir 22 | & node $scriptPath 23 | 24 | pause 25 | -------------------------------------------------------------------------------- /README_zh_CN.md: -------------------------------------------------------------------------------- 1 | [English](./README.md) 2 | 3 | 4 | ## 🚀开发背景 5 | 6 | 当在思源笔记做笔记需要添加样式的时候,如果想要给多处的文字批量添加样式,比如批量加粗、批量添加行内代码,每次都要按快捷键或者通过悬浮工具栏点击添加样式,有点繁琐,两种以上的样式叠加(例如背景色+加粗)以及三种以上的样式叠加(如字体色+字体大小+加粗)只会更繁琐,花费很多时间 😖💔 7 | 8 | 9 | 因此模仿office的格式刷,开发了这个格式刷插件,希望能成为你的思源笔记美化小帮手,帮你节省时间快速美化笔记!💃🕺 10 | 11 | ## ✨功能介绍 12 | 13 | > 本插件的最低思源笔记版本要求为v3.1.12 14 | 15 | - **进入格式刷模式**:选中文字,在悬浮工具栏点击「格式刷」按钮即可复制样式(支持叠加的样式),之后选中其他文字后,可以自动快速添加复制的样式 16 | - **支持复制的行内样式**:字体大小、背景色、文字颜色、镂空、投影、加粗、行内代码、键盘样式、下划线、删除线、上标、下标、高亮等 17 | - **支持复制无样式用来清空选中的文本样式** 18 | - **退出格式刷模式**: 19 | - 按Esc建即可 20 | - 当格式刷启动时候,dock底栏最右侧添加一个按钮,按钮图案渐变闪烁,点击该按钮可以退出格式刷模式 21 | 22 | ![](https://fastly.jsdelivr.net/gh/Achuan-2/PicBed/assets/思源笔记格式刷插件-2024-10-10.gif) 23 | 24 | 25 | 26 | ## ❤️用爱发电 27 | 28 | 穷苦研究生在读ing,如果喜欢我的插件,欢迎给GitHub仓库点star和捐赠,这会激励我继续完善此插件和开发新插件。 29 | 30 | ![](https://cdn.nlark.com/yuque/0/2024/jpeg/1408046/1714754573393-9c7f70b0-05ec-489e-b5a2-1a37fb681f6f.jpeg?x-oss-process=image%2Fformat%2Cwebp%2Fresize%2Cw_592%2Climit_0%2Finterlace%2C1) -------------------------------------------------------------------------------- /plugin.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "siyuan-plugin-formatPainter", 3 | "author": "Achuan-2", 4 | "url": "https://github.com/Achuan-2/siyuan-plugin-formatPainter", 5 | "version": "1.1.6", 6 | "minAppVersion": "3.1.12", 7 | "backends": [ 8 | "windows", 9 | "linux", 10 | "darwin", 11 | "ios", 12 | "android", 13 | "docker" 14 | ], 15 | "frontends": [ 16 | "desktop", 17 | "browser-desktop", 18 | "desktop-window" 19 | ], 20 | "displayName": { 21 | "default": "Format Painter", 22 | "zh_CN": "格式刷" 23 | }, 24 | "description": { 25 | "default": "Use the format painter to batch apply styles", 26 | "zh_CN": "使用格式刷批量添加样式" 27 | }, 28 | "readme": { 29 | "default": "README.md", 30 | "zh_CN": "README_zh_CN.md" 31 | }, 32 | "funding": { 33 | "openCollective": "", 34 | "patreon": "", 35 | "github": "", 36 | "custom": [ 37 | "https://www.yuque.com/achuan-2" 38 | ] 39 | }, 40 | "keywords": [ 41 | "Format Painter", 42 | "格式刷" 43 | ] 44 | } 45 | -------------------------------------------------------------------------------- /public/i18n/README.md: -------------------------------------------------------------------------------- 1 | 思源支持的 i18n 文件范围,可以在控制台 `siyuan.config.langs` 中查看。以下是目前(2024-10-24)支持的语言方案: 2 | 3 | The range of i18n files supported by SiYuan can be viewed in the console under `siyuan.config.langs`. Below are the language schemes currently supported as of now (October 24, 2024) : 4 | 5 | ```js 6 | >>> siyuan.config.langs.map( lang => lang.name) 7 | ['de_DE', 'en_US', 'es_ES', 'fr_FR', 'he_IL', 'it_IT', 'ja_JP', 'pl_PL', 'ru_RU', 'zh_CHT', 'zh_CN'] 8 | ``` 9 | 10 | 在插件开发中,默认使用 JSON 格式作为国际化(i18n)的载体文件。如果您更喜欢使用 YAML 语法,可以将 JSON 文件替换为 YAML 文件(例如 `en_US.yaml`),并在其中编写 i18n 文本。本模板提供了相关的 Vite 插件,可以在编译时自动将 YAML 文件转换为 JSON 文件(请参见 `/yaml-plugin.js`)。本 MD 文件 和 YAML 文件会在 `npm run build` 时自动从 `dist` 目录下删除,仅保留必要的 JSON 文件共插件系统使用。 11 | 12 | In plugin development, JSON format is used by default as the carrier file for internationalization (i18n). If you prefer to use YAML syntax, you can replace the JSON file with a YAML file (e.g., `en_US.yaml`) and write the i18n text within it. This template provides a related Vite plugin that can automatically convert YAML files to JSON files during the compilation process (see `/yaml-plugin.js`). This markdown file and YAML files will be automatically removed from the `dist` directory during `npm run build`, leaving only the necessary JSON files for plugin system to use. 13 | -------------------------------------------------------------------------------- /src/types/api.d.ts: -------------------------------------------------------------------------------- 1 | interface IResGetNotebookConf { 2 | box: string; 3 | conf: NotebookConf; 4 | name: string; 5 | } 6 | 7 | interface IReslsNotebooks { 8 | notebooks: Notebook[]; 9 | } 10 | 11 | interface IResUpload { 12 | errFiles: string[]; 13 | succMap: { [key: string]: string }; 14 | } 15 | 16 | interface IResdoOperations { 17 | doOperations: doOperation[]; 18 | undoOperations: doOperation[] | null; 19 | } 20 | 21 | interface IResGetBlockKramdown { 22 | id: BlockId; 23 | kramdown: string; 24 | } 25 | 26 | interface IResGetChildBlock { 27 | id: BlockId; 28 | type: BlockType; 29 | subtype?: BlockSubType; 30 | } 31 | 32 | interface IResGetTemplates { 33 | content: string; 34 | path: string; 35 | } 36 | 37 | interface IResReadDir { 38 | isDir: boolean; 39 | isSymlink: boolean; 40 | name: string; 41 | } 42 | 43 | interface IResExportMdContent { 44 | hPath: string; 45 | content: string; 46 | } 47 | 48 | interface IResBootProgress { 49 | progress: number; 50 | details: string; 51 | } 52 | 53 | interface IResForwardProxy { 54 | body: string; 55 | contentType: string; 56 | elapsed: number; 57 | headers: { [key: string]: string }; 58 | status: number; 59 | url: string; 60 | } 61 | 62 | interface IResExportResources { 63 | path: string; 64 | } 65 | 66 | -------------------------------------------------------------------------------- /src/libs/index.d.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2024-04-19 18:30:12 5 | * @FilePath : /src/libs/index.d.ts 6 | * @LastEditTime : 2024-04-30 16:39:54 7 | * @Description : 8 | */ 9 | type TSettingItemType = "checkbox" | "select" | "textinput" | "textarea" | "number" | "slider" | "button" | "hint" | "custom"; 10 | 11 | interface ISettingItemCore { 12 | type: TSettingItemType; 13 | key: string; 14 | value: any; 15 | placeholder?: string; 16 | rows?: number; // 为 textarea 类型使用 17 | slider?: { 18 | min: number; 19 | max: number; 20 | step: number; 21 | }; 22 | options?: { [key: string | number]: string }; 23 | button?: { 24 | label: string; 25 | callback: () => void; 26 | } 27 | } 28 | 29 | interface ISettingItem extends ISettingItemCore { 30 | title: string; 31 | description: string; 32 | direction?: "row" | "column"; 33 | rows?: number; 34 | } 35 | 36 | 37 | //Interface for setting-utils 38 | interface ISettingUtilsItem extends ISettingItem { 39 | action?: { 40 | callback: () => void; 41 | } 42 | createElement?: (currentVal: any) => HTMLElement; 43 | getEleVal?: (ele: HTMLElement) => any; 44 | setEleVal?: (ele: HTMLElement, val: any) => void; 45 | } 46 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "plugin-sample-vite-svelte", 3 | "version": "0.3.6", 4 | "type": "module", 5 | "description": "This is a sample plugin based on vite and svelte for Siyuan (https://b3log.org/siyuan)", 6 | "repository": "", 7 | "homepage": "", 8 | "author": "frostime", 9 | "license": "MIT", 10 | "scripts": { 11 | "dev": "cross-env NODE_ENV=development VITE_SOURCEMAP=inline vite build --watch", 12 | "build": "cross-env NODE_ENV=production vite build", 13 | "make-link": "node --no-warnings ./scripts/make_dev_link.js", 14 | "make_dev_copy": "node --no-warnings ./scripts/make_dev_copy.js", 15 | "update-version": "node --no-warnings ./scripts/update_version.js", 16 | "make-install": "vite build && node --no-warnings ./scripts/make_install.js" 17 | }, 18 | "devDependencies": { 19 | "@sveltejs/vite-plugin-svelte": "^3.1.0", 20 | "@tsconfig/svelte": "^4.0.1", 21 | "@types/node": "^20.3.0", 22 | "cross-env": "^7.0.3", 23 | "fast-glob": "^3.2.12", 24 | "glob": "^10.0.0", 25 | "js-yaml": "^4.1.0", 26 | "minimist": "^1.2.8", 27 | "rollup-plugin-livereload": "^2.0.5", 28 | "sass": "^1.63.3", 29 | "siyuan": "1.1.1", 30 | "svelte": "^4.2.19", 31 | "ts-node": "^10.9.1", 32 | "typescript": "^5.1.3", 33 | "vite": "^5.2.9", 34 | "vite-plugin-static-copy": "^1.0.2", 35 | "vite-plugin-zip-pack": "^1.0.5" 36 | } 37 | } -------------------------------------------------------------------------------- /src/libs/promise-pool.ts: -------------------------------------------------------------------------------- 1 | export default class PromiseLimitPool { 2 | private maxConcurrent: number; 3 | private currentRunning = 0; 4 | private queue: (() => void)[] = []; 5 | private promises: Promise[] = []; 6 | 7 | constructor(maxConcurrent: number) { 8 | this.maxConcurrent = maxConcurrent; 9 | } 10 | 11 | add(fn: () => Promise): void { 12 | const promise = new Promise((resolve, reject) => { 13 | const run = async () => { 14 | try { 15 | this.currentRunning++; 16 | const result = await fn(); 17 | resolve(result); 18 | } catch (error) { 19 | reject(error); 20 | } finally { 21 | this.currentRunning--; 22 | this.next(); 23 | } 24 | }; 25 | 26 | if (this.currentRunning < this.maxConcurrent) { 27 | run(); 28 | } else { 29 | this.queue.push(run); 30 | } 31 | }); 32 | this.promises.push(promise); 33 | } 34 | 35 | async awaitAll(): Promise { 36 | return Promise.all(this.promises); 37 | } 38 | 39 | /** 40 | * Handles the next task in the queue. 41 | */ 42 | private next(): void { 43 | if (this.queue.length > 0 && this.currentRunning < this.maxConcurrent) { 44 | const nextRun = this.queue.shift()!; 45 | nextRun(); 46 | } 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/libs/components/setting-panel.svelte: -------------------------------------------------------------------------------- 1 | 9 | 28 | 29 |
30 | 31 | {#each settingItems as item (item.key)} 32 | 33 | 46 | 47 | {/each} 48 |
49 | -------------------------------------------------------------------------------- /src/components/LoadingDialog.svelte: -------------------------------------------------------------------------------- 1 | 2 | 6 | 7 |
8 |
9 |
{message}
10 |
11 | 12 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "ESNext", 4 | "useDefineForClassFields": true, 5 | "module": "ESNext", 6 | "lib": [ 7 | "ES2020", 8 | "DOM", 9 | "DOM.Iterable" 10 | ], 11 | "skipLibCheck": true, 12 | /* Bundler mode */ 13 | "moduleResolution": "Node", 14 | // "allowImportingTsExtensions": true, 15 | "allowSyntheticDefaultImports": true, 16 | "resolveJsonModule": true, 17 | "isolatedModules": true, 18 | "noEmit": true, 19 | "jsx": "preserve", 20 | /* Linting */ 21 | "strict": false, 22 | "noUnusedLocals": true, 23 | "noUnusedParameters": true, 24 | "noFallthroughCasesInSwitch": true, 25 | /* Svelte */ 26 | /** 27 | * Typecheck JS in `.svelte` and `.js` files by default. 28 | * Disable checkJs if you'd like to use dynamic types in JS. 29 | * Note that setting allowJs false does not prevent the use 30 | * of JS in `.svelte` files. 31 | */ 32 | "allowJs": true, 33 | "checkJs": true, 34 | "types": [ 35 | "node", 36 | "vite/client", 37 | "svelte" 38 | ], 39 | // "baseUrl": "./src", 40 | "paths": { 41 | "@/*": ["./src/*"], 42 | "@/libs/*": ["./src/libs/*"], 43 | } 44 | }, 45 | "include": [ 46 | "tools/**/*.ts", 47 | "src/**/*.ts", 48 | "src/**/*.d.ts", 49 | "src/**/*.tsx", 50 | "src/**/*.vue", 51 | "src/**/*.svelte" ], 52 | "references": [ 53 | { 54 | "path": "./tsconfig.node.json" 55 | } 56 | ], 57 | "root": "." 58 | } -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Create Release on Tag Push 2 | 3 | on: 4 | push: 5 | tags: 6 | - "v*" 7 | 8 | jobs: 9 | build: 10 | runs-on: ubuntu-latest 11 | steps: 12 | # Checkout 13 | - name: Checkout 14 | uses: actions/checkout@v3 15 | 16 | # Install Node.js 17 | - name: Install Node.js 18 | uses: actions/setup-node@v3 19 | with: 20 | node-version: 18 21 | registry-url: "https://registry.npmjs.org" 22 | 23 | # Install pnpm 24 | - name: Install pnpm 25 | uses: pnpm/action-setup@v2 26 | id: pnpm-install 27 | with: 28 | version: 8 29 | run_install: false 30 | 31 | # Get pnpm store directory 32 | - name: Get pnpm store directory 33 | id: pnpm-cache 34 | shell: bash 35 | run: | 36 | echo "STORE_PATH=$(pnpm store path)" >> $GITHUB_OUTPUT 37 | 38 | # Setup pnpm cache 39 | - name: Setup pnpm cache 40 | uses: actions/cache@v3 41 | with: 42 | path: ${{ steps.pnpm-cache.outputs.STORE_PATH }} 43 | key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }} 44 | restore-keys: | 45 | ${{ runner.os }}-pnpm-store- 46 | 47 | # Install dependencies 48 | - name: Install dependencies 49 | run: pnpm install 50 | 51 | # Build for production, 这一步会生成一个 package.zip 52 | - name: Build for production 53 | run: pnpm build 54 | 55 | - name: Release 56 | uses: ncipollo/release-action@v1 57 | with: 58 | allowUpdates: true 59 | artifactErrorsFailBuild: true 60 | artifacts: "package.zip" 61 | token: ${{ secrets.GITHUB_TOKEN }} 62 | prerelease: false 63 | -------------------------------------------------------------------------------- /src/libs/components/Form/form-wrap.svelte: -------------------------------------------------------------------------------- 1 | 9 | 14 | 15 | {#if direction === "row"} 16 |
17 |
18 | {title} 19 |
{@html description}
20 |
21 |
22 | 23 |
24 |
25 |
26 | {:else} 27 |
28 |
29 | {title} 30 |
31 | {@html description} 32 |
33 |
34 | 35 | 36 |
37 | {/if} 38 | 39 | 54 | -------------------------------------------------------------------------------- /scripts/make_install.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2024-03-28 20:03:59 5 | * @FilePath : /scripts/make_install.js 6 | * @LastEditTime : 2024-09-06 18:08:19 7 | * @Description : 8 | */ 9 | // make_install.js 10 | import fs from 'fs'; 11 | import { log, error, getSiYuanDir, chooseTarget, copyDirectory, getThisPluginName } from './utils.js'; 12 | 13 | let targetDir = ''; 14 | 15 | /** 16 | * 1. Get the parent directory to install the plugin 17 | */ 18 | log('>>> Try to visit constant "targetDir" in make_install.js...'); 19 | if (targetDir === '') { 20 | log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....'); 21 | let res = await getSiYuanDir(); 22 | 23 | if (res === null || res === undefined || res.length === 0) { 24 | error('>>> Can not get SiYuan directory automatically'); 25 | process.exit(1); 26 | } else { 27 | targetDir = await chooseTarget(res); 28 | } 29 | log(`>>> Successfully got target directory: ${targetDir}`); 30 | } 31 | if (!fs.existsSync(targetDir)) { 32 | error(`Failed! Plugin directory not exists: "${targetDir}"`); 33 | error('Please set the plugin directory in scripts/make_install.js'); 34 | process.exit(1); 35 | } 36 | 37 | /** 38 | * 2. The dist directory, which contains the compiled plugin code 39 | */ 40 | const distDir = `${process.cwd()}/dist`; 41 | if (!fs.existsSync(distDir)) { 42 | fs.mkdirSync(distDir); 43 | } 44 | 45 | /** 46 | * 3. The target directory to install the plugin 47 | */ 48 | const name = getThisPluginName(); 49 | if (name === null) { 50 | process.exit(1); 51 | } 52 | const targetPath = `${targetDir}/${name}`; 53 | 54 | /** 55 | * 4. Copy the compiled plugin code to the target directory 56 | */ 57 | copyDirectory(distDir, targetPath); 58 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [中文](README_zh_CN.md) 2 | 3 | ## 🚀 Background 4 | 5 | When taking notes in SiYuan Note and needing to add styles, it can be quite troublesome to apply multiple overlapping styles to text simultaneously, such as background color + bold, let alone three or more styles (like font color + font size + bold) 😖💔 6 | 7 | Therefore, inspired by the format painter in Office, I developed this format painter plugin, hoping it can be your little helper in beautifying SiYuan notes, saving you time and quickly enhancing your notes! 💃🕺 8 | 9 | ## ✨ Feature Introduction 10 | 11 | > The minimum required version of Siyuan Notes for this plugin is v3.1.12. 12 | 13 | - **Enter format painter mode**: Select text and click the "Format Painter" button on the floating toolbar to copy the style (supports overlapping styles). Then, select other text to automatically and quickly apply the copied style. 14 | - Supported inline styles for copying: font size, background color, text color, bold, inline code, keyboard style, underline, strikethrough, superscript, subscript, highlight, etc. 15 | - Supports copying **no style** to clear the selected text style 16 | - **Exit format painter mode**: 17 | 1. Press the `Esc` key 18 | 2. When the format painter is activated, a button is added to the right of the dock's bottom bar. The button's icon gradually flashes, and clicking the button allows you to exit the format painter mode. 19 | 20 | 21 | ![](https://fastly.jsdelivr.net/gh/Achuan-2/PicBed/assets/思源笔记格式刷插件-2024-11-19.gif) 22 | 23 | 24 | ## ❤️ Powered by Love 25 | 26 | A poor graduate student in the process of studying. If you like my plugin, feel free to buy me a pack of spicy strips. This will motivate me to continue improving this plugin and developing new ones. 27 | 28 | ![](https://cdn.nlark.com/yuque/0/2024/jpeg/1408046/1714754573393-9c7f70b0-05ec-489e-b5a2-1a37fb681f6f.jpeg?x-oss-process=image%2Fformat%2Cwebp%2Fresize%2Cw_592%2Climit_0%2Finterlace%2C1) -------------------------------------------------------------------------------- /src/hello.svelte: -------------------------------------------------------------------------------- 1 | 9 | 45 | 46 |
47 |
appId:
48 |
49 |
${app?.appId}
50 |
51 |
52 |
API demo:
53 |
54 |
55 | System current time: {time} 56 |
57 |
58 |
59 |
Protyle demo: id = {blockID}
60 |
61 |
62 |
63 | 64 | -------------------------------------------------------------------------------- /scripts/make_dev_link.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2023-07-15 15:31:31 5 | * @FilePath : /scripts/make_dev_link.js 6 | * @LastEditTime : 2024-09-06 18:13:53 7 | * @Description : 8 | */ 9 | // make_dev_link.js 10 | import fs from 'fs'; 11 | import { log, error, getSiYuanDir, chooseTarget, getThisPluginName, makeSymbolicLink } from './utils.js'; 12 | 13 | let targetDir = ''; 14 | 15 | /** 16 | * 1. Get the parent directory to install the plugin 17 | */ 18 | log('>>> Try to visit constant "targetDir" in make_dev_link.js...'); 19 | if (targetDir === '') { 20 | log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....'); 21 | let res = await getSiYuanDir(); 22 | 23 | if (!res || res.length === 0) { 24 | log('>>> Can not get SiYuan directory automatically, try to visit environment variable "SIYUAN_PLUGIN_DIR"....'); 25 | let env = process.env?.SIYUAN_PLUGIN_DIR; 26 | if (env) { 27 | targetDir = env; 28 | log(`\tGot target directory from environment variable "SIYUAN_PLUGIN_DIR": ${targetDir}`); 29 | } else { 30 | error('\tCan not get SiYuan directory from environment variable "SIYUAN_PLUGIN_DIR", failed!'); 31 | process.exit(1); 32 | } 33 | } else { 34 | targetDir = await chooseTarget(res); 35 | } 36 | 37 | log(`>>> Successfully got target directory: ${targetDir}`); 38 | } 39 | if (!fs.existsSync(targetDir)) { 40 | error(`Failed! Plugin directory not exists: "${targetDir}"`); 41 | error('Please set the plugin directory in scripts/make_dev_link.js'); 42 | process.exit(1); 43 | } 44 | 45 | /** 46 | * 2. The dev directory, which contains the compiled plugin code 47 | */ 48 | const devDir = `${process.cwd()}/dev`; 49 | if (!fs.existsSync(devDir)) { 50 | fs.mkdirSync(devDir); 51 | } 52 | 53 | 54 | /** 55 | * 3. The target directory to make symbolic link to dev directory 56 | */ 57 | const name = getThisPluginName(); 58 | if (name === null) { 59 | process.exit(1); 60 | } 61 | const targetPath = `${targetDir}/${name}`; 62 | 63 | /** 64 | * 4. Make symbolic link 65 | */ 66 | makeSymbolicLink(devDir, targetPath); 67 | -------------------------------------------------------------------------------- /yaml-plugin.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2024-04-05 21:27:55 5 | * @FilePath : /yaml-plugin.js 6 | * @LastEditTime : 2024-04-05 22:53:34 7 | * @Description : 去妮玛的 json 格式,我就是要用 yaml 写 i18n 8 | */ 9 | // plugins/vite-plugin-parse-yaml.js 10 | import fs from 'fs'; 11 | import yaml from 'js-yaml'; 12 | import { resolve } from 'path'; 13 | 14 | export default function vitePluginYamlI18n(options = {}) { 15 | // Default options with a fallback 16 | const DefaultOptions = { 17 | inDir: 'src/i18n', 18 | outDir: 'dist/i18n', 19 | }; 20 | 21 | const finalOptions = { ...DefaultOptions, ...options }; 22 | 23 | return { 24 | name: 'vite-plugin-yaml-i18n', 25 | buildStart() { 26 | console.log('🌈 Parse I18n: YAML to JSON..'); 27 | const inDir = finalOptions.inDir; 28 | const outDir = finalOptions.outDir 29 | 30 | if (!fs.existsSync(outDir)) { 31 | fs.mkdirSync(outDir, { recursive: true }); 32 | } 33 | 34 | //Parse yaml file, output to json 35 | const files = fs.readdirSync(inDir); 36 | for (const file of files) { 37 | if (file.endsWith('.yaml') || file.endsWith('.yml')) { 38 | console.log(`-- Parsing ${file}`) 39 | //检查是否有同名的json文件 40 | const jsonFile = file.replace(/\.(yaml|yml)$/, '.json'); 41 | if (files.includes(jsonFile)) { 42 | console.log(`---- File ${jsonFile} already exists, skipping...`); 43 | continue; 44 | } 45 | try { 46 | const filePath = resolve(inDir, file); 47 | const fileContents = fs.readFileSync(filePath, 'utf8'); 48 | const parsed = yaml.load(fileContents); 49 | const jsonContent = JSON.stringify(parsed, null, 2); 50 | const outputFilePath = resolve(outDir, file.replace(/\.(yaml|yml)$/, '.json')); 51 | console.log(`---- Writing to ${outputFilePath}`); 52 | fs.writeFileSync(outputFilePath, jsonContent); 53 | } catch (error) { 54 | this.error(`---- Error parsing YAML file ${file}: ${error.message}`); 55 | } 56 | } 57 | } 58 | }, 59 | }; 60 | } 61 | -------------------------------------------------------------------------------- /src/libs/const.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2024-06-08 20:36:30 5 | * @FilePath : /src/libs/const.ts 6 | * @LastEditTime : 2024-06-08 20:48:06 7 | * @Description : 8 | */ 9 | 10 | 11 | export const BlockType2NodeType: {[key in BlockType]: string} = { 12 | d: 'NodeDocument', 13 | p: 'NodeParagraph', 14 | query_embed: 'NodeBlockQueryEmbed', 15 | l: 'NodeList', 16 | i: 'NodeListItem', 17 | h: 'NodeHeading', 18 | iframe: 'NodeIFrame', 19 | tb: 'NodeThematicBreak', 20 | b: 'NodeBlockquote', 21 | s: 'NodeSuperBlock', 22 | c: 'NodeCodeBlock', 23 | widget: 'NodeWidget', 24 | t: 'NodeTable', 25 | html: 'NodeHTMLBlock', 26 | m: 'NodeMathBlock', 27 | av: 'NodeAttributeView', 28 | audio: 'NodeAudio' 29 | } 30 | 31 | 32 | export const NodeIcons = { 33 | NodeAttributeView: { 34 | icon: "iconDatabase" 35 | }, 36 | NodeAudio: { 37 | icon: "iconRecord" 38 | }, 39 | NodeBlockQueryEmbed: { 40 | icon: "iconSQL" 41 | }, 42 | NodeBlockquote: { 43 | icon: "iconQuote" 44 | }, 45 | NodeCodeBlock: { 46 | icon: "iconCode" 47 | }, 48 | NodeDocument: { 49 | icon: "iconFile" 50 | }, 51 | NodeHTMLBlock: { 52 | icon: "iconHTML5" 53 | }, 54 | NodeHeading: { 55 | icon: "iconHeadings", 56 | subtypes: { 57 | h1: { icon: "iconH1" }, 58 | h2: { icon: "iconH2" }, 59 | h3: { icon: "iconH3" }, 60 | h4: { icon: "iconH4" }, 61 | h5: { icon: "iconH5" }, 62 | h6: { icon: "iconH6" } 63 | } 64 | }, 65 | NodeIFrame: { 66 | icon: "iconLanguage" 67 | }, 68 | NodeList: { 69 | subtypes: { 70 | o: { icon: "iconOrderedList" }, 71 | t: { icon: "iconCheck" }, 72 | u: { icon: "iconList" } 73 | } 74 | }, 75 | NodeListItem: { 76 | icon: "iconListItem" 77 | }, 78 | NodeMathBlock: { 79 | icon: "iconMath" 80 | }, 81 | NodeParagraph: { 82 | icon: "iconParagraph" 83 | }, 84 | NodeSuperBlock: { 85 | icon: "iconSuper" 86 | }, 87 | NodeTable: { 88 | icon: "iconTable" 89 | }, 90 | NodeThematicBreak: { 91 | icon: "iconLine" 92 | }, 93 | NodeVideo: { 94 | icon: "iconVideo" 95 | }, 96 | NodeWidget: { 97 | icon: "iconBoth" 98 | } 99 | }; 100 | -------------------------------------------------------------------------------- /src/types/index.d.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2023-08-15 10:28:10 5 | * @FilePath : /src/types/index.d.ts 6 | * @LastEditTime : 2024-06-08 20:50:53 7 | * @Description : Frequently used data structures in SiYuan 8 | */ 9 | 10 | 11 | type DocumentId = string; 12 | type BlockId = string; 13 | type NotebookId = string; 14 | type PreviousID = BlockId; 15 | type ParentID = BlockId | DocumentId; 16 | 17 | type Notebook = { 18 | id: NotebookId; 19 | name: string; 20 | icon: string; 21 | sort: number; 22 | closed: boolean; 23 | } 24 | 25 | type NotebookConf = { 26 | name: string; 27 | closed: boolean; 28 | refCreateSavePath: string; 29 | createDocNameTemplate: string; 30 | dailyNoteSavePath: string; 31 | dailyNoteTemplatePath: string; 32 | } 33 | 34 | type BlockType = 35 | | 'd' 36 | | 'p' 37 | | 'query_embed' 38 | | 'l' 39 | | 'i' 40 | | 'h' 41 | | 'iframe' 42 | | 'tb' 43 | | 'b' 44 | | 's' 45 | | 'c' 46 | | 'widget' 47 | | 't' 48 | | 'html' 49 | | 'm' 50 | | 'av' 51 | | 'audio'; 52 | 53 | 54 | type BlockSubType = "d1" | "d2" | "s1" | "s2" | "s3" | "t1" | "t2" | "h1" | "h2" | "h3" | "h4" | "h5" | "h6" | "table" | "task" | "toggle" | "latex" | "quote" | "html" | "code" | "footnote" | "cite" | "collection" | "bookmark" | "attachment" | "comment" | "mindmap" | "spreadsheet" | "calendar" | "image" | "audio" | "video" | "other"; 55 | 56 | type Block = { 57 | id: BlockId; 58 | parent_id?: BlockId; 59 | root_id: DocumentId; 60 | hash: string; 61 | box: string; 62 | path: string; 63 | hpath: string; 64 | name: string; 65 | alias: string; 66 | memo: string; 67 | tag: string; 68 | content: string; 69 | fcontent?: string; 70 | markdown: string; 71 | length: number; 72 | type: BlockType; 73 | subtype: BlockSubType; 74 | /** string of { [key: string]: string } 75 | * For instance: "{: custom-type=\"query-code\" id=\"20230613234017-zkw3pr0\" updated=\"20230613234509\"}" 76 | */ 77 | ial?: string; 78 | sort: number; 79 | created: string; 80 | updated: string; 81 | } 82 | 83 | type doOperation = { 84 | action: string; 85 | data: string; 86 | id: BlockId; 87 | parentID: BlockId | DocumentId; 88 | previousID: BlockId; 89 | retData: null; 90 | } 91 | 92 | interface Window { 93 | siyuan: { 94 | config: any; 95 | notebooks: any; 96 | menus: any; 97 | dialogs: any; 98 | blockPanels: any; 99 | storage: any; 100 | user: any; 101 | ws: any; 102 | languages: any; 103 | emojis: any; 104 | }; 105 | Lute: any; 106 | } 107 | -------------------------------------------------------------------------------- /src/libs/setting-item.svelte: -------------------------------------------------------------------------------- 1 | 28 | 29 | 93 | -------------------------------------------------------------------------------- /src/libs/setting-panel.svelte: -------------------------------------------------------------------------------- 1 | 12 | 13 | 17 | 18 |
19 |
20 |
21 |

This setting panel is provided by a svelte component

22 |
23 | 24 | See: 25 |
/lib/setting-pannel.svelte
26 |
27 |
28 |
29 |
30 | { 37 | showMessage( 38 | `Checkbox changed: ${event.detail.key} = ${event.detail.value}` 39 | ); 40 | }} 41 | /> 42 | { 50 | showMessage( 51 | `Input changed: ${event.detail.key} = ${event.detail.value}` 52 | ); 53 | }} 54 | /> 55 | { 62 | showMessage("Button clicked"); 63 | }} 64 | /> 65 | { 77 | showMessage( 78 | `Select changed: ${event.detail.key} = ${event.detail.value}` 79 | ); 80 | }} 81 | /> 82 | { 94 | showMessage( 95 | `Slide changed: ${event.detail.key} = ${event.detail.value}` 96 | ); 97 | }} 98 | /> 99 |
100 | -------------------------------------------------------------------------------- /scripts/make_dev_copy.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2025-07-13 5 | * @FilePath : /scripts/make_dev_copy.js 6 | * @LastEditTime : 2025-07-13 7 | * @Description : Copy plugin files to SiYuan plugins directory instead of creating symbolic links 8 | */ 9 | import fs from 'fs'; 10 | import path from 'path'; 11 | import { log, error, getSiYuanDir, chooseTarget, getThisPluginName, copyDirectory } from './utils.js'; 12 | 13 | let targetDir =`D:\\Notes\\Siyuan\\Achuan-2\\data\\plugins`; 14 | 15 | /** 16 | * 1. Get the parent directory to install the plugin 17 | */ 18 | log('>>> Try to visit constant "targetDir" in make_dev_copy.js...'); 19 | if (targetDir === '') { 20 | log('>>> Constant "targetDir" is empty, try to get SiYuan directory automatically....'); 21 | let res = await getSiYuanDir(); 22 | 23 | if (!res || res.length === 0) { 24 | log('>>> Can not get SiYuan directory automatically, try to visit environment variable "SIYUAN_PLUGIN_DIR"....'); 25 | let env = process.env?.SIYUAN_PLUGIN_DIR; 26 | if (env) { 27 | targetDir = env; 28 | log(`\tGot target directory from environment variable "SIYUAN_PLUGIN_DIR": ${targetDir}`); 29 | } else { 30 | error('\tCan not get SiYuan directory from environment variable "SIYUAN_PLUGIN_DIR", failed!'); 31 | process.exit(1); 32 | } 33 | } else { 34 | targetDir = await chooseTarget(res); 35 | } 36 | 37 | log(`>>> Successfully got target directory: ${targetDir}`); 38 | } 39 | if (!fs.existsSync(targetDir)) { 40 | error(`Failed! Plugin directory not exists: "${targetDir}"`); 41 | error('Please set the plugin directory in scripts/make_dev_copy.js'); 42 | process.exit(1); 43 | } 44 | 45 | /** 46 | * 2. The dev directory, which contains the compiled plugin code 47 | */ 48 | const devDir = `${process.cwd()}/dev`; 49 | if (!fs.existsSync(devDir)) { 50 | error(`Failed! Dev directory not exists: "${devDir}"`); 51 | error('Please run "pnpm run build" or "pnpm run dev" first to generate the dev directory'); 52 | process.exit(1); 53 | } 54 | 55 | /** 56 | * 3. The target directory to copy dev directory contents 57 | */ 58 | const name = getThisPluginName(); 59 | if (name === null) { 60 | process.exit(1); 61 | } 62 | const targetPath = `${targetDir}/${name}`; 63 | 64 | /** 65 | * 4. Create target directory and copy contents 66 | */ 67 | log(`>>> Creating target directory: ${targetPath}`); 68 | if (!fs.existsSync(targetPath)) { 69 | fs.mkdirSync(targetPath, { recursive: true }); 70 | log(`Created directory: ${targetPath}`); 71 | } else { 72 | // Clean existing directory contents 73 | log(`>>> Cleaning existing directory: ${targetPath}`); 74 | fs.rmSync(targetPath, { recursive: true, force: true }); 75 | fs.mkdirSync(targetPath, { recursive: true }); 76 | log(`Cleaned and recreated directory: ${targetPath}`); 77 | } 78 | 79 | /** 80 | * 5. Copy all contents from dev directory to target directory 81 | */ 82 | copyDirectory(devDir, targetPath); 83 | log(`>>> Successfully copied all files to SiYuan plugins directory!`); 84 | -------------------------------------------------------------------------------- /src/libs/components/Form/form-input.svelte: -------------------------------------------------------------------------------- 1 | 34 | 35 | {#if type === 'checkbox'} 36 | 37 | 45 | {:else if type === 'textinput'} 46 | 47 | 57 | {:else if type === 'textarea'} 58 |
21 |
22 |
23 |
24 | 25 |
`, 26 | width: args.width ?? "520px", 27 | height: args.height 28 | }); 29 | const target: HTMLTextAreaElement = dialog.element.querySelector(".b3-dialog__content>div.ft__breakword>textarea"); 30 | const btnsElement = dialog.element.querySelectorAll(".b3-button"); 31 | btnsElement[0].addEventListener("click", () => { 32 | if (args?.cancel) { 33 | args.cancel(); 34 | } 35 | dialog.destroy(); 36 | }); 37 | btnsElement[1].addEventListener("click", () => { 38 | if (args?.confirm) { 39 | args.confirm(target.value); 40 | } 41 | dialog.destroy(); 42 | }); 43 | }; 44 | 45 | export const inputDialogSync = async (args: { 46 | title: string, placeholder?: string, defaultText?: string, 47 | width?: string, height?: string 48 | }) => { 49 | return new Promise((resolve) => { 50 | let newargs = { 51 | ...args, confirm: (text) => { 52 | resolve(text); 53 | }, cancel: () => { 54 | resolve(null); 55 | } 56 | }; 57 | inputDialog(newargs); 58 | }); 59 | } 60 | 61 | 62 | interface IConfirmDialogArgs { 63 | title: string; 64 | content: string | HTMLElement; 65 | confirm?: (ele?: HTMLElement) => void; 66 | cancel?: (ele?: HTMLElement) => void; 67 | width?: string; 68 | height?: string; 69 | } 70 | 71 | export const confirmDialog = (args: IConfirmDialogArgs) => { 72 | const { title, content, confirm, cancel, width, height } = args; 73 | 74 | const dialog = new Dialog({ 75 | title, 76 | content: `
77 |
78 |
79 |
80 |
81 |
82 | 83 |
`, 84 | width: width, 85 | height: height 86 | }); 87 | 88 | const target: HTMLElement = dialog.element.querySelector(".b3-dialog__content>div.ft__breakword"); 89 | if (typeof content === "string") { 90 | target.innerHTML = content; 91 | } else { 92 | target.appendChild(content); 93 | } 94 | 95 | const btnsElement = dialog.element.querySelectorAll(".b3-button"); 96 | btnsElement[0].addEventListener("click", () => { 97 | if (cancel) { 98 | cancel(target); 99 | } 100 | dialog.destroy(); 101 | }); 102 | btnsElement[1].addEventListener("click", () => { 103 | if (confirm) { 104 | confirm(target); 105 | } 106 | dialog.destroy(); 107 | }); 108 | }; 109 | 110 | 111 | export const confirmDialogSync = async (args: IConfirmDialogArgs) => { 112 | return new Promise((resolve) => { 113 | let newargs = { 114 | ...args, confirm: (ele: HTMLElement) => { 115 | resolve(ele); 116 | }, cancel: (ele: HTMLElement) => { 117 | resolve(ele); 118 | } 119 | }; 120 | confirmDialog(newargs); 121 | }); 122 | }; 123 | 124 | 125 | export const simpleDialog = (args: { 126 | title: string, ele: HTMLElement | DocumentFragment, 127 | width?: string, height?: string, 128 | callback?: () => void; 129 | }) => { 130 | const dialog = new Dialog({ 131 | title: args.title, 132 | content: `
`, 133 | width: args.width, 134 | height: args.height, 135 | destroyCallback: args.callback 136 | }); 137 | dialog.element.querySelector(".dialog-content").appendChild(args.ele); 138 | return { 139 | dialog, 140 | close: dialog.destroy.bind(dialog) 141 | }; 142 | } 143 | 144 | 145 | export const svelteDialog = (args: { 146 | title: string, constructor: (container: HTMLElement) => SvelteComponent, 147 | width?: string, height?: string, 148 | callback?: () => void; 149 | }) => { 150 | let container = document.createElement('div') 151 | container.style.display = 'contents'; 152 | let component = args.constructor(container); 153 | const { dialog, close } = simpleDialog({ 154 | ...args, ele: container, callback: () => { 155 | component.$destroy(); 156 | if (args.callback) args.callback(); 157 | } 158 | }); 159 | return { 160 | component, 161 | dialog, 162 | close 163 | } 164 | } 165 | -------------------------------------------------------------------------------- /scripts/utils.js: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2024 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2024-09-06 17:42:57 5 | * @FilePath : /scripts/utils.js 6 | * @LastEditTime : 2024-09-06 19:23:12 7 | * @Description : 8 | */ 9 | // common.js 10 | import fs from 'fs'; 11 | import path from 'node:path'; 12 | import http from 'node:http'; 13 | import readline from 'node:readline'; 14 | 15 | // Logging functions 16 | export const log = (info) => console.log(`\x1B[36m%s\x1B[0m`, info); 17 | export const error = (info) => console.log(`\x1B[31m%s\x1B[0m`, info); 18 | 19 | // HTTP POST headers 20 | export const POST_HEADER = { 21 | "Content-Type": "application/json", 22 | }; 23 | 24 | // Fetch function compatible with older Node.js versions 25 | export async function myfetch(url, options) { 26 | return new Promise((resolve, reject) => { 27 | let req = http.request(url, options, (res) => { 28 | let data = ''; 29 | res.on('data', (chunk) => { 30 | data += chunk; 31 | }); 32 | res.on('end', () => { 33 | resolve({ 34 | ok: true, 35 | status: res.statusCode, 36 | json: () => JSON.parse(data) 37 | }); 38 | }); 39 | }); 40 | req.on('error', (e) => { 41 | reject(e); 42 | }); 43 | req.end(); 44 | }); 45 | } 46 | 47 | /** 48 | * Fetch SiYuan workspaces from port 6806 49 | * @returns {Promise} 50 | */ 51 | export async function getSiYuanDir() { 52 | let url = 'http://127.0.0.1:6806/api/system/getWorkspaces'; 53 | let conf = {}; 54 | try { 55 | let response = await myfetch(url, { 56 | method: 'POST', 57 | headers: POST_HEADER 58 | }); 59 | if (response.ok) { 60 | conf = await response.json(); 61 | } else { 62 | error(`\tHTTP-Error: ${response.status}`); 63 | return null; 64 | } 65 | } catch (e) { 66 | error(`\tError: ${e}`); 67 | error("\tPlease make sure SiYuan is running!!!"); 68 | return null; 69 | } 70 | return conf?.data; // 保持原始返回值 71 | } 72 | 73 | /** 74 | * Choose target workspace 75 | * @param {{path: string}[]} workspaces 76 | * @returns {string} The path of the selected workspace 77 | */ 78 | export async function chooseTarget(workspaces) { 79 | let count = workspaces.length; 80 | log(`>>> Got ${count} SiYuan ${count > 1 ? 'workspaces' : 'workspace'}`); 81 | workspaces.forEach((workspace, i) => { 82 | log(`\t[${i}] ${workspace.path}`); 83 | }); 84 | 85 | if (count === 1) { 86 | return `${workspaces[0].path}/data/plugins`; 87 | } else { 88 | const rl = readline.createInterface({ 89 | input: process.stdin, 90 | output: process.stdout 91 | }); 92 | let index = await new Promise((resolve) => { 93 | rl.question(`\tPlease select a workspace[0-${count - 1}]: `, (answer) => { 94 | resolve(answer); 95 | }); 96 | }); 97 | rl.close(); 98 | return `${workspaces[index].path}/data/plugins`; 99 | } 100 | } 101 | 102 | /** 103 | * Check if two paths are the same 104 | * @param {string} path1 105 | * @param {string} path2 106 | * @returns {boolean} 107 | */ 108 | export function cmpPath(path1, path2) { 109 | path1 = path1.replace(/\\/g, '/'); 110 | path2 = path2.replace(/\\/g, '/'); 111 | if (path1[path1.length - 1] !== '/') { 112 | path1 += '/'; 113 | } 114 | if (path2[path2.length - 1] !== '/') { 115 | path2 += '/'; 116 | } 117 | return path1 === path2; 118 | } 119 | 120 | export function getThisPluginName() { 121 | if (!fs.existsSync('./plugin.json')) { 122 | process.chdir('../'); 123 | if (!fs.existsSync('./plugin.json')) { 124 | error('Failed! plugin.json not found'); 125 | return null; 126 | } 127 | } 128 | 129 | const plugin = JSON.parse(fs.readFileSync('./plugin.json', 'utf8')); 130 | const name = plugin?.name; 131 | if (!name) { 132 | error('Failed! Please set plugin name in plugin.json'); 133 | return null; 134 | } 135 | 136 | return name; 137 | } 138 | 139 | export function copyDirectory(srcDir, dstDir) { 140 | if (!fs.existsSync(dstDir)) { 141 | fs.mkdirSync(dstDir); 142 | log(`Created directory ${dstDir}`); 143 | } 144 | 145 | fs.readdirSync(srcDir, { withFileTypes: true }).forEach((file) => { 146 | const src = path.join(srcDir, file.name); 147 | const dst = path.join(dstDir, file.name); 148 | 149 | if (file.isDirectory()) { 150 | copyDirectory(src, dst); 151 | } else { 152 | fs.copyFileSync(src, dst); 153 | } 154 | }); 155 | log(`All files copied!`); 156 | } 157 | 158 | 159 | export function makeSymbolicLink(srcPath, targetPath) { 160 | if (!fs.existsSync(targetPath)) { 161 | // fs.symlinkSync(srcPath, targetPath, 'junction'); 162 | //Go 1.23 no longer supports junctions as symlinks 163 | //Please refer to https://github.com/siyuan-note/siyuan/issues/12399 164 | fs.symlinkSync(srcPath, targetPath, 'dir'); 165 | log(`Done! Created symlink ${targetPath}`); 166 | return; 167 | } 168 | 169 | //Check the existed target path 170 | let isSymbol = fs.lstatSync(targetPath).isSymbolicLink(); 171 | if (!isSymbol) { 172 | error(`Failed! ${targetPath} already exists and is not a symbolic link`); 173 | return; 174 | } 175 | let existedPath = fs.readlinkSync(targetPath); 176 | if (cmpPath(existedPath, srcPath)) { 177 | log(`Good! ${targetPath} is already linked to ${srcPath}`); 178 | } else { 179 | error(`Error! Already exists symbolic link ${targetPath}\nBut it links to ${existedPath}`); 180 | } 181 | } 182 | -------------------------------------------------------------------------------- /vite.config.ts: -------------------------------------------------------------------------------- 1 | import { resolve } from "path" 2 | import { defineConfig, loadEnv } from "vite" 3 | import { viteStaticCopy } from "vite-plugin-static-copy" 4 | import livereload from "rollup-plugin-livereload" 5 | import { svelte } from "@sveltejs/vite-plugin-svelte" 6 | import zipPack from "vite-plugin-zip-pack"; 7 | import fg from 'fast-glob'; 8 | import fs from 'fs'; 9 | import { execSync } from 'child_process'; 10 | 11 | import vitePluginYamlI18n from './yaml-plugin'; 12 | 13 | const env = process.env; 14 | const isSrcmap = env.VITE_SOURCEMAP === 'inline'; 15 | const isDev = env.NODE_ENV === 'development'; 16 | 17 | const outputDir = isDev ? "dev" : "dist"; 18 | 19 | console.log("isDev=>", isDev); 20 | console.log("isSrcmap=>", isSrcmap); 21 | console.log("outputDir=>", outputDir); 22 | 23 | export default defineConfig({ 24 | resolve: { 25 | alias: { 26 | "@": resolve(__dirname, "src"), 27 | } 28 | }, 29 | 30 | plugins: [ 31 | svelte(), 32 | 33 | vitePluginYamlI18n({ 34 | inDir: 'public/i18n', 35 | outDir: `${outputDir}/i18n` 36 | }), 37 | 38 | viteStaticCopy({ 39 | targets: [ 40 | { src: "./README*.md", dest: "./" }, 41 | { src: "./plugin.json", dest: "./" }, 42 | { src: "./preview.png", dest: "./" }, 43 | { src: "./icon.png", dest: "./" }, 44 | { src: "./src/assets/", dest: "./" } 45 | ], 46 | }), 47 | 48 | // Auto copy to SiYuan plugins directory in dev mode 49 | ...(isDev ? [ 50 | { 51 | name: 'auto-copy-to-siyuan', 52 | writeBundle() { 53 | try { 54 | // Run the copy script after build 55 | execSync('node --no-warnings ./scripts/make_dev_copy.js', { 56 | stdio: 'inherit', 57 | cwd: process.cwd() 58 | }); 59 | } catch (error) { 60 | console.warn('Auto copy to SiYuan failed:', error.message); 61 | console.warn('You can manually run: pnpm run make-link-win'); 62 | } 63 | } 64 | } 65 | ] : []), 66 | 67 | ], 68 | 69 | define: { 70 | "process.env.DEV_MODE": JSON.stringify(isDev), 71 | "process.env.NODE_ENV": JSON.stringify(env.NODE_ENV) 72 | }, 73 | 74 | build: { 75 | outDir: outputDir, 76 | emptyOutDir: false, 77 | minify: true, 78 | sourcemap: isSrcmap ? 'inline' : false, 79 | 80 | lib: { 81 | entry: resolve(__dirname, "src/index.ts"), 82 | fileName: "index", 83 | formats: ["cjs"], 84 | }, 85 | rollupOptions: { 86 | plugins: [ 87 | ...(isDev ? [ 88 | { 89 | name: 'watch-external', 90 | async buildStart() { 91 | const files = await fg([ 92 | 'public/i18n/**', 93 | './README*.md', 94 | './plugin.json' 95 | ]); 96 | for (let file of files) { 97 | this.addWatchFile(file); 98 | } 99 | } 100 | } 101 | ] : [ 102 | // Clean up unnecessary files under dist dir 103 | cleanupDistFiles({ 104 | patterns: ['i18n/*.yaml', 'i18n/*.md'], 105 | distDir: outputDir 106 | }), 107 | zipPack({ 108 | inDir: './dist', 109 | outDir: './', 110 | outFileName: 'package.zip' 111 | }) 112 | ]) 113 | ], 114 | 115 | external: ["siyuan", "process"], 116 | 117 | output: { 118 | entryFileNames: "[name].js", 119 | assetFileNames: (assetInfo) => { 120 | if (assetInfo.name === "style.css") { 121 | return "index.css" 122 | } 123 | return assetInfo.name 124 | }, 125 | }, 126 | }, 127 | } 128 | }); 129 | 130 | 131 | /** 132 | * Clean up some dist files after compiled 133 | * @author frostime 134 | * @param options: 135 | * @returns 136 | */ 137 | function cleanupDistFiles(options: { patterns: string[], distDir: string }) { 138 | const { 139 | patterns, 140 | distDir 141 | } = options; 142 | 143 | return { 144 | name: 'rollup-plugin-cleanup', 145 | enforce: 'post', 146 | writeBundle: { 147 | sequential: true, 148 | order: 'post' as 'post', 149 | async handler() { 150 | const fg = await import('fast-glob'); 151 | const fs = await import('fs'); 152 | // const path = await import('path'); 153 | 154 | // 使用 glob 语法,确保能匹配到文件 155 | const distPatterns = patterns.map(pat => `${distDir}/${pat}`); 156 | console.debug('Cleanup searching patterns:', distPatterns); 157 | 158 | const files = await fg.default(distPatterns, { 159 | dot: true, 160 | absolute: true, 161 | onlyFiles: false 162 | }); 163 | 164 | // console.info('Files to be cleaned up:', files); 165 | 166 | for (const file of files) { 167 | try { 168 | if (fs.default.existsSync(file)) { 169 | const stat = fs.default.statSync(file); 170 | if (stat.isDirectory()) { 171 | fs.default.rmSync(file, { recursive: true }); 172 | } else { 173 | fs.default.unlinkSync(file); 174 | } 175 | console.log(`Cleaned up: ${file}`); 176 | } 177 | } catch (error) { 178 | console.error(`Failed to clean up ${file}:`, error); 179 | } 180 | } 181 | } 182 | } 183 | }; 184 | } 185 | -------------------------------------------------------------------------------- /src/setting-example.svelte: -------------------------------------------------------------------------------- 1 | 168 | 169 |
170 |
    171 | {#each groups as group} 172 |
  • { 177 | focusGroup = group.name; 178 | }} 179 | on:keydown={() => {}} 180 | > 181 | {group.name} 182 |
  • 183 | {/each} 184 |
185 |
186 | 192 |
193 |
194 | 195 | 213 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | (()=>{"use strict";var __webpack_modules__={"./src/index.ts":(__unused_webpack_module,__webpack_exports__,__webpack_require__)=>{eval(`{__webpack_require__.r(__webpack_exports__); 2 | /* harmony export */ __webpack_require__.d(__webpack_exports__, { 3 | /* harmony export */ "default": () => (/* binding */ PluginSample) 4 | /* harmony export */ }); 5 | /* harmony import */ var siyuan__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! siyuan */ "siyuan"); 6 | /* harmony import */ var siyuan__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(siyuan__WEBPACK_IMPORTED_MODULE_0__); 7 | 8 | class PluginSample extends siyuan__WEBPACK_IMPORTED_MODULE_0__.Plugin { 9 | constructor() { 10 | super(...arguments); 11 | this.formatPainterEnable = false; 12 | this.formatData = null; 13 | } 14 | // \u6DFB\u52A0\u5DE5\u5177\u680F\u6309\u94AE 15 | updateProtyleToolbar(toolbar) { 16 | toolbar.push( 17 | { 18 | name: "format-painter", 19 | icon: "iconFormat", 20 | tipPosition: "n", 21 | tip: this.i18n.tips, 22 | click: (protyle) => { 23 | this.protyle = protyle.protyle; 24 | if (!this.formatPainterEnable) { 25 | const selectedInfo = this.getSelectedParentHtml(); 26 | if (selectedInfo) { 27 | this.formatData = { 28 | datatype: selectedInfo.datatype, 29 | style: selectedInfo.style 30 | }; 31 | } else { 32 | this.formatData = null; 33 | } 34 | this.formatPainterEnable = true; 35 | document.body.dataset.formatPainterEnable = "true"; 36 | (0,siyuan__WEBPACK_IMPORTED_MODULE_0__.fetchPost)("/api/notification/pushMsg", { "msg": this.i18n.enable, "timeout": 7e3 }); 37 | const indicator = document.querySelector(".siyuan-plugin-formatPainter_brush_indicator"); 38 | if (indicator) { 39 | indicator.style.display = "flex"; 40 | } 41 | this.protyle.toolbar.range.collapse(true); 42 | const toolbarElements = document.querySelectorAll(".protyle-toolbar"); 43 | toolbarElements.forEach((element) => { 44 | if (!element.classList.contains("fn__none")) { 45 | element.classList.add("fn__none"); 46 | } 47 | }); 48 | } 49 | } 50 | } 51 | ); 52 | return toolbar; 53 | } 54 | onload() { 55 | document.addEventListener("mouseup", (event) => { 56 | if (this.formatPainterEnable) { 57 | const selection = window.getSelection(); 58 | let hasmath = false; 59 | if (selection && selection.rangeCount > 0) { 60 | const range = selection.getRangeAt(0); 61 | const selectedText = range.toString(); 62 | if (selectedText) { 63 | const startBlockElement = hasClosestBlock(range.startContainer); 64 | if (range.endContainer.nodeType !== 3 && range.endContainer.tagName === "DIV" && range.endOffset === 0) { 65 | if (range.endContainer.classList.contains("protyle-attr") && startBlockElement) { 66 | setLastNodeRange(getContenteditableElement(startBlockElement), range, false); 67 | } 68 | } 69 | this.protyle.toolbar.range = range; 70 | this.protyle.toolbar.setInlineMark(this.protyle, "clear", "range"); 71 | if (!this.formatData) { 72 | this.protyle.toolbar.range.collapse(false); 73 | this.protyle.toolbar.element.classList.add("fn__none"); 74 | return; 75 | } 76 | if (this.formatData.datatype) { 77 | if (this.formatData.datatype.includes("inline-math")) { 78 | this.protyle.toolbar.setInlineMark(this.protyle, "inline-math", "range", { 79 | type: "inline-math" 80 | }); 81 | hasmath = true; 82 | } 83 | const otherTypes = this.formatData.datatype.replace(/\\b(inline-math|block-ref|a|text)\\b/g, "").trim(); 84 | if (otherTypes) { 85 | this.protyle.toolbar.setInlineMark(this.protyle, otherTypes, "range"); 86 | } 87 | } 88 | if (this.formatData.style) { 89 | let type = "text"; 90 | if (hasmath) { 91 | type = "inline-math"; 92 | return; 93 | } 94 | const { backgroundColor, color, fontSize, textShadow, webkitTextStroke, webkitTextFillColor } = parseStyle(this.formatData.style); 95 | if (backgroundColor) { 96 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 97 | "type": "backgroundColor", 98 | "color": backgroundColor 99 | }); 100 | } 101 | if (color) { 102 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 103 | "type": "color", 104 | "color": color 105 | }); 106 | } 107 | if (fontSize) { 108 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 109 | "type": "fontSize", 110 | "color": fontSize 111 | }); 112 | } 113 | if (textShadow) { 114 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 115 | "type": "style4", 116 | //\u6295\u5F71\u6548\u679C 117 | "color": textShadow 118 | }); 119 | } 120 | if (webkitTextStroke) { 121 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 122 | "type": "style2", 123 | //\u9542\u7A7A\u6548\u679C 124 | "color": webkitTextStroke 125 | }); 126 | } 127 | } 128 | this.protyle.toolbar.range.collapse(false); 129 | this.protyle.toolbar.element.classList.add("fn__none"); 130 | } 131 | } 132 | } 133 | }); 134 | document.addEventListener("keydown", (event) => { 135 | var _a; 136 | if (event.key === "Escape") { 137 | if (this.formatPainterEnable) { 138 | event.stopPropagation(); 139 | event.preventDefault(); 140 | this.formatPainterEnable = false; 141 | document.body.dataset.formatPainterEnable = "false"; 142 | this.formatData = null; 143 | (0,siyuan__WEBPACK_IMPORTED_MODULE_0__.fetchPost)("/api/notification/pushMsg", { "msg": this.i18n.disable, "timeout": 7e3 }); 144 | const indicator = document.querySelector(".siyuan-plugin-formatPainter_brush_indicator"); 145 | if (indicator) { 146 | indicator.style.display = "none"; 147 | } 148 | (_a = window.getSelection()) == null ? void 0 : _a.removeAllRanges(); 149 | } 150 | } 151 | }, true); 152 | const hasClosestByAttribute = (element, attr, value, top = false) => { 153 | var _a; 154 | if (!element) { 155 | return false; 156 | } 157 | if (element.nodeType === 3) { 158 | element = element.parentElement; 159 | } 160 | let e = element; 161 | let isClosest = false; 162 | while (e && !isClosest && (top ? e.tagName !== "BODY" : !e.classList.contains("protyle-wysiwyg"))) { 163 | if (typeof value === "string" && ((_a = e.getAttribute(attr)) == null ? void 0 : _a.split(" ").includes(value))) { 164 | isClosest = true; 165 | } else if (typeof value !== "string" && e.hasAttribute(attr)) { 166 | isClosest = true; 167 | } else { 168 | e = e.parentElement; 169 | } 170 | } 171 | return isClosest && e; 172 | }; 173 | const hasClosestBlock = (element) => { 174 | var _a; 175 | const nodeElement = hasClosestByAttribute(element, "data-node-id", null); 176 | if (nodeElement && nodeElement.tagName !== "BUTTON" && ((_a = nodeElement.getAttribute("data-type")) == null ? void 0 : _a.startsWith("Node"))) { 177 | return nodeElement; 178 | } 179 | return false; 180 | }; 181 | const getContenteditableElement = (element) => { 182 | if (!element || element.getAttribute("contenteditable") === "true" && !element.classList.contains("protyle-wysiwyg")) { 183 | return element; 184 | } 185 | return element.querySelector('[contenteditable="true"]'); 186 | }; 187 | const setLastNodeRange = (editElement, range, setStart = true) => { 188 | if (!editElement) { 189 | return range; 190 | } 191 | let lastNode = editElement.lastChild; 192 | while (lastNode && lastNode.nodeType !== 3) { 193 | if (lastNode.nodeType !== 3 && lastNode.tagName === "BR") { 194 | return range; 195 | } 196 | lastNode = lastNode.lastChild; 197 | } 198 | if (!lastNode) { 199 | range.selectNodeContents(editElement); 200 | return range; 201 | } 202 | if (setStart) { 203 | range.setStart(lastNode, lastNode.textContent.length); 204 | } else { 205 | range.setEnd(lastNode, lastNode.textContent.length); 206 | } 207 | return range; 208 | }; 209 | function parseStyle(styleString) { 210 | const styles = styleString.split(";").filter((s) => s.trim() !== ""); 211 | const styleObject = {}; 212 | styles.forEach((style) => { 213 | const [property, value] = style.split(":").map((s) => s.trim()); 214 | styleObject[property] = value; 215 | }); 216 | return { 217 | backgroundColor: styleObject["background-color"], 218 | color: styleObject["color"], 219 | fontSize: styleObject["font-size"], 220 | textShadow: styleObject["text-shadow"], 221 | webkitTextStroke: styleObject["-webkit-text-stroke"], 222 | webkitTextFillColor: styleObject["-webkit-text-fill-color"] 223 | }; 224 | } 225 | console.log(this.i18n.helloPlugin); 226 | } 227 | getSelectedParentHtml() { 228 | const selection = window.getSelection(); 229 | if (selection.rangeCount > 0) { 230 | const range = selection.getRangeAt(0); 231 | let selectedNode = range.startContainer; 232 | const endNode = range.endContainer; 233 | if (endNode.previousSibling && endNode.previousSibling.nodeType === Node.ELEMENT_NODE) { 234 | const previousSibling = endNode.previousSibling; 235 | if (previousSibling.tagName.toLowerCase() === "span" && previousSibling.classList.contains("render-node")) { 236 | selectedNode = previousSibling; 237 | } 238 | } 239 | let parentElement = selectedNode.nodeType === Node.TEXT_NODE ? selectedNode.parentNode : selectedNode; 240 | while (parentElement && !parentElement.hasAttribute("data-type")) { 241 | parentElement = parentElement.parentElement; 242 | } 243 | if (parentElement && parentElement.tagName.toLowerCase() === "span") { 244 | const result = { 245 | html: parentElement.outerHTML, 246 | datatype: parentElement.getAttribute("data-type"), 247 | style: parentElement.getAttribute("style") 248 | }; 249 | selection.removeAllRanges(); 250 | return result; 251 | } 252 | } 253 | selection.removeAllRanges(); 254 | return null; 255 | } 256 | addDockBrushModeIndicator() { 257 | const indicator = document.createElement("div"); 258 | indicator.classList.add("siyuan-plugin-formatPainter_brush_indicator", "status__counter", "toolbar__item", "ariaLabel", "blink-animation"); 259 | indicator.innerHTML = \`\`; 260 | this.addStatusBar({ 261 | element: indicator 262 | }); 263 | indicator.setAttribute("aria-label", this.i18n.closeTips); 264 | indicator.style.display = "none"; 265 | const style = document.createElement("style"); 266 | style.textContent = \` 267 | @keyframes blink { 268 | 0% { opacity: 1; } 269 | 50% { opacity: 0.2; } 270 | 100% { opacity: 1; } 271 | } 272 | .blink-animation { 273 | animation: blink 1s infinite; 274 | } 275 | \`; 276 | document.head.appendChild(style); 277 | indicator.addEventListener("click", () => { 278 | this.toggleFormatPainter(); 279 | }); 280 | } 281 | toggleFormatPainter() { 282 | if (this.formatPainterEnable) { 283 | (0,siyuan__WEBPACK_IMPORTED_MODULE_0__.fetchPost)("/api/notification/pushMsg", { "msg": this.i18n.disable, "timeout": 7e3 }); 284 | document.body.dataset.formatPainterEnable = "false"; 285 | } else { 286 | (0,siyuan__WEBPACK_IMPORTED_MODULE_0__.fetchPost)("/api/notification/pushMsg", { "msg": this.i18n.enable, "timeout": 7e3 }); 287 | document.body.dataset.formatPainterEnable = "true"; 288 | } 289 | this.formatPainterEnable = !this.formatPainterEnable; 290 | const indicator = document.querySelector(".siyuan-plugin-formatPainter_brush_indicator"); 291 | if (indicator) { 292 | indicator.style.display = this.formatPainterEnable ? "flex" : "none"; 293 | } 294 | } 295 | onLayoutReady() { 296 | this.addDockBrushModeIndicator(); 297 | } 298 | onunload() { 299 | console.log(this.i18n.byePlugin); 300 | } 301 | uninstall() { 302 | console.log("uninstall"); 303 | } 304 | } 305 | 306 | 307 | //# sourceURL=webpack://test_quote/./src/index.ts? 308 | }`)},siyuan:e=>{e.exports=require("siyuan")}},__webpack_module_cache__={};function __webpack_require__(e){var t=__webpack_module_cache__[e];if(t!==void 0)return t.exports;var n=__webpack_module_cache__[e]={exports:{}};return __webpack_modules__[e](n,n.exports,__webpack_require__),n.exports}__webpack_require__.n=e=>{var t=e&&e.__esModule?()=>e.default:()=>e;return __webpack_require__.d(t,{a:t}),t},__webpack_require__.d=(e,t)=>{for(var n in t)__webpack_require__.o(t,n)&&!__webpack_require__.o(e,n)&&Object.defineProperty(e,n,{enumerable:!0,get:t[n]})},__webpack_require__.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),__webpack_require__.r=e=>{typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var __webpack_exports__=__webpack_require__("./src/index.ts");module.exports=__webpack_exports__})(); 309 | -------------------------------------------------------------------------------- /src/libs/setting-utils.ts: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2023 by frostime. All Rights Reserved. 3 | * @Author : frostime 4 | * @Date : 2023-12-17 18:28:19 5 | * @FilePath : /src/libs/setting-utils.ts 6 | * @LastEditTime : 2024-05-01 17:44:16 7 | * @Description : 8 | */ 9 | 10 | import { Plugin, Setting } from 'siyuan'; 11 | 12 | 13 | /** 14 | * The default function to get the value of the element 15 | * @param type 16 | * @returns 17 | */ 18 | const createDefaultGetter = (type: TSettingItemType) => { 19 | let getter: (ele: HTMLElement) => any; 20 | switch (type) { 21 | case 'checkbox': 22 | getter = (ele: HTMLInputElement) => { 23 | return ele.checked; 24 | }; 25 | break; 26 | case 'select': 27 | case 'slider': 28 | case 'textinput': 29 | case 'textarea': 30 | getter = (ele: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement) => { 31 | return ele.value; 32 | }; 33 | break; 34 | case 'number': 35 | getter = (ele: HTMLInputElement) => { 36 | return parseInt(ele.value); 37 | } 38 | break; 39 | default: 40 | getter = () => null; 41 | break; 42 | } 43 | return getter; 44 | } 45 | 46 | 47 | /** 48 | * The default function to set the value of the element 49 | * @param type 50 | * @returns 51 | */ 52 | const createDefaultSetter = (type: TSettingItemType) => { 53 | let setter: (ele: HTMLElement, value: any) => void; 54 | switch (type) { 55 | case 'checkbox': 56 | setter = (ele: HTMLInputElement, value: any) => { 57 | ele.checked = value; 58 | }; 59 | break; 60 | case 'select': 61 | case 'slider': 62 | case 'textinput': 63 | case 'textarea': 64 | case 'number': 65 | setter = (ele: HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement, value: any) => { 66 | ele.value = value; 67 | }; 68 | break; 69 | default: 70 | setter = () => {}; 71 | break; 72 | } 73 | return setter; 74 | 75 | } 76 | 77 | 78 | export class SettingUtils { 79 | plugin: Plugin; 80 | name: string; 81 | file: string; 82 | 83 | settings: Map = new Map(); 84 | elements: Map = new Map(); 85 | 86 | constructor(args: { 87 | plugin: Plugin, 88 | name?: string, 89 | callback?: (data: any) => void, 90 | width?: string, 91 | height?: string 92 | }) { 93 | this.name = args.name ?? 'settings'; 94 | this.plugin = args.plugin; 95 | this.file = this.name.endsWith('.json') ? this.name : `${this.name}.json`; 96 | this.plugin.setting = new Setting({ 97 | width: args.width, 98 | height: args.height, 99 | confirmCallback: () => { 100 | for (let key of this.settings.keys()) { 101 | this.updateValueFromElement(key); 102 | } 103 | let data = this.dump(); 104 | if (args.callback !== undefined) { 105 | args.callback(data); 106 | } 107 | this.plugin.data[this.name] = data; 108 | this.save(data); 109 | }, 110 | destroyCallback: () => { 111 | //Restore the original value 112 | for (let key of this.settings.keys()) { 113 | this.updateElementFromValue(key); 114 | } 115 | } 116 | }); 117 | } 118 | 119 | async load() { 120 | let data = await this.plugin.loadData(this.file); 121 | // console.debug('Load config:', data); 122 | if (data) { 123 | for (let [key, item] of this.settings) { 124 | item.value = data?.[key] ?? item.value; 125 | } 126 | } 127 | this.plugin.data[this.name] = this.dump(); 128 | return data; 129 | } 130 | 131 | async save(data?: any) { 132 | data = data ?? this.dump(); 133 | await this.plugin.saveData(this.file, this.dump()); 134 | // console.debug('Save config:', data); 135 | return data; 136 | } 137 | 138 | /** 139 | * read the data after saving 140 | * @param key key name 141 | * @returns setting item value 142 | */ 143 | get(key: string) { 144 | return this.settings.get(key)?.value; 145 | } 146 | 147 | /** 148 | * Set data to this.settings, 149 | * but do not save it to the configuration file 150 | * @param key key name 151 | * @param value value 152 | */ 153 | set(key: string, value: any) { 154 | let item = this.settings.get(key); 155 | if (item) { 156 | item.value = value; 157 | this.updateElementFromValue(key); 158 | } 159 | } 160 | 161 | /** 162 | * Set and save setting item value 163 | * If you want to set and save immediately you can use this method 164 | * @param key key name 165 | * @param value value 166 | */ 167 | async setAndSave(key: string, value: any) { 168 | let item = this.settings.get(key); 169 | if (item) { 170 | item.value = value; 171 | this.updateElementFromValue(key); 172 | await this.save(); 173 | } 174 | } 175 | 176 | /** 177 | * Read in the value of element instead of setting obj in real time 178 | * @param key key name 179 | * @param apply whether to apply the value to the setting object 180 | * if true, the value will be applied to the setting object 181 | * @returns value in html 182 | */ 183 | take(key: string, apply: boolean = false) { 184 | let item = this.settings.get(key); 185 | let element = this.elements.get(key) as any; 186 | if (!element) { 187 | return 188 | } 189 | if (apply) { 190 | this.updateValueFromElement(key); 191 | } 192 | return item.getEleVal(element); 193 | } 194 | 195 | /** 196 | * Read data from html and save it 197 | * @param key key name 198 | * @param value value 199 | * @return value in html 200 | */ 201 | async takeAndSave(key: string) { 202 | let value = this.take(key, true); 203 | await this.save(); 204 | return value; 205 | } 206 | 207 | /** 208 | * Disable setting item 209 | * @param key key name 210 | */ 211 | disable(key: string) { 212 | let element = this.elements.get(key) as any; 213 | if (element) { 214 | element.disabled = true; 215 | } 216 | } 217 | 218 | /** 219 | * Enable setting item 220 | * @param key key name 221 | */ 222 | enable(key: string) { 223 | let element = this.elements.get(key) as any; 224 | if (element) { 225 | element.disabled = false; 226 | } 227 | } 228 | 229 | /** 230 | * 将设置项目导出为 JSON 对象 231 | * @returns object 232 | */ 233 | dump(): Object { 234 | let data: any = {}; 235 | for (let [key, item] of this.settings) { 236 | if (item.type === 'button') continue; 237 | data[key] = item.value; 238 | } 239 | return data; 240 | } 241 | 242 | addItem(item: ISettingUtilsItem) { 243 | this.settings.set(item.key, item); 244 | const IsCustom = item.type === 'custom'; 245 | let error = IsCustom && (item.createElement === undefined || item.getEleVal === undefined || item.setEleVal === undefined); 246 | if (error) { 247 | console.error('The custom setting item must have createElement, getEleVal and setEleVal methods'); 248 | return; 249 | } 250 | 251 | if (item.getEleVal === undefined) { 252 | item.getEleVal = createDefaultGetter(item.type); 253 | } 254 | if (item.setEleVal === undefined) { 255 | item.setEleVal = createDefaultSetter(item.type); 256 | } 257 | 258 | if (item.createElement === undefined) { 259 | let itemElement = this.createDefaultElement(item); 260 | this.elements.set(item.key, itemElement); 261 | this.plugin.setting.addItem({ 262 | title: item.title, 263 | description: item?.description, 264 | direction: item?.direction, 265 | createActionElement: () => { 266 | this.updateElementFromValue(item.key); 267 | let element = this.getElement(item.key); 268 | return element; 269 | } 270 | }); 271 | } else { 272 | this.plugin.setting.addItem({ 273 | title: item.title, 274 | description: item?.description, 275 | direction: item?.direction, 276 | createActionElement: () => { 277 | let val = this.get(item.key); 278 | let element = item.createElement(val); 279 | this.elements.set(item.key, element); 280 | return element; 281 | } 282 | }); 283 | } 284 | } 285 | 286 | createDefaultElement(item: ISettingUtilsItem) { 287 | let itemElement: HTMLElement; 288 | //阻止思源内置的回车键确认 289 | const preventEnterConfirm = (e) => { 290 | if (e.key === 'Enter') { 291 | e.preventDefault(); 292 | e.stopImmediatePropagation(); 293 | } 294 | } 295 | switch (item.type) { 296 | case 'checkbox': 297 | let element: HTMLInputElement = document.createElement('input'); 298 | element.type = 'checkbox'; 299 | element.checked = item.value; 300 | element.className = "b3-switch fn__flex-center"; 301 | itemElement = element; 302 | element.onchange = item.action?.callback ?? (() => { }); 303 | break; 304 | case 'select': 305 | let selectElement: HTMLSelectElement = document.createElement('select'); 306 | selectElement.className = "b3-select fn__flex-center fn__size200"; 307 | let options = item?.options ?? {}; 308 | for (let val in options) { 309 | let optionElement = document.createElement('option'); 310 | let text = options[val]; 311 | optionElement.value = val; 312 | optionElement.text = text; 313 | selectElement.appendChild(optionElement); 314 | } 315 | selectElement.value = item.value; 316 | selectElement.onchange = item.action?.callback ?? (() => { }); 317 | itemElement = selectElement; 318 | break; 319 | case 'slider': 320 | let sliderElement: HTMLInputElement = document.createElement('input'); 321 | sliderElement.type = 'range'; 322 | sliderElement.className = 'b3-slider fn__size200 b3-tooltips b3-tooltips__n'; 323 | sliderElement.ariaLabel = item.value; 324 | sliderElement.min = item.slider?.min.toString() ?? '0'; 325 | sliderElement.max = item.slider?.max.toString() ?? '100'; 326 | sliderElement.step = item.slider?.step.toString() ?? '1'; 327 | sliderElement.value = item.value; 328 | sliderElement.onchange = () => { 329 | sliderElement.ariaLabel = sliderElement.value; 330 | item.action?.callback(); 331 | } 332 | itemElement = sliderElement; 333 | break; 334 | case 'textinput': 335 | let textInputElement: HTMLInputElement = document.createElement('input'); 336 | textInputElement.className = 'b3-text-field fn__flex-center fn__size200'; 337 | textInputElement.value = item.value; 338 | textInputElement.onchange = item.action?.callback ?? (() => { }); 339 | itemElement = textInputElement; 340 | textInputElement.addEventListener('keydown', preventEnterConfirm); 341 | break; 342 | case 'textarea': 343 | let textareaElement: HTMLTextAreaElement = document.createElement('textarea'); 344 | textareaElement.className = "b3-text-field fn__block"; 345 | textareaElement.rows = 6; 346 | textareaElement.value = item.value; 347 | textareaElement.spellcheck = false; 348 | textareaElement.onchange = item.action?.callback ?? (() => { }); 349 | itemElement = textareaElement; 350 | break; 351 | case 'number': 352 | let numberElement: HTMLInputElement = document.createElement('input'); 353 | numberElement.type = 'number'; 354 | numberElement.className = 'b3-text-field fn__flex-center fn__size200'; 355 | numberElement.value = item.value; 356 | itemElement = numberElement; 357 | numberElement.addEventListener('keydown', preventEnterConfirm); 358 | break; 359 | case 'button': 360 | let buttonElement: HTMLButtonElement = document.createElement('button'); 361 | buttonElement.className = "b3-button b3-button--outline fn__flex-center fn__size200"; 362 | buttonElement.innerText = item.button?.label ?? 'Button'; 363 | buttonElement.onclick = item.button?.callback ?? (() => { }); 364 | itemElement = buttonElement; 365 | break; 366 | case 'hint': 367 | let hintElement: HTMLElement = document.createElement('div'); 368 | hintElement.className = 'b3-label fn__flex-center'; 369 | itemElement = hintElement; 370 | break; 371 | } 372 | return itemElement; 373 | } 374 | 375 | /** 376 | * return the setting element 377 | * @param key key name 378 | * @returns element 379 | */ 380 | getElement(key: string) { 381 | // let item = this.settings.get(key); 382 | let element = this.elements.get(key) as any; 383 | return element; 384 | } 385 | 386 | private updateValueFromElement(key: string) { 387 | let item = this.settings.get(key); 388 | if (item.type === 'button') return; 389 | let element = this.elements.get(key) as any; 390 | item.value = item.getEleVal(element); 391 | } 392 | 393 | private updateElementFromValue(key: string) { 394 | let item = this.settings.get(key); 395 | if (item.type === 'button') return; 396 | let element = this.elements.get(key) as any; 397 | item.setEleVal(element, item.value); 398 | } 399 | } -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { 2 | Plugin, 3 | getFrontend, 4 | getBackend, 5 | fetchPost, 6 | IModel, 7 | Protyle, 8 | IProtyle, 9 | Toolbar 10 | } from "siyuan"; 11 | 12 | import { IMenuItem } from "siyuan/types"; 13 | 14 | 15 | 16 | 17 | export default class PluginSample extends Plugin { 18 | private isMobile: boolean; 19 | private formatPainterEnable = false; 20 | private formatData: { datatype: string, style: string } | null = null; 21 | private protyle: IProtyle; 22 | 23 | // 添加工具栏按钮 24 | updateProtyleToolbar(toolbar: Array) { 25 | toolbar.push( 26 | { 27 | name: "format-painter", 28 | icon: "iconFormat", 29 | tipPosition: "n", 30 | tip: this.i18n.tips, 31 | click: (protyle: Protyle) => { 32 | this.protyle = protyle.protyle; 33 | 34 | if (!this.formatPainterEnable) { 35 | const selectedInfo = this.getSelectedParentHtml(); 36 | if (selectedInfo) { 37 | this.formatData = { 38 | datatype: selectedInfo.datatype, 39 | style: selectedInfo.style 40 | }; 41 | 42 | } 43 | else { 44 | this.formatData = null; 45 | // console.log("选中无样式文字"); 46 | } 47 | this.formatPainterEnable = true; 48 | document.body.dataset.formatPainterEnable = "true"; 49 | // console.log(this.formatData); 50 | fetchPost("/api/notification/pushMsg", { "msg": this.i18n.enable, "timeout": 7000 }); 51 | 52 | ///v dock indicator worker 53 | const indicator = document.querySelector(".siyuan-plugin-formatPainter_brush_indicator"); 54 | if (indicator) { 55 | (indicator as HTMLElement).style.display = "flex"; 56 | } 57 | ///^ dock indicator worker 58 | 59 | // 关闭toolbar 60 | this.protyle.toolbar.range.collapse(true); 61 | // 选择所有具有 .protyle-toolbar 类的元素 62 | const toolbarElements = document.querySelectorAll('.protyle-toolbar'); 63 | // 遍历选中的元素 64 | toolbarElements.forEach(element => { 65 | // 检查元素是否没有 .fn__none 类 66 | if (!element.classList.contains("fn__none")) { 67 | // 如果没有 .fn__none 类,则添加它 68 | element.classList.add("fn__none"); 69 | } 70 | }); 71 | 72 | 73 | } 74 | } 75 | } 76 | ); 77 | return toolbar; 78 | } 79 | onload() { 80 | 81 | document.addEventListener('mouseup', (event) => { 82 | if (this.formatPainterEnable) { 83 | const selection = window.getSelection(); 84 | let hasmath = false; 85 | if (selection && selection.rangeCount > 0) { 86 | const range = selection.getRangeAt(0); 87 | const selectedText = range.toString(); 88 | if (selectedText) { 89 | const startBlockElement = hasClosestBlock(range.startContainer); 90 | if (range.endContainer.nodeType !== 3 && (range.endContainer as HTMLElement).tagName === "DIV" && range.endOffset === 0) { 91 | // 三选中段落块时,rangeEnd 会在下一个块 92 | if ((range.endContainer as HTMLElement).classList.contains("protyle-attr") && startBlockElement) { 93 | // 三击在悬浮层中会选择到 attr https://github.com/siyuan-note/siyuan/issues/4636 94 | // 需要获取可编辑元素,使用 previousElementSibling 的话会 https://github.com/siyuan-note/siyuan/issues/9714 95 | setLastNodeRange(getContenteditableElement(startBlockElement), range, false); 96 | } 97 | } 98 | this.protyle.toolbar.range = range; // 更改选区 99 | // console.log(this.protyle.toolbar.range.toString()); 100 | // Apply the stored format to the selected text 101 | // 如果都为空 102 | this.protyle.toolbar.setInlineMark(this.protyle, "clear", "range"); 103 | if (!this.formatData) { 104 | // 移动光标到末尾 105 | this.protyle.toolbar.range.collapse(false); // false表示折叠到末尾 106 | 107 | // 工具栏关闭 108 | this.protyle.toolbar.element.classList.add("fn__none"); 109 | return; 110 | } 111 | if (this.formatData.datatype) { 112 | // console.log(this.formatData.datatype); 113 | 114 | 115 | // this.protyle.toolbar.setInlineMark(this.protyle, this.formatData.datatype, "range"); 116 | // 检查是否包含 "inline-math" 117 | if (this.formatData.datatype.includes("inline-math")) { 118 | // 单独设置 "inline-math" 样式 119 | this.protyle.toolbar.setInlineMark(this.protyle, "inline-math", "range", { 120 | type: "inline-math", 121 | }); 122 | hasmath = true; 123 | } 124 | const otherTypes = this.formatData.datatype.replace(/\b(inline-math|block-ref|a|text)\b/g, "").trim(); 125 | if (otherTypes) { 126 | this.protyle.toolbar.setInlineMark(this.protyle, otherTypes, "range"); 127 | } 128 | } 129 | if (this.formatData.style) { 130 | // this.protyle.toolbar.setInlineMark(this.protyle, "text", "range", { "type": "style1", "color": this.formatData.style }); 131 | // console.log(backgroundColor, color, fontSize, textShadow); 132 | let type = "text"; 133 | if (hasmath) { 134 | // 数学公式加颜色有bug 135 | type = "inline-math"; 136 | return; 137 | } 138 | const { backgroundColor, color, fontSize, textShadow, webkitTextStroke, webkitTextFillColor } = parseStyle(this.formatData.style); 139 | if (backgroundColor) { 140 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 141 | "type": "backgroundColor", 142 | "color": backgroundColor 143 | }); 144 | } 145 | 146 | if (color) { 147 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 148 | "type": "color", 149 | "color": color 150 | }); 151 | } 152 | 153 | if (fontSize) { 154 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 155 | "type": "fontSize", 156 | "color": fontSize 157 | }); 158 | } 159 | if (textShadow) { 160 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 161 | "type": "style4", //投影效果 162 | "color": textShadow 163 | }); 164 | } 165 | if (webkitTextStroke) { 166 | this.protyle.toolbar.setInlineMark(this.protyle, type, "range", { 167 | "type": "style2", //镂空效果 168 | "color": webkitTextStroke 169 | }); 170 | } 171 | } 172 | 173 | // 移动光标到末尾 174 | this.protyle.toolbar.range.collapse(false); // false表示折叠到末尾 175 | 176 | // 工具栏关闭 177 | this.protyle.toolbar.element.classList.add("fn__none"); 178 | 179 | } 180 | } 181 | } 182 | }); 183 | document.addEventListener("keydown", (event) => { 184 | if (event.key === "Escape") { 185 | if (this.formatPainterEnable) { 186 | // 阻止事件冒泡和默认行为 187 | event.stopPropagation(); 188 | event.preventDefault(); 189 | 190 | this.formatPainterEnable = false; 191 | document.body.dataset.formatPainterEnable = "false"; 192 | this.formatData = null; 193 | fetchPost("/api/notification/pushMsg", { "msg": this.i18n.disable, "timeout": 7000 }); 194 | 195 | ///v dock indicator worker 196 | const indicator = document.querySelector(".siyuan-plugin-formatPainter_brush_indicator"); 197 | if (indicator) { 198 | (indicator as HTMLElement).style.display = "none"; 199 | } 200 | ///^ dock indicator worker 201 | 202 | // 确保取消所有选择 203 | window.getSelection()?.removeAllRanges(); 204 | } 205 | } 206 | }, true); // 添加 true 参数使用事件捕获阶段 207 | 208 | 209 | const hasClosestByAttribute = (element: Node, attr: string, value: string | null, top = false) => { 210 | if (!element) { 211 | return false; 212 | } 213 | if (element.nodeType === 3) { 214 | element = element.parentElement; 215 | } 216 | let e = element as HTMLElement; 217 | let isClosest = false; 218 | while (e && !isClosest && (top ? e.tagName !== "BODY" : !e.classList.contains("protyle-wysiwyg"))) { 219 | if (typeof value === "string" && e.getAttribute(attr)?.split(" ").includes(value)) { 220 | isClosest = true; 221 | } else if (typeof value !== "string" && e.hasAttribute(attr)) { 222 | isClosest = true; 223 | } else { 224 | e = e.parentElement; 225 | } 226 | } 227 | return isClosest && e; 228 | }; 229 | const hasClosestBlock = (element: Node) => { 230 | const nodeElement = hasClosestByAttribute(element, "data-node-id", null); 231 | if (nodeElement && nodeElement.tagName !== "BUTTON" && nodeElement.getAttribute("data-type")?.startsWith("Node")) { 232 | return nodeElement; 233 | } 234 | return false; 235 | }; 236 | const getContenteditableElement = (element: Element) => { 237 | if (!element || (element.getAttribute("contenteditable") === "true") && !element.classList.contains("protyle-wysiwyg")) { 238 | return element; 239 | } 240 | return element.querySelector('[contenteditable="true"]'); 241 | }; 242 | const setLastNodeRange = (editElement: Element, range: Range, setStart = true) => { 243 | if (!editElement) { 244 | return range; 245 | } 246 | let lastNode = editElement.lastChild as Element; 247 | while (lastNode && lastNode.nodeType !== 3) { 248 | if (lastNode.nodeType !== 3 && lastNode.tagName === "BR") { 249 | // 防止单元格中 ⇧↓ 全部选中 250 | return range; 251 | } 252 | // 最后一个为多种行内元素嵌套 253 | lastNode = lastNode.lastChild as Element; 254 | } 255 | if (!lastNode) { 256 | range.selectNodeContents(editElement); 257 | return range; 258 | } 259 | if (setStart) { 260 | range.setStart(lastNode, lastNode.textContent.length); 261 | } else { 262 | range.setEnd(lastNode, lastNode.textContent.length); 263 | } 264 | return range; 265 | }; 266 | function parseStyle(styleString) { 267 | const styles = styleString.split(';').filter(s => s.trim() !== ''); 268 | const styleObject = {}; 269 | 270 | styles.forEach(style => { 271 | const [property, value] = style.split(':').map(s => s.trim()); 272 | styleObject[property] = value; 273 | }); 274 | 275 | return { 276 | backgroundColor: styleObject['background-color'], 277 | color: styleObject['color'], 278 | fontSize: styleObject['font-size'], 279 | textShadow: styleObject['text-shadow'], 280 | webkitTextStroke: styleObject['-webkit-text-stroke'], 281 | webkitTextFillColor: styleObject['-webkit-text-fill-color'] 282 | }; 283 | } 284 | 285 | 286 | console.log(this.i18n.helloPlugin); 287 | } 288 | getSelectedParentHtml() { 289 | const selection = window.getSelection(); 290 | if (selection.rangeCount > 0) { 291 | const range = selection.getRangeAt(0); 292 | let selectedNode = range.startContainer; 293 | const endNode = range.endContainer; 294 | 295 | // 检查 endNode 的 previousSibling 296 | if (endNode.previousSibling && endNode.previousSibling.nodeType === Node.ELEMENT_NODE) { 297 | const previousSibling = endNode.previousSibling; 298 | if (previousSibling.tagName.toLowerCase() === "span" && previousSibling.classList.contains("render-node")) { 299 | selectedNode = previousSibling; 300 | } 301 | } 302 | 303 | let parentElement = selectedNode.nodeType === Node.TEXT_NODE ? selectedNode.parentNode : selectedNode; 304 | while (parentElement && !parentElement.hasAttribute("data-type")) { 305 | parentElement = parentElement.parentElement; 306 | } 307 | 308 | if (parentElement && parentElement.tagName.toLowerCase() === "span") { 309 | const result = { 310 | html: parentElement.outerHTML, 311 | datatype: parentElement.getAttribute("data-type"), 312 | style: parentElement.getAttribute("style") 313 | }; 314 | // 清空选区 315 | selection.removeAllRanges(); 316 | return result; 317 | } 318 | } 319 | // 清空选区 320 | selection.removeAllRanges(); 321 | return null; 322 | } 323 | addDockBrushModeIndicator() { 324 | const indicator = document.createElement("div"); 325 | indicator.classList.add("siyuan-plugin-formatPainter_brush_indicator", "status__counter", "toolbar__item", "ariaLabel", "blink-animation"); 326 | indicator.innerHTML = ``; 327 | this.addStatusBar({ 328 | element: indicator, 329 | }); 330 | // indicator添加aria - label 331 | indicator.setAttribute("aria-label", this.i18n.closeTips); 332 | indicator.style.display = "none"; 333 | 334 | const style = document.createElement('style'); 335 | style.textContent = ` 336 | @keyframes blink { 337 | 0% { opacity: 1; } 338 | 50% { opacity: 0.2; } 339 | 100% { opacity: 1; } 340 | } 341 | .blink-animation { 342 | animation: blink 1s infinite; 343 | } 344 | `; 345 | document.head.appendChild(style); 346 | 347 | indicator.addEventListener('click', () => { 348 | this.toggleFormatPainter(); 349 | }); 350 | } 351 | 352 | toggleFormatPainter() { 353 | if (this.formatPainterEnable) { 354 | fetchPost("/api/notification/pushMsg", { "msg": this.i18n.disable, "timeout": 7000 }); 355 | document.body.dataset.formatPainterEnable = "false"; 356 | } else { 357 | fetchPost("/api/notification/pushMsg", { "msg": this.i18n.enable, "timeout": 7000 }); 358 | document.body.dataset.formatPainterEnable = "true"; 359 | } 360 | this.formatPainterEnable = !this.formatPainterEnable; 361 | const indicator = document.querySelector(".siyuan-plugin-formatPainter_brush_indicator"); 362 | if (indicator) { 363 | (indicator as HTMLElement).style.display = this.formatPainterEnable ? "flex" : "none"; 364 | } 365 | } 366 | 367 | 368 | onLayoutReady() { 369 | this.addDockBrushModeIndicator(); 370 | } 371 | 372 | onunload() { 373 | console.log(this.i18n.byePlugin); 374 | } 375 | 376 | uninstall() { 377 | console.log("uninstall"); 378 | } 379 | 380 | 381 | } -------------------------------------------------------------------------------- /src/api.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (c) 2023 frostime. All rights reserved. 3 | * https://github.com/frostime/sy-plugin-template-vite 4 | * 5 | * See API Document in [API.md](https://github.com/siyuan-note/siyuan/blob/master/API.md) 6 | * API 文档见 [API_zh_CN.md](https://github.com/siyuan-note/siyuan/blob/master/API_zh_CN.md) 7 | */ 8 | 9 | import { fetchPost, fetchSyncPost, IWebSocketData, openTab, Constants } from "siyuan"; 10 | import { getFrontend, openMobileFileById } from 'siyuan'; 11 | 12 | 13 | export async function request(url: string, data: any) { 14 | let response: IWebSocketData = await fetchSyncPost(url, data); 15 | let res = response.code === 0 ? response.data : null; 16 | return res; 17 | } 18 | 19 | // **************************************** Riff (闪卡) **************************************** 20 | 21 | export async function addRiffCards(blockIDs: string[], deckID: string = Constants.QUICK_DECK_ID): Promise { 22 | let data = { 23 | deckID: deckID, 24 | blockIDs: blockIDs 25 | }; 26 | let url = '/api/riff/addRiffCards'; 27 | return request(url, data); 28 | } 29 | 30 | export async function removeRiffCards(blockIDs: string[], deckID: string = Constants.QUICK_DECK_ID): Promise { 31 | let data = { 32 | deckID: deckID, 33 | blockIDs: blockIDs 34 | }; 35 | let url = '/api/riff/removeRiffCards'; 36 | return request(url, data); 37 | } 38 | 39 | export async function getRiffDecks(): Promise { 40 | let url = '/api/riff/getRiffDecks'; 41 | return request(url, {}); 42 | } 43 | 44 | export async function createRiffDeck(name: string): Promise { 45 | let data = { 46 | name: name 47 | }; 48 | let url = '/api/riff/createRiffDeck'; 49 | return request(url, data); 50 | } 51 | 52 | export async function removeRiffDeck(deckID: string): Promise { 53 | let data = { 54 | deckID: deckID 55 | }; 56 | let url = '/api/riff/removeRiffDeck'; 57 | return request(url, data); 58 | } 59 | 60 | export async function renameRiffDeck(deckID: string, name: string): Promise { 61 | let data = { 62 | deckID: deckID, 63 | name: name 64 | }; 65 | let url = '/api/riff/renameRiffDeck'; 66 | return request(url, data); 67 | } 68 | 69 | export async function getRiffCards(deckID: string): Promise { 70 | let data = { 71 | deckID: deckID 72 | }; 73 | let url = '/api/riff/getRiffCards'; 74 | return request(url, data); 75 | } 76 | 77 | 78 | // **************************************** Noteboook **************************************** 79 | 80 | 81 | export async function lsNotebooks(): Promise { 82 | let url = '/api/notebook/lsNotebooks'; 83 | return request(url, ''); 84 | } 85 | 86 | 87 | export async function openNotebook(notebook: NotebookId) { 88 | let url = '/api/notebook/openNotebook'; 89 | return request(url, { notebook: notebook }); 90 | } 91 | 92 | 93 | export async function closeNotebook(notebook: NotebookId) { 94 | let url = '/api/notebook/closeNotebook'; 95 | return request(url, { notebook: notebook }); 96 | } 97 | 98 | 99 | export async function renameNotebook(notebook: NotebookId, name: string) { 100 | let url = '/api/notebook/renameNotebook'; 101 | return request(url, { notebook: notebook, name: name }); 102 | } 103 | 104 | 105 | export async function createNotebook(name: string): Promise { 106 | let url = '/api/notebook/createNotebook'; 107 | return request(url, { name: name }); 108 | } 109 | 110 | 111 | export async function removeNotebook(notebook: NotebookId) { 112 | let url = '/api/notebook/removeNotebook'; 113 | return request(url, { notebook: notebook }); 114 | } 115 | 116 | 117 | export async function getNotebookConf(notebook: NotebookId): Promise { 118 | let data = { notebook: notebook }; 119 | let url = '/api/notebook/getNotebookConf'; 120 | return request(url, data); 121 | } 122 | 123 | 124 | export async function setNotebookConf(notebook: NotebookId, conf: NotebookConf): Promise { 125 | let data = { notebook: notebook, conf: conf }; 126 | let url = '/api/notebook/setNotebookConf'; 127 | return request(url, data); 128 | } 129 | 130 | 131 | // **************************************** File Tree **************************************** 132 | 133 | export async function getDoc(id: BlockId) { 134 | let data = { 135 | id: id 136 | }; 137 | let url = '/api/filetree/getDoc'; 138 | return request(url, data); 139 | } 140 | 141 | 142 | export async function createDocWithMd(notebook: NotebookId, path: string, markdown: string): Promise { 143 | let data = { 144 | notebook: notebook, 145 | path: path, 146 | markdown: markdown, 147 | }; 148 | let url = '/api/filetree/createDocWithMd'; 149 | return request(url, data); 150 | } 151 | 152 | 153 | export async function renameDoc(notebook: NotebookId, path: string, title: string): Promise { 154 | let data = { 155 | doc: notebook, 156 | path: path, 157 | title: title 158 | }; 159 | let url = '/api/filetree/renameDoc'; 160 | return request(url, data); 161 | } 162 | 163 | export async function renameDocByID(id: string, title: string): Promise { 164 | let data = { 165 | id: id, 166 | title: title 167 | }; 168 | let url = '/api/filetree/renameDocByID'; 169 | return request(url, data); 170 | } 171 | 172 | 173 | export async function removeDoc(notebook: NotebookId, path: string) { 174 | let data = { 175 | notebook: notebook, 176 | path: path, 177 | }; 178 | let url = '/api/filetree/removeDoc'; 179 | return request(url, data); 180 | } 181 | 182 | 183 | export async function moveDocs(fromPaths: string[], toNotebook: NotebookId, toPath: string) { 184 | let data = { 185 | fromPaths: fromPaths, 186 | toNotebook: toNotebook, 187 | toPath: toPath 188 | }; 189 | let url = '/api/filetree/moveDocs'; 190 | return request(url, data); 191 | } 192 | 193 | export async function moveDocsByID(fromIDs: string[], toID: string) { 194 | let data = { 195 | fromIDs: fromIDs, 196 | toID: toID 197 | }; 198 | let url = '/api/filetree/moveDocsByID'; 199 | return request(url, data); 200 | } 201 | 202 | 203 | export async function getHPathByPath(notebook: NotebookId, path: string): Promise { 204 | let data = { 205 | notebook: notebook, 206 | path: path 207 | }; 208 | let url = '/api/filetree/getHPathByPath'; 209 | return request(url, data); 210 | } 211 | 212 | 213 | export async function getHPathByID(id: BlockId): Promise { 214 | let data = { 215 | id: id 216 | }; 217 | let url = '/api/filetree/getHPathByID'; 218 | return request(url, data); 219 | } 220 | 221 | 222 | export async function getIDsByHPath(notebook: NotebookId, path: string): Promise { 223 | let data = { 224 | notebook: notebook, 225 | path: path 226 | }; 227 | let url = '/api/filetree/getIDsByHPath'; 228 | return request(url, data); 229 | } 230 | 231 | // **************************************** Asset Files **************************************** 232 | 233 | export async function upload(assetsDirPath: string, files: any[]): Promise { 234 | let form = new FormData(); 235 | form.append('assetsDirPath', assetsDirPath); 236 | for (let file of files) { 237 | form.append('file[]', file); 238 | } 239 | let url = '/api/asset/upload'; 240 | return request(url, form); 241 | } 242 | 243 | // **************************************** Block **************************************** 244 | type DataType = "markdown" | "dom"; 245 | export async function insertBlock( 246 | dataType: DataType, data: string, 247 | nextID?: BlockId, previousID?: BlockId, parentID?: BlockId 248 | ): Promise { 249 | let payload = { 250 | dataType: dataType, 251 | data: data, 252 | nextID: nextID, 253 | previousID: previousID, 254 | parentID: parentID 255 | } 256 | let url = '/api/block/insertBlock'; 257 | return request(url, payload); 258 | } 259 | 260 | 261 | export async function prependBlock(dataType: DataType, data: string, parentID: BlockId | DocumentId): Promise { 262 | let payload = { 263 | dataType: dataType, 264 | data: data, 265 | parentID: parentID 266 | } 267 | let url = '/api/block/prependBlock'; 268 | return request(url, payload); 269 | } 270 | 271 | 272 | export async function appendBlock(dataType: DataType, data: string, parentID: BlockId | DocumentId): Promise { 273 | let payload = { 274 | dataType: dataType, 275 | data: data, 276 | parentID: parentID 277 | } 278 | let url = '/api/block/appendBlock'; 279 | return request(url, payload); 280 | } 281 | 282 | 283 | export async function updateBlock(dataType: DataType, data: string, id: BlockId): Promise { 284 | let payload = { 285 | dataType: dataType, 286 | data: data, 287 | id: id 288 | } 289 | let url = '/api/block/updateBlock'; 290 | return request(url, payload); 291 | } 292 | 293 | 294 | export async function deleteBlock(id: BlockId): Promise { 295 | let data = { 296 | id: id 297 | } 298 | let url = '/api/block/deleteBlock'; 299 | return request(url, data); 300 | } 301 | 302 | 303 | export async function moveBlock(id: BlockId, previousID?: PreviousID, parentID?: ParentID): Promise { 304 | let data = { 305 | id: id, 306 | previousID: previousID, 307 | parentID: parentID 308 | } 309 | let url = '/api/block/moveBlock'; 310 | return request(url, data); 311 | } 312 | 313 | 314 | export async function foldBlock(id: BlockId) { 315 | let data = { 316 | id: id 317 | } 318 | let url = '/api/block/foldBlock'; 319 | return request(url, data); 320 | } 321 | 322 | 323 | export async function unfoldBlock(id: BlockId) { 324 | let data = { 325 | id: id 326 | } 327 | let url = '/api/block/unfoldBlock'; 328 | return request(url, data); 329 | } 330 | 331 | 332 | export async function getBlockKramdown(id: BlockId, mode: string = 'md'): Promise { 333 | let data = { 334 | id: id, 335 | mode: mode 336 | } 337 | let url = '/api/block/getBlockKramdown'; 338 | return request(url, data); 339 | } 340 | export async function getBlockDOM(id: BlockId) { 341 | let data = { 342 | id: id 343 | } 344 | let url = '/api/block/getBlockDOM'; 345 | return request(url, data); 346 | } 347 | 348 | export async function getChildBlocks(id: BlockId): Promise { 349 | let data = { 350 | id: id 351 | } 352 | let url = '/api/block/getChildBlocks'; 353 | return request(url, data); 354 | } 355 | 356 | export async function transferBlockRef(fromID: BlockId, toID: BlockId, refIDs: BlockId[]) { 357 | let data = { 358 | fromID: fromID, 359 | toID: toID, 360 | refIDs: refIDs 361 | } 362 | let url = '/api/block/transferBlockRef'; 363 | return request(url, data); 364 | } 365 | 366 | // **************************************** Attributes **************************************** 367 | export async function setBlockAttrs(id: BlockId, attrs: { [key: string]: string }) { 368 | let data = { 369 | id: id, 370 | attrs: attrs 371 | } 372 | let url = '/api/attr/setBlockAttrs'; 373 | return request(url, data); 374 | } 375 | 376 | 377 | export async function getBlockAttrs(id: BlockId): Promise<{ [key: string]: string }> { 378 | let data = { 379 | id: id 380 | } 381 | let url = '/api/attr/getBlockAttrs'; 382 | return request(url, data); 383 | } 384 | 385 | // **************************************** SQL **************************************** 386 | 387 | export async function sql(sql: string): Promise { 388 | let sqldata = { 389 | stmt: sql, 390 | }; 391 | let url = '/api/query/sql'; 392 | return request(url, sqldata); 393 | } 394 | 395 | export async function getBlockByID(blockId: string): Promise { 396 | let sqlScript = `select * from blocks where id ='${blockId}'`; 397 | let data = await sql(sqlScript); 398 | return data[0]; 399 | } 400 | 401 | export async function openBlock(blockId: string) { 402 | // 检测块是否存在 403 | const block = await getBlockByID(blockId); 404 | if (!block) { 405 | throw new Error('块不存在'); 406 | } 407 | // 判断是否是移动端 408 | const isMobile = getFrontend().endsWith('mobile'); 409 | if (isMobile) { 410 | // 如果是mobile,直接打开块 411 | openMobileFileById(window.siyuan.ws.app, blockId); 412 | return; 413 | } 414 | // 判断块的类型 415 | const isDoc = block.type === 'd'; 416 | if (isDoc) { 417 | openTab({ 418 | app: window.siyuan.ws.app, 419 | doc: { 420 | id: blockId, 421 | action: ["cb-get-focus", "cb-get-scroll"] 422 | }, 423 | keepCursor: false, 424 | removeCurrentTab: false 425 | }); 426 | } else { 427 | openTab({ 428 | app: window.siyuan.ws.app, 429 | doc: { 430 | id: blockId, 431 | action: ["cb-get-focus", "cb-get-context", "cb-get-hl"] 432 | }, 433 | keepCursor: false, 434 | removeCurrentTab: false 435 | }); 436 | 437 | } 438 | } 439 | 440 | // **************************************** Template **************************************** 441 | 442 | export async function render(id: DocumentId, path: string): Promise { 443 | let data = { 444 | id: id, 445 | path: path 446 | } 447 | let url = '/api/template/render'; 448 | return request(url, data); 449 | } 450 | 451 | 452 | export async function renderSprig(template: string): Promise { 453 | let url = '/api/template/renderSprig'; 454 | return request(url, { template: template }); 455 | } 456 | 457 | // **************************************** File **************************************** 458 | 459 | 460 | 461 | export async function getFile(path: string): Promise { 462 | let data = { 463 | path: path 464 | } 465 | let url = '/api/file/getFile'; 466 | return new Promise((resolve, _) => { 467 | fetchPost(url, data, (content: any) => { 468 | resolve(content) 469 | }); 470 | }); 471 | } 472 | 473 | 474 | /** 475 | * fetchPost will secretly convert data into json, this func merely return Blob 476 | * @param endpoint 477 | * @returns 478 | */ 479 | export const getFileBlob = async (path: string): Promise => { 480 | const endpoint = '/api/file/getFile' 481 | let response = await fetch(endpoint, { 482 | method: 'POST', 483 | body: JSON.stringify({ 484 | path: path 485 | }) 486 | }); 487 | if (!response.ok) { 488 | return null; 489 | } 490 | let data = await response.blob(); 491 | return data; 492 | } 493 | 494 | 495 | export async function putFile(path: string, isDir: boolean, file: any) { 496 | let form = new FormData(); 497 | form.append('path', path); 498 | form.append('isDir', isDir.toString()); 499 | form.append('modTime', Date.now().toString()); 500 | form.append('file', file); 501 | let url = '/api/file/putFile'; 502 | return request(url, form); 503 | } 504 | 505 | export async function removeFile(path: string) { 506 | let data = { 507 | path: path 508 | } 509 | let url = '/api/file/removeFile'; 510 | return request(url, data); 511 | } 512 | 513 | 514 | 515 | export async function readDir(path: string): Promise { 516 | let data = { 517 | path: path 518 | } 519 | let url = '/api/file/readDir'; 520 | return request(url, data); 521 | } 522 | 523 | 524 | // **************************************** Export **************************************** 525 | 526 | export async function exportMdContent(id: DocumentId): Promise { 527 | let data = { 528 | id: id 529 | } 530 | let url = '/api/export/exportMdContent'; 531 | return request(url, data); 532 | } 533 | 534 | export async function exportResources(paths: string[], name: string): Promise { 535 | let data = { 536 | paths: paths, 537 | name: name 538 | } 539 | let url = '/api/export/exportResources'; 540 | return request(url, data); 541 | } 542 | 543 | // **************************************** Convert **************************************** 544 | 545 | export type PandocArgs = string; 546 | export async function pandoc(args: PandocArgs[]) { 547 | let data = { 548 | args: args 549 | } 550 | let url = '/api/convert/pandoc'; 551 | return request(url, data); 552 | } 553 | 554 | // **************************************** Notification **************************************** 555 | 556 | // /api/notification/pushMsg 557 | // { 558 | // "msg": "test", 559 | // "timeout": 7000 560 | // } 561 | export async function pushMsg(msg: string, timeout: number = 7000) { 562 | let payload = { 563 | msg: msg, 564 | timeout: timeout 565 | }; 566 | let url = "/api/notification/pushMsg"; 567 | return request(url, payload); 568 | } 569 | 570 | export async function pushErrMsg(msg: string, timeout: number = 7000) { 571 | let payload = { 572 | msg: msg, 573 | timeout: timeout 574 | }; 575 | let url = "/api/notification/pushErrMsg"; 576 | return request(url, payload); 577 | } 578 | 579 | // **************************************** Network **************************************** 580 | export async function forwardProxy( 581 | url: string, method: string = 'GET', payload: any = {}, 582 | headers: any[] = [], timeout: number = 7000, contentType: string = "text/html" 583 | ): Promise { 584 | let data = { 585 | url: url, 586 | method: method, 587 | timeout: timeout, 588 | contentType: contentType, 589 | headers: headers, 590 | payload: payload 591 | } 592 | let url1 = '/api/network/forwardProxy'; 593 | return request(url1, data); 594 | } 595 | 596 | 597 | // **************************************** System **************************************** 598 | 599 | export async function bootProgress(): Promise { 600 | return request('/api/system/bootProgress', {}); 601 | } 602 | 603 | export async function version(): Promise { 604 | return request('/api/system/version', {}); 605 | } 606 | 607 | export async function currentTime(): Promise { 608 | return request('/api/system/currentTime', {}); 609 | } 610 | 611 | 612 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU AFFERO GENERAL PUBLIC LICENSE 2 | Version 3, 19 November 2007 3 | 4 | Copyright (c) 2025 Achuan-2 5 | 6 | Preamble 7 | 8 | The GNU Affero General Public License is a free, copyleft license for 9 | software and other kinds of works, specifically designed to ensure 10 | cooperation with the community in the case of network server software. 11 | 12 | The licenses for most software and other practical works are designed 13 | to take away your freedom to share and change the works. By contrast, 14 | our General Public Licenses are intended to guarantee your freedom to 15 | share and change all versions of a program--to make sure it remains free 16 | software for all its users. 17 | 18 | When we speak of free software, we are referring to freedom, not 19 | price. Our General Public Licenses are designed to make sure that you 20 | have the freedom to distribute copies of free software (and charge for 21 | them if you wish), that you receive source code or can get it if you 22 | want it, that you can change the software or use pieces of it in new 23 | free programs, and that you know you can do these things. 24 | 25 | Developers that use our General Public Licenses protect your rights 26 | with two steps: (1) assert copyright on the software, and (2) offer 27 | you this License which gives you legal permission to copy, distribute 28 | and/or modify the software. 29 | 30 | A secondary benefit of defending all users' freedom is that 31 | improvements made in alternate versions of the program, if they 32 | receive widespread use, become available for other developers to 33 | incorporate. Many developers of free software are heartened and 34 | encouraged by the resulting cooperation. However, in the case of 35 | software used on network servers, this result may fail to come about. 36 | The GNU General Public License permits making a modified version and 37 | letting the public access it on a server without ever releasing its 38 | source code to the public. 39 | 40 | The GNU Affero General Public License is designed specifically to 41 | ensure that, in such cases, the modified source code becomes available 42 | to the community. It requires the operator of a network server to 43 | provide the source code of the modified version running there to the 44 | users of that server. Therefore, public use of a modified version, on 45 | a publicly accessible server, gives the public access to the source 46 | code of the modified version. 47 | 48 | An older license, called the Affero General Public License and 49 | published by Affero, was designed to accomplish similar goals. This is 50 | a different license, not a version of the Affero GPL, but Affero has 51 | released a new version of the Affero GPL which permits relicensing under 52 | this license. 53 | 54 | The precise terms and conditions for copying, distribution and 55 | modification follow. 56 | 57 | TERMS AND CONDITIONS 58 | 59 | 0. Definitions. 60 | 61 | "This License" refers to version 3 of the GNU Affero General Public License. 62 | 63 | "Copyright" also means copyright-like laws that apply to other kinds of 64 | works, such as semiconductor masks. 65 | 66 | "The Program" refers to any copyrightable work licensed under this 67 | License. Each licensee is addressed as "you". "Licensees" and 68 | "recipients" may be individuals or organizations. 69 | 70 | To "modify" a work means to copy from or adapt all or part of the work 71 | in a fashion requiring copyright permission, other than the making of an 72 | exact copy. The resulting work is called a "modified version" of the 73 | earlier work or a work "based on" the earlier work. 74 | 75 | A "covered work" means either the unmodified Program or a work based 76 | on the Program. 77 | 78 | To "propagate" a work means to do anything with it that, without 79 | permission, would make you directly or secondarily liable for 80 | infringement under applicable copyright law, except executing it on a 81 | computer or modifying a private copy. Propagation includes copying, 82 | distribution (with or without modification), making available to the 83 | public, and in some countries other activities as well. 84 | 85 | To "convey" a work means any kind of propagation that enables other 86 | parties to make or receive copies. Mere interaction with a user through 87 | a computer network, with no transfer of a copy, is not conveying. 88 | 89 | An interactive user interface displays "Appropriate Legal Notices" 90 | to the extent that it includes a convenient and prominently visible 91 | feature that (1) displays an appropriate copyright notice, and (2) 92 | tells the user that there is no warranty for the work (except to the 93 | extent that warranties are provided), that licensees may convey the 94 | work under this License, and how to view a copy of this License. If 95 | the interface presents a list of user commands or options, such as a 96 | menu, a prominent item in the list meets this criterion. 97 | 98 | 1. Source Code. 99 | 100 | The "source code" for a work means the preferred form of the work 101 | for making modifications to it. "Object code" means any non-source 102 | form of a work. 103 | 104 | A "Standard Interface" means an interface that either is an official 105 | standard defined by a recognized standards body, or, in the case of 106 | interfaces specified for a particular programming language, one that 107 | is widely used among developers working in that language. 108 | 109 | The "System Libraries" of an executable work include anything, other 110 | than the work as a whole, that (a) is included in the normal form of 111 | packaging a Major Component, but which is not part of that Major 112 | Component, and (b) serves only to enable use of the work with that 113 | Major Component, or to implement a Standard Interface for which an 114 | implementation is available to the public in source code form. A 115 | "Major Component", in this context, means a major essential component 116 | (kernel, window system, and so on) of the specific operating system 117 | (if any) on which the executable work runs, or a compiler used to 118 | produce the work, or an object code interpreter used to run it. 119 | 120 | The "Corresponding Source" for a work in object code form means all 121 | the source code needed to generate, install, and (for an executable 122 | work) run the object code and to modify the work, including scripts to 123 | control those activities. However, it does not include the work's 124 | System Libraries, or general-purpose tools or generally available free 125 | programs which are used unmodified in performing those activities but 126 | which are not part of the work. For example, Corresponding Source 127 | includes interface definition files associated with source files for 128 | the work, and the source code for shared libraries and dynamically 129 | linked subprograms that the work is specifically designed to require, 130 | such as by intimate data communication or control flow between those 131 | subprograms and other parts of the work. 132 | 133 | The Corresponding Source need not include anything that users 134 | can regenerate automatically from other parts of the Corresponding 135 | Source. 136 | 137 | The Corresponding Source for a work in source code form is that 138 | same work. 139 | 140 | 2. Basic Permissions. 141 | 142 | All rights granted under this License are granted for the term of 143 | copyright on the Program, and are irrevocable provided the stated 144 | conditions are met. This License explicitly affirms your unlimited 145 | permission to run the unmodified Program. The output from running a 146 | covered work is covered by this License only if the output, given its 147 | content, constitutes a covered work. This License acknowledges your 148 | rights of fair use or other equivalent, as provided by copyright law. 149 | 150 | You may make, run and propagate covered works that you do not 151 | convey, without conditions so long as your license otherwise remains 152 | in force. You may convey covered works to others for the sole purpose 153 | of having them make modifications exclusively for you, or provide you 154 | with facilities for running those works, provided that you comply with 155 | the terms of this License in conveying all material for which you do 156 | not control copyright. Those thus making or running the covered works 157 | for you must do so exclusively on your behalf, under your direction 158 | and control, on terms that prohibit them from making any copies of 159 | your copyrighted material outside their relationship with you. 160 | 161 | Conveying under any other circumstances is permitted solely under 162 | the conditions stated below. Sublicensing is not allowed; section 10 163 | makes it unnecessary. 164 | 165 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 166 | 167 | No covered work shall be deemed part of an effective technological 168 | measure under any applicable law fulfilling obligations under article 169 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 170 | similar laws prohibiting or restricting circumvention of such 171 | measures. 172 | 173 | When you convey a covered work, you waive any legal power to forbid 174 | circumvention of technological measures to the extent such circumvention 175 | is effected by exercising rights under this License with respect to 176 | the covered work, and you disclaim any intention to limit operation or 177 | modification of the work as a means of enforcing, against the work's 178 | users, your or third parties' legal rights to forbid circumvention of 179 | technological measures. 180 | 181 | 4. Conveying Verbatim Copies. 182 | 183 | You may convey verbatim copies of the Program's source code as you 184 | receive it, in any medium, provided that you conspicuously and 185 | appropriately publish on each copy an appropriate copyright notice; 186 | keep intact all notices stating that this License and any 187 | non-permissive terms added in accord with section 7 apply to the code; 188 | keep intact all notices of the absence of any warranty; and give all 189 | recipients a copy of this License along with the Program. 190 | 191 | You may charge any price or no price for each copy that you convey, 192 | and you may offer support or warranty protection for a fee. 193 | 194 | 5. Conveying Modified Source Versions. 195 | 196 | You may convey a work based on the Program, or the modifications to 197 | produce it from the Program, in the form of source code under the 198 | terms of section 4, provided that you also meet all of these conditions: 199 | 200 | a) The work must carry prominent notices stating that you modified 201 | it, and giving a relevant date. 202 | 203 | b) The work must carry prominent notices stating that it is 204 | released under this License and any conditions added under section 205 | 7. This requirement modifies the requirement in section 4 to 206 | "keep intact all notices". 207 | 208 | c) You must license the entire work, as a whole, under this 209 | License to anyone who comes into possession of a copy. This 210 | License will therefore apply, along with any applicable section 7 211 | additional terms, to the whole of the work, and all its parts, 212 | regardless of how they are packaged. This License gives no 213 | permission to license the work in any other way, but it does not 214 | invalidate such permission if you have separately received it. 215 | 216 | d) If the work has interactive user interfaces, each must display 217 | Appropriate Legal Notices; however, if the Program has interactive 218 | interfaces that do not display Appropriate Legal Notices, your 219 | work need not make them do so. 220 | 221 | A compilation of a covered work with other separate and independent 222 | works, which are not by their nature extensions of the covered work, 223 | and which are not combined with it such as to form a larger program, 224 | in or on a volume of a storage or distribution medium, is called an 225 | "aggregate" if the compilation and its resulting copyright are not 226 | used to limit the access or legal rights of the compilation's users 227 | beyond what the individual works permit. Inclusion of a covered work 228 | in an aggregate does not cause this License to apply to the other 229 | parts of the aggregate. 230 | 231 | 6. Conveying Non-Source Forms. 232 | 233 | You may convey a covered work in object code form under the terms 234 | of sections 4 and 5, provided that you also convey the 235 | machine-readable Corresponding Source under the terms of this License, 236 | in one of these ways: 237 | 238 | a) Convey the object code in, or embodied in, a physical product 239 | (including a physical distribution medium), accompanied by the 240 | Corresponding Source fixed on a durable physical medium 241 | customarily used for software interchange. 242 | 243 | b) Convey the object code in, or embodied in, a physical product 244 | (including a physical distribution medium), accompanied by a 245 | written offer, valid for at least three years and valid for as 246 | long as you offer spare parts or customer support for that product 247 | model, to give anyone who possesses the object code either (1) a 248 | copy of the Corresponding Source for all the software in the 249 | product that is covered by this License, on a durable physical 250 | medium customarily used for software interchange, for a price no 251 | more than your reasonable cost of physically performing this 252 | conveying of source, or (2) access to copy the 253 | Corresponding Source from a network server at no charge. 254 | 255 | c) Convey individual copies of the object code with a copy of the 256 | written offer to provide the Corresponding Source. This 257 | alternative is allowed only occasionally and noncommercially, and 258 | only if you received the object code with such an offer, in accord 259 | with subsection 6b. 260 | 261 | d) Convey the object code by offering access from a designated 262 | place (gratis or for a charge), and offer equivalent access to the 263 | Corresponding Source in the same way through the same place at no 264 | further charge. You need not require recipients to copy the 265 | Corresponding Source along with the object code. If the place to 266 | copy the object code is a network server, the Corresponding Source 267 | may be on a different server (operated by you or a third party) 268 | that supports equivalent copying facilities, provided you maintain 269 | clear directions next to the object code saying where to find the 270 | Corresponding Source. Regardless of what server hosts the 271 | Corresponding Source, you remain obligated to ensure that it is 272 | available for as long as needed to satisfy these requirements. 273 | 274 | e) Convey the object code using peer-to-peer transmission, provided 275 | you inform other peers where the object code and Corresponding 276 | Source of the work are being offered to the general public at no 277 | charge under subsection 6d. 278 | 279 | A separable portion of the object code, whose source code is excluded 280 | from the Corresponding Source as a System Library, need not be 281 | included in conveying the object code work. 282 | 283 | A "User Product" is either (1) a "consumer product", which means any 284 | tangible personal property which is normally used for personal, family, 285 | or household purposes, or (2) anything designed or sold for incorporation 286 | into a dwelling. In determining whether a product is a consumer product, 287 | doubtful cases shall be resolved in favor of coverage. For a particular 288 | product received by a particular user, "normally used" refers to a 289 | typical or common use of that class of product, regardless of the status 290 | of the particular user or of the way in which the particular user 291 | actually uses, or expects or is expected to use, the product. A product 292 | is a consumer product regardless of whether the product has substantial 293 | commercial, industrial or non-consumer uses, unless such uses represent 294 | the only significant mode of use of the product. 295 | 296 | "Installation Information" for a User Product means any methods, 297 | procedures, authorization keys, or other information required to install 298 | and execute modified versions of a covered work in that User Product from 299 | a modified version of its Corresponding Source. The information must 300 | suffice to ensure that the continued functioning of the modified object 301 | code is in no case prevented or interfered with solely because 302 | modification has been made. 303 | 304 | If you convey an object code work under this section in, or with, or 305 | specifically for use in, a User Product, and the conveying occurs as 306 | part of a transaction in which the right of possession and use of the 307 | User Product is transferred to the recipient in perpetuity or for a 308 | fixed term (regardless of how the transaction is characterized), the 309 | Corresponding Source conveyed under this section must be accompanied 310 | by the Installation Information. But this requirement does not apply 311 | if neither you nor any third party retains the ability to install 312 | modified object code on the User Product (for example, the work has 313 | been installed in ROM). 314 | 315 | The requirement to provide Installation Information does not include a 316 | requirement to continue to provide support service, warranty, or updates 317 | for a work that has been modified or installed by the recipient, or for 318 | the User Product in which it has been modified or installed. Access to a 319 | network may be denied when the modification itself materially and 320 | adversely affects the operation of the network or violates the rules and 321 | protocols for communication across the network. 322 | 323 | Corresponding Source conveyed, and Installation Information provided, 324 | in accord with this section must be in a format that is publicly 325 | documented (and with an implementation available to the public in 326 | source code form), and must require no special password or key for 327 | unpacking, reading or copying. 328 | 329 | 7. Additional Terms. 330 | 331 | "Additional permissions" are terms that supplement the terms of this 332 | License by making exceptions from one or more of its conditions. 333 | Additional permissions that are applicable to the entire Program shall 334 | be treated as though they were included in this License, to the extent 335 | that they are valid under applicable law. If additional permissions 336 | apply only to part of the Program, that part may be used separately 337 | under those permissions, but the entire Program remains governed by 338 | this License without regard to the additional permissions. 339 | 340 | When you convey a copy of a covered work, you may at your option 341 | remove any additional permissions from that copy, or from any part of 342 | it. (Additional permissions may be written to require their own 343 | removal in certain cases when you modify the work.) You may place 344 | additional permissions on material, added by you to a covered work, 345 | for which you have or can give appropriate copyright permission. 346 | 347 | Notwithstanding any other provision of this License, for material you 348 | add to a covered work, you may (if authorized by the copyright holders of 349 | that material) supplement the terms of this License with terms: 350 | 351 | a) Disclaiming warranty or limiting liability differently from the 352 | terms of sections 15 and 16 of this License; or 353 | 354 | b) Requiring preservation of specified reasonable legal notices or 355 | author attributions in that material or in the Appropriate Legal 356 | Notices displayed by works containing it; or 357 | 358 | c) Prohibiting misrepresentation of the origin of that material, or 359 | requiring that modified versions of such material be marked in 360 | reasonable ways as different from the original version; or 361 | 362 | d) Limiting the use for publicity purposes of names of licensors or 363 | authors of the material; or 364 | 365 | e) Declining to grant rights under trademark law for use of some 366 | trade names, trademarks, or service marks; or 367 | 368 | f) Requiring indemnification of licensors and authors of that 369 | material by anyone who conveys the material (or modified versions of 370 | it) with contractual assumptions of liability to the recipient, for 371 | any liability that these contractual assumptions directly impose on 372 | those licensors and authors. 373 | 374 | All other non-permissive additional terms are considered "further 375 | restrictions" within the meaning of section 10. If the Program as you 376 | received it, or any part of it, contains a notice stating that it is 377 | governed by this License along with a term that is a further 378 | restriction, you may remove that term. If a license document contains 379 | a further restriction but permits relicensing or conveying under this 380 | License, you may add to a covered work material governed by the terms 381 | of that license document, provided that the further restriction does 382 | not survive such relicensing or conveying. 383 | 384 | If you add terms to a covered work in accord with this section, you 385 | must place, in the relevant source files, a statement of the 386 | additional terms that apply to those files, or a notice indicating 387 | where to find the applicable terms. 388 | 389 | Additional terms, permissive or non-permissive, may be stated in the 390 | form of a separately written license, or stated as exceptions; 391 | the above requirements apply either way. 392 | 393 | 8. Termination. 394 | 395 | You may not propagate or modify a covered work except as expressly 396 | provided under this License. Any attempt otherwise to propagate or 397 | modify it is void, and will automatically terminate your rights under 398 | this License (including any patent licenses granted under the third 399 | paragraph of section 11). 400 | 401 | However, if you cease all violation of this License, then your 402 | license from a particular copyright holder is reinstated (a) 403 | provisionally, unless and until the copyright holder explicitly and 404 | finally terminates your license, and (b) permanently, if the copyright 405 | holder fails to notify you of the violation by some reasonable means 406 | prior to 60 days after the cessation. 407 | 408 | Moreover, your license from a particular copyright holder is 409 | reinstated permanently if the copyright holder notifies you of the 410 | violation by some reasonable means, this is the first time you have 411 | received notice of violation of this License (for any work) from that 412 | copyright holder, and you cure the violation prior to 30 days after 413 | your receipt of the notice. 414 | 415 | Termination of your rights under this section does not terminate the 416 | licenses of parties who have received copies or rights from you under 417 | this License. If your rights have been terminated and not permanently 418 | reinstated, you do not qualify to receive new licenses for the same 419 | material under section 10. 420 | 421 | 9. Acceptance Not Required for Having Copies. 422 | 423 | You are not required to accept this License in order to receive or 424 | run a copy of the Program. Ancillary propagation of a covered work 425 | occurring solely as a consequence of using peer-to-peer transmission 426 | to receive a copy likewise does not require acceptance. However, 427 | nothing other than this License grants you permission to propagate or 428 | modify any covered work. These actions infringe copyright if you do 429 | not accept this License. Therefore, by modifying or propagating a 430 | covered work, you indicate your acceptance of this License to do so. 431 | 432 | 10. Automatic Licensing of Downstream Recipients. 433 | 434 | Each time you convey a covered work, the recipient automatically 435 | receives a license from the original licensors, to run, modify and 436 | propagate that work, subject to this License. You are not responsible 437 | for enforcing compliance by third parties with this License. 438 | 439 | An "entity transaction" is a transaction transferring control of an 440 | organization, or substantially all assets of one, or subdividing an 441 | organization, or merging organizations. If propagation of a covered 442 | work results from an entity transaction, each party to that 443 | transaction who receives a copy of the work also receives whatever 444 | licenses to the work the party's predecessor in interest had or could 445 | give under the previous paragraph, plus a right to possession of the 446 | Corresponding Source of the work from the predecessor in interest, if 447 | the predecessor has it or can get it with reasonable efforts. 448 | 449 | You may not impose any further restrictions on the exercise of the 450 | rights granted or affirmed under this License. For example, you may 451 | not impose a license fee, royalty, or other charge for exercise of 452 | rights granted under this License, and you may not initiate litigation 453 | (including a cross-claim or counterclaim in a lawsuit) alleging that 454 | any patent claim is infringed by making, using, selling, offering for 455 | sale, or importing the Program or any portion of it. 456 | 457 | 11. Patents. 458 | 459 | A "contributor" is a copyright holder who authorizes use under this 460 | License of the Program or a work on which the Program is based. The 461 | work thus licensed is called the contributor's "contributor version". 462 | 463 | A contributor's "essential patent claims" are all patent claims 464 | owned or controlled by the contributor, whether already acquired or 465 | hereafter acquired, that would be infringed by some manner, permitted 466 | by this License, of making, using, or selling its contributor version, 467 | but do not include claims that would be infringed only as a 468 | consequence of further modification of the contributor version. For 469 | purposes of this definition, "control" includes the right to grant 470 | patent sublicenses in a manner consistent with the requirements of 471 | this License. 472 | 473 | Each contributor grants you a non-exclusive, worldwide, royalty-free 474 | patent license under the contributor's essential patent claims, to 475 | make, use, sell, offer for sale, import and otherwise run, modify and 476 | propagate the contents of its contributor version. 477 | 478 | In the following three paragraphs, a "patent license" is any express 479 | agreement or commitment, however denominated, not to enforce a patent 480 | (such as an express permission to practice a patent or covenant not to 481 | sue for patent infringement). To "grant" such a patent license to a 482 | party means to make such an agreement or commitment not to enforce a 483 | patent against the party. 484 | 485 | If you convey a covered work, knowingly relying on a patent license, 486 | and the Corresponding Source of the work is not available for anyone 487 | to copy, free of charge and under the terms of this License, through a 488 | publicly available network server or other readily accessible means, 489 | then you must either (1) cause the Corresponding Source to be so 490 | available, or (2) arrange to deprive yourself of the benefit of the 491 | patent license for this particular work, or (3) arrange, in a manner 492 | consistent with the requirements of this License, to extend the patent 493 | license to downstream recipients. "Knowingly relying" means you have 494 | actual knowledge that, but for the patent license, your conveying the 495 | covered work in a country, or your recipient's use of the covered work 496 | in a country, would infringe one or more identifiable patents in that 497 | country that you have reason to believe are valid. 498 | 499 | If, pursuant to or in connection with a single transaction or 500 | arrangement, you convey, or propagate by procuring conveyance of, a 501 | covered work, and grant a patent license to some of the parties 502 | receiving the covered work authorizing them to use, propagate, modify 503 | or convey a specific copy of the covered work, then the patent license 504 | you grant is automatically extended to all recipients of the covered 505 | work and works based on it. 506 | 507 | A patent license is "discriminatory" if it does not include within 508 | the scope of its coverage, prohibits the exercise of, or is 509 | conditioned on the non-exercise of one or more of the rights that are 510 | specifically granted under this License. You may not convey a covered 511 | work if you are a party to an arrangement with a third party that is 512 | in the business of distributing software, under which you make payment 513 | to the third party based on the extent of your activity of conveying 514 | the work, and under which the third party grants, to any of the 515 | parties who would receive the covered work from you, a discriminatory 516 | patent license (a) in connection with copies of the covered work 517 | conveyed by you (or copies made from those copies), or (b) primarily 518 | for and in connection with specific products or compilations that 519 | contain the covered work, unless you entered into that arrangement, 520 | or that patent license was granted, prior to 28 March 2007. 521 | 522 | Nothing in this License shall be construed as excluding or limiting 523 | any implied license or other defenses to infringement that may 524 | otherwise be available to you under applicable patent law. 525 | 526 | 12. No Surrender of Others' Freedom. 527 | 528 | If conditions are imposed on you (whether by court order, agreement or 529 | otherwise) that contradict the conditions of this License, they do not 530 | excuse you from the conditions of this License. If you cannot convey a 531 | covered work so as to satisfy simultaneously your obligations under this 532 | License and any other pertinent obligations, then as a consequence you may 533 | not convey it at all. For example, if you agree to terms that obligate you 534 | to collect a royalty for further conveying from those to whom you convey 535 | the Program, the only way you could satisfy both those terms and this 536 | License would be to refrain entirely from conveying the Program. 537 | 538 | 13. Remote Network Interaction; Use with the GNU General Public License. 539 | 540 | Notwithstanding any other provision of this License, if you modify the 541 | Program, your modified version must prominently offer all users 542 | interacting with it remotely through a computer network (if your version 543 | supports such interaction) an opportunity to receive the Corresponding 544 | Source of your version by providing access to the Corresponding Source 545 | from a network server at no charge, through some standard or customary 546 | means of facilitating copying of software. This Corresponding Source 547 | shall include the Corresponding Source for any work covered by version 3 548 | of the GNU General Public License that is incorporated pursuant to the 549 | following paragraph. 550 | 551 | Notwithstanding any other provision of this License, you have 552 | permission to link or combine any covered work with a work licensed 553 | under version 3 of the GNU General Public License into a single 554 | combined work, and to convey the resulting work. The terms of this 555 | License will continue to apply to the part which is the covered work, 556 | but the work with which it is combined will remain governed by version 557 | 3 of the GNU General Public License. 558 | 559 | 14. Revised Versions of this License. 560 | 561 | The Free Software Foundation may publish revised and/or new versions of 562 | the GNU Affero General Public License from time to time. Such new versions 563 | will be similar in spirit to the present version, but may differ in detail to 564 | address new problems or concerns. 565 | 566 | Each version is given a distinguishing version number. If the 567 | Program specifies that a certain numbered version of the GNU Affero General 568 | Public License "or any later version" applies to it, you have the 569 | option of following the terms and conditions either of that numbered 570 | version or of any later version published by the Free Software 571 | Foundation. If the Program does not specify a version number of the 572 | GNU Affero General Public License, you may choose any version ever published 573 | by the Free Software Foundation. 574 | 575 | If the Program specifies that a proxy can decide which future 576 | versions of the GNU Affero General Public License can be used, that proxy's 577 | public statement of acceptance of a version permanently authorizes you 578 | to choose that version for the Program. 579 | 580 | Later license versions may give you additional or different 581 | permissions. However, no additional obligations are imposed on any 582 | author or copyright holder as a result of your choosing to follow a 583 | later version. 584 | 585 | 15. Disclaimer of Warranty. 586 | 587 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 588 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 589 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 590 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 591 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 592 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 593 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 594 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 595 | 596 | 16. Limitation of Liability. 597 | 598 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 599 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 600 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 601 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 602 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 603 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 604 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 605 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 606 | SUCH DAMAGES. 607 | 608 | 17. Interpretation of Sections 15 and 16. 609 | 610 | If the disclaimer of warranty and limitation of liability provided 611 | above cannot be given local legal effect according to their terms, 612 | reviewing courts shall apply local law that most closely approximates 613 | an absolute waiver of all civil liability in connection with the 614 | Program, unless a warranty or assumption of liability accompanies a 615 | copy of the Program in return for a fee. 616 | 617 | END OF TERMS AND CONDITIONS 618 | 619 | How to Apply These Terms to Your New Programs 620 | 621 | If you develop a new program, and you want it to be of the greatest 622 | possible use to the public, the best way to achieve this is to make it 623 | free software which everyone can redistribute and change under these terms. 624 | 625 | To do so, attach the following notices to the program. It is safest 626 | to attach them to the start of each source file to most effectively 627 | state the exclusion of warranty; and each file should have at least 628 | the "copyright" line and a pointer to where the full notice is found. 629 | 630 | 631 | Copyright (C) 632 | 633 | This program is free software: you can redistribute it and/or modify 634 | it under the terms of the GNU Affero General Public License as published 635 | by the Free Software Foundation, either version 3 of the License, or 636 | (at your option) any later version. 637 | 638 | This program is distributed in the hope that it will be useful, 639 | but WITHOUT ANY WARRANTY; without even the implied warranty of 640 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 641 | GNU Affero General Public License for more details. 642 | 643 | You should have received a copy of the GNU Affero General Public License 644 | along with this program. If not, see . 645 | 646 | Also add information on how to contact you by electronic and paper mail. 647 | 648 | If your software can interact with users remotely through a computer 649 | network, you should also make sure that it provides a way for users to 650 | get its source. For example, if your program is a web application, its 651 | interface could display a "Source" link that leads users to an archive 652 | of the code. There are many ways you could offer source, and different 653 | solutions will be better for different programs; see section 13 for the 654 | specific requirements. 655 | 656 | You should also get your employer (if you work as a programmer) or school, 657 | if any, to sign a "copyright disclaimer" for the program, if necessary. 658 | For more information on this, and how to apply and follow the GNU AGPL, see 659 | . 660 | --------------------------------------------------------------------------------