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 |
30 |
31 | {title}
32 |
33 | {text}
34 |
35 |
36 |
37 |
38 | {#if type === "checkbox"}
39 |
40 |
47 | {:else if type === "input"}
48 |
49 |
56 | {:else if type === "button"}
57 |
58 |
63 | {settingValue}
64 |
65 | {:else if type === "select"}
66 |
67 |
73 | {#each Object.entries(options) as [value, text]}
74 | {text}
75 | {/each}
76 |
77 | {:else if type == "slider"}
78 |
79 |
80 |
90 |
91 | {/if}
92 |
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 |
67 | {:else if type === 'number'}
68 |
78 | {:else if type === 'button'}
79 |
80 |
89 | {button.label}
90 |
91 | {:else if type === 'select'}
92 |
93 |
102 | {#each Object.entries(options) as [value, text]}
103 | {text}
104 | {/each}
105 |
106 | {:else if type == 'slider'}
107 |
108 |
109 |
121 |
122 | {/if}
123 |
--------------------------------------------------------------------------------
/CHANGELOG.md:
--------------------------------------------------------------------------------
1 | # Changelog
2 |
3 | ## v0.3.5 2024-04-30
4 |
5 | * [Add `direction` to plugin method `Setting.addItem`](https://github.com/siyuan-note/siyuan/issues/11183)
6 |
7 |
8 | ## 0.3.4 2024-02-20
9 |
10 | * [Add plugin event bus `click-flashcard-action`](https://github.com/siyuan-note/siyuan/issues/10318)
11 |
12 | ## 0.3.3 2024-01-24
13 |
14 | * Update dock icon class
15 |
16 | ## 0.3.2 2024-01-09
17 |
18 | * [Add plugin `protyleOptions`](https://github.com/siyuan-note/siyuan/issues/10090)
19 | * [Add plugin api `uninstall`](https://github.com/siyuan-note/siyuan/issues/10063)
20 | * [Add plugin method `updateCards`](https://github.com/siyuan-note/siyuan/issues/10065)
21 | * [Add plugin function `lockScreen`](https://github.com/siyuan-note/siyuan/issues/10063)
22 | * [Add plugin event bus `lock-screen`](https://github.com/siyuan-note/siyuan/pull/9967)
23 | * [Add plugin event bus `open-menu-inbox`](https://github.com/siyuan-note/siyuan/pull/9967)
24 |
25 |
26 | ## 0.3.1 2023-12-06
27 |
28 | * [Support `Dock Plugin` and `Command Palette` on mobile](https://github.com/siyuan-note/siyuan/issues/9926)
29 |
30 | ## 0.3.0 2023-12-05
31 |
32 | * Upgrade Siyuan to 0.9.0
33 | * Support more platforms
34 |
35 | ## 0.2.9 2023-11-28
36 |
37 | * [Add plugin method `openMobileFileById`](https://github.com/siyuan-note/siyuan/issues/9738)
38 |
39 |
40 | ## 0.2.8 2023-11-15
41 |
42 | * [`resize` cannot be triggered after dragging to unpin the dock](https://github.com/siyuan-note/siyuan/issues/9640)
43 |
44 | ## 0.2.7 2023-10-31
45 |
46 | * [Export `Constants` to plugin](https://github.com/siyuan-note/siyuan/issues/9555)
47 | * [Add plugin `app.appId`](https://github.com/siyuan-note/siyuan/issues/9538)
48 | * [Add plugin event bus `switch-protyle`](https://github.com/siyuan-note/siyuan/issues/9454)
49 |
50 | ## 0.2.6 2023-10-24
51 |
52 | * [Deprecated `loaded-protyle` use `loaded-protyle-static` instead](https://github.com/siyuan-note/siyuan/issues/9468)
53 |
54 | ## 0.2.5 2023-10-10
55 |
56 | * [Add plugin event bus `open-menu-doctree`](https://github.com/siyuan-note/siyuan/issues/9351)
57 |
58 | ## 0.2.4 2023-09-19
59 |
60 | * Supports use in windows
61 | * [Add plugin function `transaction`](https://github.com/siyuan-note/siyuan/issues/9172)
62 |
63 | ## 0.2.3 2023-09-05
64 |
65 | * [Add plugin function `transaction`](https://github.com/siyuan-note/siyuan/issues/9172)
66 | * [Plugin API add openWindow and command.globalCallback](https://github.com/siyuan-note/siyuan/issues/9032)
67 |
68 | ## 0.2.2 2023-08-29
69 |
70 | * [Add plugin event bus `destroy-protyle`](https://github.com/siyuan-note/siyuan/issues/9033)
71 | * [Add plugin event bus `loaded-protyle-dynamic`](https://github.com/siyuan-note/siyuan/issues/9021)
72 |
73 | ## 0.2.1 2023-08-21
74 |
75 | * [Plugin API add getOpenedTab method](https://github.com/siyuan-note/siyuan/issues/9002)
76 | * [Plugin API custom.fn => custom.id in openTab](https://github.com/siyuan-note/siyuan/issues/8944)
77 |
78 | ## 0.2.0 2023-08-15
79 |
80 | * [Add plugin event bus `open-siyuan-url-plugin` and `open-siyuan-url-block`](https://github.com/siyuan-note/siyuan/pull/8927)
81 |
82 |
83 | ## 0.1.12 2023-08-01
84 |
85 | * Upgrade siyuan to 0.7.9
86 |
87 | ## 0.1.11
88 |
89 | * [Add `input-search` event bus to plugins](https://github.com/siyuan-note/siyuan/issues/8725)
90 |
91 |
92 | ## 0.1.10
93 |
94 | * [Add `bind this` example for eventBus in plugins](https://github.com/siyuan-note/siyuan/issues/8668)
95 | * [Add `open-menu-breadcrumbmore` event bus to plugins](https://github.com/siyuan-note/siyuan/issues/8666)
96 |
97 | ## 0.1.9
98 |
99 | * [Add `open-menu-xxx` event bus for plugins ](https://github.com/siyuan-note/siyuan/issues/8617)
100 |
101 | ## 0.1.8
102 |
103 | * [Add protyleSlash to the plugin](https://github.com/siyuan-note/siyuan/issues/8599)
104 | * [Add plugin API protyle](https://github.com/siyuan-note/siyuan/issues/8445)
105 |
106 | ## 0.1.7
107 |
108 | * [Support build js and json](https://github.com/siyuan-note/plugin-sample/pull/8)
109 |
110 | ## 0.1.6
111 |
112 | * add `fetchPost` example
113 |
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | const path = require("path");
2 | const fs = require("fs");
3 | const webpack = require("webpack");
4 | const { EsbuildPlugin } = require("esbuild-loader");
5 | const MiniCssExtractPlugin = require("mini-css-extract-plugin");
6 | const CopyPlugin = require("copy-webpack-plugin");
7 | const ZipPlugin = require("zip-webpack-plugin");
8 |
9 | module.exports = (env, argv) => {
10 | const isPro = argv.mode === "production";
11 | const plugins = [
12 | new MiniCssExtractPlugin({
13 | filename: isPro ? "dist/index.css" : "index.css",
14 | })
15 | ];
16 | let entry = {
17 | "index": "./src/index.ts",
18 | };
19 | if (isPro) {
20 | entry = {
21 | "dist/index": "./src/index.ts",
22 | };
23 | plugins.push(new webpack.BannerPlugin({
24 | banner: () => {
25 | return fs.readFileSync("LICENSE").toString();
26 | },
27 | }));
28 | plugins.push(new CopyPlugin({
29 | // 用途:把文件放在dist,用来打包
30 | patterns: [
31 | { from: "preview.png", to: "./dist/" },
32 | { from: "icon.png", to: "./dist/" },
33 | { from: "README*.md", to: "./dist/" },
34 | { from: "plugin.json", to: "./dist/" },
35 | { from: "src/i18n/", to: "./dist/i18n/" },
36 | { from: "src/index.css", to: "./dist/" }, // Add this line
37 | { from: "src/assets/", to: "./dist/assets/" } // Add this line
38 | ],
39 | }));
40 | plugins.push(new ZipPlugin({
41 | filename: "package.zip",
42 | algorithm: "gzip",
43 | include: [/dist/],
44 | pathMapper: (assetPath) => {
45 | return assetPath.replace("dist/", "");
46 | },
47 | }));
48 | } else {
49 | plugins.push(new CopyPlugin({
50 | // 用途:run dev的时候放在当前目录,可以直接运行
51 | patterns: [
52 | { from: "src/i18n/", to: "./i18n/" },
53 | { from: "src/index.css", to: "./" }, // Add this line
54 | { from: "src/assets/", to: "./assets/" } // Add this line
55 | ],
56 | }));
57 | }
58 | return {
59 | mode: argv.mode || "development",
60 | watch: !isPro,
61 | devtool: isPro ? false : "eval",
62 | output: {
63 | filename: "[name].js",
64 | path: path.resolve(__dirname),
65 | libraryTarget: "commonjs2",
66 | library: {
67 | type: "commonjs2",
68 | },
69 | },
70 | externals: {
71 | siyuan: "siyuan",
72 | },
73 | entry,
74 | optimization: {
75 | minimize: true,
76 | minimizer: [
77 | new EsbuildPlugin(),
78 | ],
79 | },
80 | resolve: {
81 | extensions: [".ts", ".scss", ".js", ".json"],
82 | },
83 | module: {
84 | rules: [
85 | {
86 | test: /\.ts(x?)$/,
87 | include: [path.resolve(__dirname, "src")],
88 | use: [
89 | {
90 | loader: "esbuild-loader",
91 | options: {
92 | target: "es6",
93 | }
94 | },
95 | ],
96 | },
97 | {
98 | test: /\.scss$/,
99 | include: [path.resolve(__dirname, "src")],
100 | use: [
101 | MiniCssExtractPlugin.loader,
102 | {
103 | loader: "css-loader", // translates CSS into CommonJS
104 | },
105 | {
106 | loader: "sass-loader", // compiles Sass to CSS
107 | },
108 | ],
109 | }
110 | ],
111 | },
112 | plugins,
113 | };
114 | };
115 |
--------------------------------------------------------------------------------
/src/utils/i18n.ts:
--------------------------------------------------------------------------------
1 | let pluginInstance: any = null;
2 |
3 | // 设置插件实例的引用
4 | export function setPluginInstance(plugin: any) {
5 | pluginInstance = plugin;
6 | }
7 |
8 | /**
9 | * 获取当前语言
10 | */
11 | export function getCurrentLanguage(): string {
12 | if (pluginInstance && pluginInstance.i18n) {
13 | // 从插件实例获取当前语言
14 | return pluginInstance.i18n.getCurrentLanguage?.() || 'zh_CN';
15 | }
16 |
17 | // 尝试从全局获取
18 | try {
19 | const { i18n } = require("siyuan");
20 | return i18n.getCurrentLanguage?.() || 'zh_CN';
21 | } catch (error) {
22 | console.warn('无法获取当前语言:', error);
23 | return 'zh_CN';
24 | }
25 | }
26 |
27 | /**
28 | * 翻译函数
29 | */
30 | export function t(key: string, params?: { [key: string]: string }): string {
31 | // 首先尝试从插件实例获取i18n数据
32 | let i18nData = null;
33 |
34 | if (pluginInstance && pluginInstance.i18n) {
35 | i18nData = pluginInstance.i18n;
36 | }
37 |
38 | // 如果插件实例不可用,尝试从全局获取
39 | if (!i18nData) {
40 | try {
41 | const { i18n } = require("siyuan");
42 | i18nData = i18n;
43 | } catch (error) {
44 | console.warn('无法获取i18n对象:', error);
45 | }
46 | }
47 |
48 | // 如果仍然没有i18n数据,使用key作为后备
49 | if (!i18nData || typeof i18nData !== 'object') {
50 | console.warn('i18n数据不可用,使用key作为后备:', key);
51 | return key;
52 | }
53 |
54 | // 支持嵌套键访问(如 settings.template.description)
55 | let text = i18nData;
56 | const keyParts = key.split('.');
57 |
58 | for (const part of keyParts) {
59 | if (text && typeof text === 'object' && part in text) {
60 | text = text[part];
61 | } else {
62 | text = undefined;
63 | break;
64 | }
65 | }
66 |
67 | // 如果没有找到对应的翻译文本,使用key作为后备
68 | if (typeof text !== 'string') {
69 | console.warn('未找到i18n键:', key);
70 | text = key;
71 | }
72 |
73 | // 处理参数替换
74 | if (params && typeof text === 'string') {
75 | Object.keys(params).forEach(param => {
76 | text = text.replace(new RegExp(`\\$\\{${param}\\}`, 'g'), params[param]);
77 | });
78 | }
79 |
80 | return text;
81 | }
82 |
83 | /**
84 | * 检查是否存在翻译键
85 | */
86 | export function hasTranslation(key: string): boolean {
87 | let i18nData = null;
88 |
89 | if (pluginInstance && pluginInstance.i18n) {
90 | i18nData = pluginInstance.i18n;
91 | }
92 |
93 | if (!i18nData) {
94 | try {
95 | const { i18n } = require("siyuan");
96 | i18nData = i18n;
97 | } catch (error) {
98 | return false;
99 | }
100 | }
101 |
102 | if (!i18nData) {
103 | return false;
104 | }
105 |
106 | // 支持嵌套键检查
107 | let current = i18nData;
108 | const keyParts = key.split('.');
109 |
110 | for (const part of keyParts) {
111 | if (current && typeof current === 'object' && part in current) {
112 | current = current[part];
113 | } else {
114 | return false;
115 | }
116 | }
117 |
118 | return typeof current === 'string';
119 | }
120 |
121 | /**
122 | * 格式化带参数的翻译文本
123 | */
124 | export function tf(key: string, ...args: any[]): string {
125 | const text = t(key);
126 |
127 | if (args.length === 0) {
128 | return text;
129 | }
130 |
131 | // 支持位置参数替换 {0}, {1}, {2} 等
132 | return text.replace(/\{(\d+)\}/g, (match, index) => {
133 | const argIndex = parseInt(index);
134 | return argIndex < args.length ? String(args[argIndex]) : match;
135 | });
136 | }
137 |
138 | /**
139 | * 多元化翻译(根据数量选择不同的翻译)
140 | */
141 | export function tp(key: string, count: number, params?: { [key: string]: string }): string {
142 | let pluralKey = key;
143 |
144 | // 根据数量选择不同的键
145 | if (count === 0) {
146 | pluralKey = `${key}_zero`;
147 | } else if (count === 1) {
148 | pluralKey = `${key}_one`;
149 | } else {
150 | pluralKey = `${key}_other`;
151 | }
152 |
153 | // 如果复数形式不存在,回退到原始键
154 | if (!hasTranslation(pluralKey)) {
155 | pluralKey = key;
156 | }
157 |
158 | // 添加count参数
159 | const finalParams = { count: count.toString(), ...params };
160 |
161 | return t(pluralKey, finalParams);
162 | }
163 |
--------------------------------------------------------------------------------
/scripts/update_version.js:
--------------------------------------------------------------------------------
1 | // const fs = require('fs');
2 | // const path = require('path');
3 | // const readline = require('readline');
4 | import fs from 'node:fs';
5 | import path from 'node:path';
6 | import readline from 'node:readline';
7 |
8 | // Utility to read JSON file
9 | function readJsonFile(filePath) {
10 | return new Promise((resolve, reject) => {
11 | fs.readFile(filePath, 'utf8', (err, data) => {
12 | if (err) return reject(err);
13 | try {
14 | const jsonData = JSON.parse(data);
15 | resolve(jsonData);
16 | } catch (e) {
17 | reject(e);
18 | }
19 | });
20 | });
21 | }
22 |
23 | // Utility to write JSON file
24 | function writeJsonFile(filePath, jsonData) {
25 | return new Promise((resolve, reject) => {
26 | fs.writeFile(filePath, JSON.stringify(jsonData, null, 2), 'utf8', (err) => {
27 | if (err) return reject(err);
28 | resolve();
29 | });
30 | });
31 | }
32 |
33 | // Utility to prompt the user for input
34 | function promptUser(query) {
35 | const rl = readline.createInterface({
36 | input: process.stdin,
37 | output: process.stdout
38 | });
39 | return new Promise((resolve) => rl.question(query, (answer) => {
40 | rl.close();
41 | resolve(answer);
42 | }));
43 | }
44 |
45 | // Function to parse the version string
46 | function parseVersion(version) {
47 | const [major, minor, patch] = version.split('.').map(Number);
48 | return { major, minor, patch };
49 | }
50 |
51 | // Function to auto-increment version parts
52 | function incrementVersion(version, type) {
53 | let { major, minor, patch } = parseVersion(version);
54 |
55 | switch (type) {
56 | case 'major':
57 | major++;
58 | minor = 0;
59 | patch = 0;
60 | break;
61 | case 'minor':
62 | minor++;
63 | patch = 0;
64 | break;
65 | case 'patch':
66 | patch++;
67 | break;
68 | default:
69 | break;
70 | }
71 |
72 | return `${major}.${minor}.${patch}`;
73 | }
74 |
75 | // Main script
76 | (async function () {
77 | try {
78 | const pluginJsonPath = path.join(process.cwd(), 'plugin.json');
79 | const packageJsonPath = path.join(process.cwd(), 'package.json');
80 |
81 | // Read both JSON files
82 | const pluginData = await readJsonFile(pluginJsonPath);
83 | const packageData = await readJsonFile(packageJsonPath);
84 |
85 | // Get the current version from both files (assuming both have the same version)
86 | const currentVersion = pluginData.version || packageData.version;
87 | console.log(`\n🌟 Current version: \x1b[36m${currentVersion}\x1b[0m\n`);
88 |
89 | // Calculate potential new versions for auto-update
90 | const newPatchVersion = incrementVersion(currentVersion, 'patch');
91 | const newMinorVersion = incrementVersion(currentVersion, 'minor');
92 | const newMajorVersion = incrementVersion(currentVersion, 'major');
93 |
94 | // Prompt the user with formatted options
95 | console.log('🔄 How would you like to update the version?\n');
96 | console.log(` 1️⃣ Auto update \x1b[33mpatch\x1b[0m version (new version: \x1b[32m${newPatchVersion}\x1b[0m)`);
97 | console.log(` 2️⃣ Auto update \x1b[33mminor\x1b[0m version (new version: \x1b[32m${newMinorVersion}\x1b[0m)`);
98 | console.log(` 3️⃣ Auto update \x1b[33mmajor\x1b[0m version (new version: \x1b[32m${newMajorVersion}\x1b[0m)`);
99 | console.log(` 4️⃣ Input version \x1b[33mmanually\x1b[0m`);
100 | // Press 0 to skip version update
101 | console.log(' 0️⃣ Quit without updating\n');
102 |
103 | const updateChoice = await promptUser('👉 Please choose (1/2/3/4): ');
104 |
105 | let newVersion;
106 |
107 | switch (updateChoice.trim()) {
108 | case '1':
109 | newVersion = newPatchVersion;
110 | break;
111 | case '2':
112 | newVersion = newMinorVersion;
113 | break;
114 | case '3':
115 | newVersion = newMajorVersion;
116 | break;
117 | case '4':
118 | newVersion = await promptUser('✍️ Please enter the new version (in a.b.c format): ');
119 | break;
120 | case '0':
121 | console.log('\n🛑 Skipping version update.');
122 | return;
123 | default:
124 | console.log('\n❌ Invalid option, no version update.');
125 | return;
126 | }
127 |
128 | // Update the version in both plugin.json and package.json
129 | pluginData.version = newVersion;
130 | packageData.version = newVersion;
131 |
132 | // Write the updated JSON back to files
133 | await writeJsonFile(pluginJsonPath, pluginData);
134 | await writeJsonFile(packageJsonPath, packageData);
135 |
136 | console.log(`\n✅ Version successfully updated to: \x1b[32m${newVersion}\x1b[0m\n`);
137 |
138 | } catch (error) {
139 | console.error('❌ Error:', error);
140 | }
141 | })();
142 |
--------------------------------------------------------------------------------
/src/libs/dialog.ts:
--------------------------------------------------------------------------------
1 | /*
2 | * Copyright (c) 2024 by frostime. All Rights Reserved.
3 | * @Author : frostime
4 | * @Date : 2024-03-23 21:37:33
5 | * @FilePath : /src/libs/dialog.ts
6 | * @LastEditTime : 2024-10-16 14:31:04
7 | * @Description : Kits about dialogs
8 | */
9 | import { Dialog } from "siyuan";
10 | import { type SvelteComponent } from "svelte";
11 |
12 | export const inputDialog = (args: {
13 | title: string, placeholder?: string, defaultText?: string,
14 | confirm?: (text: string) => void, cancel?: () => void,
15 | width?: string, height?: string
16 | }) => {
17 | const dialog = new Dialog({
18 | title: args.title,
19 | content: `
22 |
23 |
${window.siyuan.languages.cancel}
24 |
${window.siyuan.languages.confirm}
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: `
80 |
81 |
${window.siyuan.languages.cancel}
82 |
${window.siyuan.languages.confirm}
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 |
--------------------------------------------------------------------------------