8 小时以前 9bad721754fe8bbe2e5f459d0706e0fefac569f3
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
package cn.iocoder.yudao.module.qcreport.engine.render;
 
import cn.iocoder.yudao.module.qcreport.engine.JsValues;
 
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
 
/**
 * GrapesJS 项目数据节点。
 * <p>
 * 只声明渲染需要的字段,直接读原始 Map:{@code components} 既可能是数组也可能是字符串,
 * 用 POJO 反序列化要额外处理联合类型,不如按需取值来得直白,也省一次拷贝。
 */
public final class RenderNode {
 
    private final Map<String, Object> data;
 
    private RenderNode(Map<String, Object> data) {
        this.data = data;
    }
 
    /** 不是对象节点时返回 null(如数组里混入了字符串) */
    @SuppressWarnings("unchecked")
    public static RenderNode of(Object raw) {
        return raw instanceof Map<?, ?> ? new RenderNode((Map<String, Object>) raw) : null;
    }
 
    public String type() {
        return text(data.get("type"));
    }
 
    public String tagName() {
        return text(data.get("tagName"));
    }
 
    /** 只在 content 本身是字符串时返回,与前端 {@code typeof node.content === 'string'} 一致 */
    public String content() {
        return data.get("content") instanceof String content ? content : null;
    }
 
    /** 取一个属性值,取不到返回 null */
    public String attribute(String name) {
        return attributes().get(name);
    }
 
    /** 属性表,值统一成文本 */
    public Map<String, String> attributes() {
        Map<String, String> result = new LinkedHashMap<>();
        if (data.get("attributes") instanceof Map<?, ?> attributes) {
            for (Map.Entry<?, ?> entry : attributes.entrySet()) {
                result.put(String.valueOf(entry.getKey()), JsValues.asText(entry.getValue()));
            }
        }
        return result;
    }
 
    /** 行内样式表,值统一成文本 */
    public Map<String, String> style() {
        Map<String, String> result = new LinkedHashMap<>();
        if (data.get("style") instanceof Map<?, ?> style) {
            for (Map.Entry<?, ?> entry : style.entrySet()) {
                result.put(String.valueOf(entry.getKey()), JsValues.asText(entry.getValue()));
            }
        }
        return result;
    }
 
    /** 子组件;components 是字符串(旧数据/纯文本组件)时返回空列表 */
    public List<RenderNode> children() {
        List<RenderNode> result = new ArrayList<>();
        if (data.get("components") instanceof List<?> components) {
            for (Object raw : components) {
                RenderNode child = of(raw);
                if (child != null) {
                    result.add(child);
                }
            }
        }
        return result;
    }
 
    private static String text(Object value) {
        return value == null ? null : String.valueOf(value);
    }
 
}