-
-
Notifications
You must be signed in to change notification settings - Fork 339
Expand file tree
/
Copy pathsetCustomHtml.ts
More file actions
220 lines (195 loc) · 6.84 KB
/
setCustomHtml.ts
File metadata and controls
220 lines (195 loc) · 6.84 KB
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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
import { ISentence } from '@/Core/controller/scene/sceneInterface';
import { IPerform } from '@/Core/Modules/perform/performInterface';
import { webgalStore } from '@/store/store';
import { stageActions } from '@/store/stageReducer';
import React from 'react';
// 工具函数:将css字符串转为对象,并返回 feature 字段
function parseCssString(css: string): { styleObj: Record<string, string>; feature?: string } {
const styleObj: Record<string, string> = {};
let feature: string | undefined;
css
.replace(/[{}]/g, '')
.split(',')
.map((s) => s.trim())
.filter(Boolean)
.forEach((item) => {
const [key, value] = item.split(':').map((s) => s.trim());
if (key && value) {
if (key === 'feature') {
feature = value;
} else {
// 驼峰化
const camelKey = key.replace(/-([a-z])/g, (_, c) => c.toUpperCase());
styleObj[camelKey] = value;
}
}
});
return { styleObj, feature };
}
// 解析HTML元素,提取标签名、属性和内容
interface ParsedElement {
tagName: string;
attributes: Record<string, string>;
innerHTML: string;
children: ParsedElement[];
selfClosing: boolean; // 标记是否为自闭合标签
}
// 自动添加绝对定位
function autoAddPositionAbsolute(style: string): string {
// 只要有 left/top/width/height 且没有 position,就加上
if (!/position\s*:/.test(style) && /(left\s*:|top\s*:|right\s*:|bottom\s*:|width\s*:|height\s*:)/.test(style)) {
// 逗号分隔
return `position: absolute,pointer-events: none, ${style}`;
}
return style;
}
// 将单个解析后的元素转换为带样式的HTML字符串
// 支持返回 feature 字段
function convertElementToStyledHtml(element: ParsedElement): { html: string; feature?: string } {
let feature: string | undefined;
let html = `<${element.tagName}`;
// 处理style属性
if (element.attributes.style) {
element.attributes.style = autoAddPositionAbsolute(element.attributes.style);
const { styleObj, feature: f } = parseCssString(element.attributes.style);
if (f && !feature) feature = f;
const cssString = Object.entries(styleObj)
.map(([key, value]) => {
const cssKey = key.replace(/([A-Z])/g, '-$1').toLowerCase();
return `${cssKey}: ${value}`;
})
.join('; ');
html += ` style="${cssString}"`;
}
// 处理其他属性,但过滤掉所有on*事件处理器以防止XSS
Object.entries(element.attributes).forEach(([key, value]) => {
// 禁止所有on*事件处理器属性,防止XSS攻击
if (key !== 'style' && !key.startsWith('on')) {
html += ` ${key}="${value}"`;
}
});
// 处理自闭合标签
if (element.selfClosing) {
html += '/>';
} else {
html += '>';
// 添加子元素
if (element.children.length > 0) {
// 递归处理所有子元素
const childResults = element.children.map((child) => convertElementToStyledHtml(child));
html += childResults
.map((result) => {
if (result.feature && !feature) feature = result.feature;
return result.html;
})
.join('');
} else if (element.innerHTML) {
html += element.innerHTML;
}
html += `</${element.tagName}>`;
}
return { html, feature };
}
// 解析HTML字符串,提取所有元素及其样式
function parseHtmlWithStyles(htmlInput: string): ParsedElement[] {
// 使用DOMParser解析HTML字符串,更加安全和可靠
const parser = new DOMParser();
const doc = parser.parseFromString(htmlInput, 'text/html');
// 递归遍历节点并转换为ParsedElement结构
function parseNode(node: Node): ParsedElement[] {
const elements: ParsedElement[] = [];
// 遍历所有子节点
node.childNodes.forEach((child) => {
if (child.nodeType === Node.ELEMENT_NODE) {
const element = child as HTMLElement;
const tagName = element.tagName.toLowerCase();
const attributes: Record<string, string> = {};
// 提取所有属性
for (const attr of element.attributes) {
attributes[attr.name] = attr.value;
}
// 判断是否为自闭合标签
const selfClosingTags = [
'img',
'br',
'hr',
'input',
'link',
'meta',
'area',
'base',
'col',
'embed',
'source',
'track',
'wbr',
];
const isSelfClosing =
selfClosingTags.includes(tagName) || (element.childNodes.length === 0 && !element.textContent);
// 递归处理子元素(如果不是自闭合标签)
const children = isSelfClosing ? [] : parseNode(element);
// 获取innerHTML内容
let innerHTML = '';
if (children.length === 0 && !isSelfClosing) {
innerHTML = element.innerHTML;
}
elements.push({
tagName,
attributes,
innerHTML,
children,
selfClosing: isSelfClosing,
});
}
});
return elements;
}
// 从body开始解析(因为DOMParser会自动包装HTML)
return parseNode(doc.body);
}
export const setCustomHtml = (sentence: ISentence): IPerform => {
const removeMatch = sentence.content.match(/^remove\((\d+)\)$/);
if (removeMatch) {
const idx = parseInt(removeMatch[1], 10) - 1 || 0;
webgalStore.dispatch(stageActions.removeCustomHtml(idx));
return {
performName: 'none',
duration: 0,
isHoldOn: false,
stopFunction: () => {},
blockingNext: () => false,
blockingAuto: () => true,
stopTimeout: undefined,
};
}
// 直接解析HTML中的样式(不再支持<div>content</div> {css}格式)
const html = sentence.content.trim();
// 解析HTML并处理内联样式
const elements = parseHtmlWithStyles(html);
// 为每个元素单独处理和分发action
elements.forEach((element) => {
const { html: styledHtml, feature } = convertElementToStyledHtml(element);
// 直接从元素的attributes中提取样式,避免再次解析HTML字符串
let style: React.CSSProperties = { position: 'absolute' };
if (element.attributes.style) {
const processedStyle = autoAddPositionAbsolute(element.attributes.style);
const { styleObj } = parseCssString(processedStyle);
// 将styleObj转换为React.CSSProperties
Object.keys(styleObj).forEach((key) => {
// 使用类型断言来避免TypeScript错误
(style as any)[key] = styleObj[key];
});
}
// 添加到状态管理,带 feature 字段和style对象
webgalStore.dispatch(stageActions.addCustomHtml({ html: styledHtml, _feature: feature, style }));
});
return {
performName: 'none',
duration: 0,
isHoldOn: false,
stopFunction: () => {},
blockingNext: () => false,
blockingAuto: () => true,
stopTimeout: undefined,
};
};