-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.ts
156 lines (143 loc) · 5.18 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { siyuan } from "@llej/js_util";
import { updateBlock } from "~/libs/api";
import { pluginClassName } from "./constant";
import { get_exprBlocks } from "./fn/get_exprBlocks";
import "./index.css";
import type { MergedBlock } from "./type";
import * as recast from "recast";
import { encodeHTML, generateTimestamp } from "~/libs/js_util";
import { SiyuanPlugin } from "~/libs/siyuanPlugin";
const dev = console.log;
declare global {
var expr: Expr;
}
export default class Expr extends SiyuanPlugin {
IntervalId = 0;
/** 主循环的间隔毫秒数 */
intervalMs = 1_000;
/** 控制sql相关 TODO 添加选项配置 */
intervalUpdateSql = siyuan.bindData({
initValue: true,
that: this,
storageName: "intervalUpdateSql.json",
});
/** 只更新这个时间戳以后的表达式 */
updated = siyuan.bindData({
initValue: 0,
that: this,
storageName: "updated.json",
});
/** 为 true 代表正在进行求值运算中 */
evalState = false;
async onload() {
console.log("[expr]", this);
/** 注册Expr实例到全局变量 */
globalThis.expr = this;
this.addUnloadFn(
() =>
//@ts-ignore
delete globalThis.expr,
);
// 切换页签时清空已计算的id数组来实现每次打开自动计算
this.eventBus.on("switch-protyle", () => {
this.evalExprIDs = [];
});
/** 注册求值循环 */
this.IntervalId = setInterval(this.evalAllExpr.bind(this), this.intervalMs);
this.addUnloadFn(() => clearInterval(this.IntervalId));
/** 在 body 上注册插件类名,用于控制样式的开关 */
document.body.classList.add(pluginClassName);
this.addUnloadFn(() => document.body.classList.remove(pluginClassName));
}
/** 对所有表达式进行求值 */
async evalAllExpr() {
if (this.evalState) {
/** 只有上一轮求值计算进行完毕后才会开始新一轮计算 */
return;
}
const exprIDs = (
[...document.querySelectorAll("[custom-expr]")].filter((el) => {
if (!(el instanceof HTMLElement)) {
return false;
}
if (el.dataset.nodeId && this.evalExprIDs.includes(el.dataset.nodeId)) {
// 已经求值过了的不在参加计算
return false;
}
return true;
}) as HTMLElement[]
).map((el) => {
const id = el.dataset.nodeId as string;
return id;
});
// 当配置不根据update字段更新的时候,不进行求值
if (!this.intervalUpdateSql.value() && exprIDs.length === 0) {
return;
}
try {
this.evalState = true;
const exprBlock = await get_exprBlocks(exprIDs);
if (exprBlock && exprBlock.length > 0) {
await Promise.all(exprBlock.map(this.exprEval.bind(this)));
}
} catch (error) {
dev("求值错误", error);
} finally {
this.evalState = false;
}
}
/** 记录计算完成的 id ,不再计算 */
evalExprIDs: string[] = [];
/** 对指定id进行求值 */
async exprEvalByID(block_id: string) {
const blocks = await get_exprBlocks([block_id]);
return this.exprEval(blocks[0]);
}
async exprEval(block: MergedBlock) {
const code = `async ()=>{\n${block.a_value}\n}`;
const ast = recast.parse(code);
const b = recast.types.builders;
// 如果没有 return 则为最后一个表达式添加 return
const body: any[] = ast.program.body[0].expression.body.body;
if (body.find((item) => item.type === "ReturnStatement")) {
} else {
const lastExp = body.pop();
if ((lastExp.type = "ExpressionStatement")) {
body.push(b.returnStatement(lastExp.expression));
}
}
const output = recast.print(ast).code;
let evalValue = await eval(output)();
const updated = generateTimestamp();
if (Number(updated) > this.updated.value()) {
this.updated.set(Number(updated));
}
/** TODO,这里应该要考虑ial中不存在相关字段的情况,需要进行添加而非替换 更新块的update时间戳
* ial = `{: updated="20240604233920" custom-expr="10-11+Math.random()+"2"" custom-expr-value="-0.95897021536132312" id="20240514180539-3zvaoab" style="background-color: var(--b3-font-background4);"} `
*/
let newKramdownAttr = block.ial!;
if (/updated="\d+"/.test(newKramdownAttr)) {
newKramdownAttr = newKramdownAttr.replace(/updated="\d+"/, `updated="${updated}"`);
} else {
newKramdownAttr = newKramdownAttr.replace(/}$/, ` updated="${updated}"`);
}
const evalValue_string = String(evalValue);
if (/custom-expr-value=".*?"/.test(newKramdownAttr)) {
newKramdownAttr = newKramdownAttr.replace(
/custom-expr-value=".*?"/,
`custom-expr-value="${encodeHTML(evalValue_string)}"`,
);
} else {
newKramdownAttr = newKramdownAttr.replace(
/}$/,
` custom-expr-value="${encodeHTML(evalValue_string)}"` + "}",
);
}
// custom-expr-value="-0.56273369360008952"
/** 将求值结果更新到块文本 */
await updateBlock("markdown", String(evalValue_string + "\n" + newKramdownAttr), block.id);
dev("expr eval:", { id: block.id, expr: block.a_value, evalValue });
this.evalExprIDs.push(block.id);
return evalValue;
}
}