feat(editor): robust Vditor init + HTML<->MD handling; fix table rendering, image extraction, save flow
This commit is contained in:
parent
0809c0e7df
commit
2c10b0e34f
Binary file not shown.
|
|
@ -0,0 +1,18 @@
|
||||||
|
# Generated by Django 4.2.7 on 2025-10-18 18:17
|
||||||
|
|
||||||
|
from django.db import migrations, models
|
||||||
|
|
||||||
|
|
||||||
|
class Migration(migrations.Migration):
|
||||||
|
|
||||||
|
dependencies = [
|
||||||
|
('mindmap', '0004_node_html_content'),
|
||||||
|
]
|
||||||
|
|
||||||
|
operations = [
|
||||||
|
migrations.AddField(
|
||||||
|
model_name='node',
|
||||||
|
name='markdown_content',
|
||||||
|
field=models.TextField(blank=True, default=''),
|
||||||
|
),
|
||||||
|
]
|
||||||
|
|
@ -37,6 +37,8 @@ class Node(models.Model):
|
||||||
|
|
||||||
# HTML内容字段
|
# HTML内容字段
|
||||||
html_content = models.TextField(blank=True, default='') # dangerouslySetInnerHTML内容
|
html_content = models.TextField(blank=True, default='') # dangerouslySetInnerHTML内容
|
||||||
|
# Markdown源码(新增)
|
||||||
|
markdown_content = models.TextField(blank=True, default='')
|
||||||
|
|
||||||
created_at = models.DateTimeField(auto_now_add=True) # createDate
|
created_at = models.DateTimeField(auto_now_add=True) # createDate
|
||||||
updated_at = models.DateTimeField(auto_now=True) # updateDate
|
updated_at = models.DateTimeField(auto_now=True) # updateDate
|
||||||
|
|
|
||||||
|
|
@ -35,6 +35,7 @@ def map_node_to_doc(node: Node) -> dict:
|
||||||
'title': node.title or '',
|
'title': node.title or '',
|
||||||
'des': (node.desc or ''),
|
'des': (node.desc or ''),
|
||||||
'htmlContent': node.html_content or '',
|
'htmlContent': node.html_content or '',
|
||||||
|
'markdown': node.markdown_content or '',
|
||||||
'createDate': node.created_at,
|
'createDate': node.created_at,
|
||||||
'updateDate': node.updated_at,
|
'updateDate': node.updated_at,
|
||||||
'delete': bool(node.deleted),
|
'delete': bool(node.deleted),
|
||||||
|
|
|
||||||
|
|
@ -178,6 +178,7 @@ def create_mindmap(request):
|
||||||
deleted=False,
|
deleted=False,
|
||||||
# 添加HTML内容
|
# 添加HTML内容
|
||||||
html_content=mindmap_data.get('dangerouslySetInnerHTML', ''),
|
html_content=mindmap_data.get('dangerouslySetInnerHTML', ''),
|
||||||
|
markdown_content=mindmap_data.get('markdown', '') or mindmap_data.get('des', ''),
|
||||||
# 添加图片信息
|
# 添加图片信息
|
||||||
image_url=mindmap_data.get('image', {}).get('url') if mindmap_data.get('image') else None,
|
image_url=mindmap_data.get('image', {}).get('url') if mindmap_data.get('image') else None,
|
||||||
image_width=mindmap_data.get('image', {}).get('width') if mindmap_data.get('image') else None,
|
image_width=mindmap_data.get('image', {}).get('width') if mindmap_data.get('image') else None,
|
||||||
|
|
@ -238,6 +239,7 @@ def create_nodes_recursively(nodes_data, mindmap, parent_id):
|
||||||
deleted=False,
|
deleted=False,
|
||||||
# 添加HTML内容
|
# 添加HTML内容
|
||||||
html_content=node_data.get('dangerouslySetInnerHTML', ''),
|
html_content=node_data.get('dangerouslySetInnerHTML', ''),
|
||||||
|
markdown_content=node_data.get('markdown', '') or node_data.get('des', ''),
|
||||||
# 添加图片信息
|
# 添加图片信息
|
||||||
image_url=node_data.get('image', {}).get('url') if node_data.get('image') else None,
|
image_url=node_data.get('image', {}).get('url') if node_data.get('image') else None,
|
||||||
image_width=node_data.get('image', {}).get('width') if node_data.get('image') else None,
|
image_width=node_data.get('image', {}).get('width') if node_data.get('image') else None,
|
||||||
|
|
@ -310,6 +312,7 @@ def add_nodes(request):
|
||||||
deleted=False,
|
deleted=False,
|
||||||
# 添加HTML内容
|
# 添加HTML内容
|
||||||
html_content=n.get('dangerouslySetInnerHTML', ''),
|
html_content=n.get('dangerouslySetInnerHTML', ''),
|
||||||
|
markdown_content=n.get('markdown', '') or n.get('des', ''),
|
||||||
)
|
)
|
||||||
|
|
||||||
# 更新父节点的子节点计数
|
# 更新父节点的子节点计数
|
||||||
|
|
@ -370,6 +373,10 @@ def update_node(request):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
print(f"❌ 更新 html_content 时出错: {e}")
|
print(f"❌ 更新 html_content 时出错: {e}")
|
||||||
return Response({'detail': f'Failed to update html_content: {str(e)}'}, status=500)
|
return Response({'detail': f'Failed to update html_content: {str(e)}'}, status=500)
|
||||||
|
# 新增:更新 markdown_content
|
||||||
|
if 'newMarkdown' in body:
|
||||||
|
node.markdown_content = body.get('newMarkdown') or ''
|
||||||
|
updated_fields.append('markdown_content')
|
||||||
|
|
||||||
if 'newParentId' in body:
|
if 'newParentId' in body:
|
||||||
new_parent_id = body.get('newParentId')
|
new_parent_id = body.get('newParentId')
|
||||||
|
|
|
||||||
|
|
@ -0,0 +1,111 @@
|
||||||
|
## 节点包含表格时的渲染逻辑(MindMap 前端)
|
||||||
|
|
||||||
|
本文件汇总“当节点内容中有表格时”的数据流、渲染、样式、交互与导出路径,便于快速定位问题与修改。
|
||||||
|
|
||||||
|
### 一、总体流程
|
||||||
|
- **输入来源**:
|
||||||
|
- Markdown 表格(GFM)
|
||||||
|
- 已有 HTML(`<table>`)
|
||||||
|
- **转换阶段**:
|
||||||
|
- Markdown → HTML:解析后输出 `<table class="markdown-table">`(附基础样式)。
|
||||||
|
- HTML → Markdown(需要时):优先用 Vditor 的 `html2md`;内置兜底逻辑会提取 `<table>` 为 GFM 格式。
|
||||||
|
- **节点渲染**:
|
||||||
|
- 优先使用 `dangerouslySetInnerHTML` 将 HTML 直接写入节点 DOM。
|
||||||
|
- 若是纯文本则走普通 `topic` 文本渲染。
|
||||||
|
- **样式覆盖**:
|
||||||
|
- 统一为表格设置固定布局、边框、间距、`white-space: normal` 等,避免被思维导图默认排版影响。
|
||||||
|
- **交互编辑**:
|
||||||
|
- 双击含表格的节点 → 走“表格专用编辑”流程(弹出覆盖层,按 Markdown 表格编辑)。
|
||||||
|
- **图片导出(SVG)**:
|
||||||
|
- 发现 `<table>` 时,导出使用 `foreignObject` 渲染,并内联样式与添加背景矩形,确保版式一致。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 二、数据来源与转换
|
||||||
|
- **Markdown → HTML(保留为 `<table>`)**
|
||||||
|
- 位置:`frontend/src/components/MindMap.vue`
|
||||||
|
- 逻辑:将 GFM 表格替换为 `<table class="markdown-table">`,并生成 `<thead>/<tbody>` 与单元格基础内联样式。
|
||||||
|
- **渲染后统一后处理**
|
||||||
|
- 位置:`frontend/src/utils/markdownRenderer.js`
|
||||||
|
- 逻辑:把裸 `<table>` 补成 `<table class="markdown-table">`,并处理代码块语法高亮等。
|
||||||
|
- **HTML → Markdown(用于回填编辑器/导出)**
|
||||||
|
- 位置:`frontend/src/components/MindMap.vue`
|
||||||
|
- 逻辑:若缺少 Markdown 源,优先 `Vditor.html2md`;否则解析 DOM,将 `<table>` 转回 GFM 表格(含表头/表体)。
|
||||||
|
|
||||||
|
示例 Markdown:
|
||||||
|
```markdown
|
||||||
|
| A | B |
|
||||||
|
|---|---|
|
||||||
|
| 1 | 2 |
|
||||||
|
```
|
||||||
|
渲染为:
|
||||||
|
```html
|
||||||
|
<table class="markdown-table">...
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 三、节点渲染优先级与更新
|
||||||
|
- **优先级**:`dangerouslySetInnerHTML` > `markdown` > `topic` 文本。
|
||||||
|
- **直接写入 DOM**:更新节点时,如果存在 `dangerouslySetInnerHTML`,直接 `nodeElement.innerHTML = dangerouslySetInnerHTML`。
|
||||||
|
- **回退渲染**:当内容不是 Markdown 时,回退渲染会先清理重复符号;若检测到 `<table>`,不做列表转换,直接保留表格结构。
|
||||||
|
|
||||||
|
涉及位置:
|
||||||
|
- `frontend/src/components/MindMap.vue`(保存与“直接设置 HTML”)
|
||||||
|
- `frontend/src/lib/mind-elixir/src/utils/dom.ts`(回退渲染与表格检测)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 四、样式与布局(确保表格按网格显示)
|
||||||
|
- 全局样式(保证在节点内渲染出的 `<table>` 有固定布局/合并边框/边框色):
|
||||||
|
- `frontend/src/App.vue` 中对 `.mind-elixir .map-container .topic table` 的规则。
|
||||||
|
- 组件内样式(覆盖思维导图的 `white-space`、`display`):
|
||||||
|
- `frontend/src/components/MindMap.vue` 中 `.topic .topic-text.markdown-content table` 及 `th/td/tr` 规则。
|
||||||
|
- 统一 `th/td` 的内边距、边框与交互高亮,避免被默认 inline 布局破坏行列结构。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 五、交互:双击进入表格编辑
|
||||||
|
- 位置:
|
||||||
|
- `frontend/src/lib/mind-elixir/src/mouse.ts`:双击节点时若 `innerHTML` 含 `<table>`,走“表格编辑”。
|
||||||
|
- `frontend/src/lib/mind-elixir/src/nodeOperation.ts`:`beginEdit` 内部判断表格后调用 `editTableNode`。
|
||||||
|
- 编辑方式:
|
||||||
|
- `editTableNode` 弹出覆盖层,编辑 Markdown 表格源(包含 HTML↔Markdown 的转换工具)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 六、导出图片(SVG)中的表格渲染
|
||||||
|
- 位置:`frontend/src/lib/mind-elixir/src/plugin/exportImage.ts`
|
||||||
|
- 检测 `dangerouslySetInnerHTML` 中是否含 `<table>`:
|
||||||
|
- 含表格:使用 `foreignObject` 嵌入 HTML,计算节点尺寸,创建背景矩形,并将所需样式内联化以确保导出与画布一致;表格本身在 `foreignObject` 内按浏览器 HTML 布局渲染。
|
||||||
|
- 非表格 HTML:优先尝试原生 SVG 文本渲染;必要时退回 `foreignObject`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 七、关键判断点一览
|
||||||
|
- 是否包含表格:
|
||||||
|
- 通过检测 `'<table'`、`'<td>'`、`'<th>'` 或 Markdown 中的 `|` 来作出路径选择(如走表格编辑、使用 `foreignObject` 导出等)。
|
||||||
|
- 渲染选择:
|
||||||
|
- 有 `dangerouslySetInnerHTML` → 直接注入 HTML;
|
||||||
|
- 否则尝试 `markdown` → `marked/自定义解析`;
|
||||||
|
- 最后回退到纯文本 `topic`。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 八、常见问题与建议
|
||||||
|
- 若表格在节点中“挤成一行”或“行列错乱”,优先检查是否有样式覆盖了:
|
||||||
|
- `display: table-*`、`white-space: normal !important`、`table-layout: fixed`、`border-collapse: collapse` 是否生效。
|
||||||
|
- 导出图片中表格错位:确认 `foreignObject` 是否被禁用、样式是否已内联、节点尺寸计算是否准确。
|
||||||
|
- 需要统一风格时,优先改 `.markdown-table` 与 `.topic .topic-text.markdown-content table` 相关样式。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 相关文件清单(便于跳转)
|
||||||
|
- `frontend/src/components/MindMap.vue`
|
||||||
|
- `frontend/src/utils/markdownRenderer.js`
|
||||||
|
- `frontend/src/lib/mind-elixir/src/utils/dom.ts`
|
||||||
|
- `frontend/src/lib/mind-elixir/src/mouse.ts`
|
||||||
|
- `frontend/src/lib/mind-elixir/src/nodeOperation.ts`
|
||||||
|
- `frontend/src/lib/mind-elixir/src/plugin/exportImage.ts`
|
||||||
|
- `frontend/src/App.vue`
|
||||||
|
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -23,8 +23,8 @@
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
}
|
}
|
||||||
</style>
|
</style>
|
||||||
<script type="module" crossorigin src="/assets/index-93385e5a.js"></script>
|
<script type="module" crossorigin src="/assets/index-54b52ca8.js"></script>
|
||||||
<link rel="stylesheet" href="/assets/index-1b564f4b.css">
|
<link rel="stylesheet" href="/assets/index-31cfb9b2.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|
|
||||||
|
|
@ -133,6 +133,13 @@
|
||||||
"node": ">= 10"
|
"node": ">= 10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/trusted-types": {
|
||||||
|
"version": "2.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||||
|
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"node_modules/@vitejs/plugin-vue": {
|
"node_modules/@vitejs/plugin-vue": {
|
||||||
"version": "4.6.2",
|
"version": "4.6.2",
|
||||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-4.6.2.tgz",
|
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-4.6.2.tgz",
|
||||||
|
|
@ -920,6 +927,15 @@
|
||||||
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/dompurify": {
|
||||||
|
"version": "3.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.0.tgz",
|
||||||
|
"integrity": "sha512-r+f6MYR1gGN1eJv0TVQbhA7if/U7P87cdPl3HN5rikqaBSBxLiCb/b9O+2eG0cxz0ghyU+mU1QkbsOwERMYlWQ==",
|
||||||
|
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@types/trusted-types": "^2.0.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/domutils": {
|
"node_modules/domutils": {
|
||||||
"version": "3.2.2",
|
"version": "3.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
|
||||||
|
|
|
||||||
|
|
@ -1,84 +1,90 @@
|
||||||
{
|
{
|
||||||
"hash": "c46ec827",
|
"hash": "b9f2c48d",
|
||||||
"browserHash": "60d29aeb",
|
"browserHash": "f5a8cee5",
|
||||||
"optimized": {
|
"optimized": {
|
||||||
"axios": {
|
"axios": {
|
||||||
"src": "../../axios/index.js",
|
"src": "../../axios/index.js",
|
||||||
"file": "axios.js",
|
"file": "axios.js",
|
||||||
"fileHash": "2ca36ff2",
|
"fileHash": "5a81d522",
|
||||||
"needsInterop": false
|
"needsInterop": false
|
||||||
},
|
},
|
||||||
"katex": {
|
"katex": {
|
||||||
"src": "../../katex/dist/katex.mjs",
|
"src": "../../katex/dist/katex.mjs",
|
||||||
"file": "katex.js",
|
"file": "katex.js",
|
||||||
"fileHash": "9c5eb978",
|
"fileHash": "da19a06e",
|
||||||
"needsInterop": false
|
"needsInterop": false
|
||||||
},
|
},
|
||||||
"mammoth": {
|
"mammoth": {
|
||||||
"src": "../../mammoth/lib/index.js",
|
"src": "../../mammoth/lib/index.js",
|
||||||
"file": "mammoth.js",
|
"file": "mammoth.js",
|
||||||
"fileHash": "f3f73b0d",
|
"fileHash": "b4c74eb7",
|
||||||
"needsInterop": true
|
"needsInterop": true
|
||||||
},
|
},
|
||||||
"marked": {
|
"marked": {
|
||||||
"src": "../../marked/lib/marked.esm.js",
|
"src": "../../marked/lib/marked.esm.js",
|
||||||
"file": "marked.js",
|
"file": "marked.js",
|
||||||
"fileHash": "f55c75a3",
|
"fileHash": "e67052f3",
|
||||||
"needsInterop": false
|
"needsInterop": false
|
||||||
},
|
},
|
||||||
"pdfjs-dist": {
|
"pdfjs-dist": {
|
||||||
"src": "../../pdfjs-dist/build/pdf.mjs",
|
"src": "../../pdfjs-dist/build/pdf.mjs",
|
||||||
"file": "pdfjs-dist.js",
|
"file": "pdfjs-dist.js",
|
||||||
"fileHash": "e73f4508",
|
"fileHash": "01c7aa39",
|
||||||
"needsInterop": false
|
"needsInterop": false
|
||||||
},
|
},
|
||||||
"prismjs": {
|
"prismjs": {
|
||||||
"src": "../../prismjs/prism.js",
|
"src": "../../prismjs/prism.js",
|
||||||
"file": "prismjs.js",
|
"file": "prismjs.js",
|
||||||
"fileHash": "85835641",
|
"fileHash": "67bb96db",
|
||||||
"needsInterop": true
|
"needsInterop": true
|
||||||
},
|
},
|
||||||
"prismjs/components/prism-css": {
|
"prismjs/components/prism-css": {
|
||||||
"src": "../../prismjs/components/prism-css.js",
|
"src": "../../prismjs/components/prism-css.js",
|
||||||
"file": "prismjs_components_prism-css.js",
|
"file": "prismjs_components_prism-css.js",
|
||||||
"fileHash": "9253baed",
|
"fileHash": "a46d4da5",
|
||||||
"needsInterop": true
|
"needsInterop": true
|
||||||
},
|
},
|
||||||
"prismjs/components/prism-javascript": {
|
"prismjs/components/prism-javascript": {
|
||||||
"src": "../../prismjs/components/prism-javascript.js",
|
"src": "../../prismjs/components/prism-javascript.js",
|
||||||
"file": "prismjs_components_prism-javascript.js",
|
"file": "prismjs_components_prism-javascript.js",
|
||||||
"fileHash": "c141d325",
|
"fileHash": "0edfaf95",
|
||||||
"needsInterop": true
|
"needsInterop": true
|
||||||
},
|
},
|
||||||
"prismjs/components/prism-json": {
|
"prismjs/components/prism-json": {
|
||||||
"src": "../../prismjs/components/prism-json.js",
|
"src": "../../prismjs/components/prism-json.js",
|
||||||
"file": "prismjs_components_prism-json.js",
|
"file": "prismjs_components_prism-json.js",
|
||||||
"fileHash": "b5b29352",
|
"fileHash": "9230ff9c",
|
||||||
"needsInterop": true
|
"needsInterop": true
|
||||||
},
|
},
|
||||||
"prismjs/components/prism-python": {
|
"prismjs/components/prism-python": {
|
||||||
"src": "../../prismjs/components/prism-python.js",
|
"src": "../../prismjs/components/prism-python.js",
|
||||||
"file": "prismjs_components_prism-python.js",
|
"file": "prismjs_components_prism-python.js",
|
||||||
"fileHash": "8c860934",
|
"fileHash": "fc916b99",
|
||||||
"needsInterop": true
|
"needsInterop": true
|
||||||
},
|
},
|
||||||
"prismjs/components/prism-sql": {
|
"prismjs/components/prism-sql": {
|
||||||
"src": "../../prismjs/components/prism-sql.js",
|
"src": "../../prismjs/components/prism-sql.js",
|
||||||
"file": "prismjs_components_prism-sql.js",
|
"file": "prismjs_components_prism-sql.js",
|
||||||
"fileHash": "1f26e048",
|
"fileHash": "05918beb",
|
||||||
"needsInterop": true
|
"needsInterop": true
|
||||||
},
|
},
|
||||||
"vue": {
|
"vue": {
|
||||||
"src": "../../vue/dist/vue.runtime.esm-bundler.js",
|
"src": "../../vue/dist/vue.runtime.esm-bundler.js",
|
||||||
"file": "vue.js",
|
"file": "vue.js",
|
||||||
"fileHash": "478d8195",
|
"fileHash": "ebb93566",
|
||||||
"needsInterop": false
|
"needsInterop": false
|
||||||
},
|
},
|
||||||
"vditor": {
|
"vditor": {
|
||||||
"src": "../../vditor/dist/index.js",
|
"src": "../../vditor/dist/index.js",
|
||||||
"file": "vditor.js",
|
"file": "vditor.js",
|
||||||
"fileHash": "1ea4a307",
|
"fileHash": "747d5f76",
|
||||||
"needsInterop": true
|
"needsInterop": true
|
||||||
|
},
|
||||||
|
"dompurify": {
|
||||||
|
"src": "../../dompurify/dist/purify.es.mjs",
|
||||||
|
"file": "dompurify.js",
|
||||||
|
"fileHash": "13de455c",
|
||||||
|
"needsInterop": false
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"chunks": {
|
"chunks": {
|
||||||
|
|
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,21 @@
|
||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) Microsoft Corporation.
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE
|
||||||
|
|
@ -0,0 +1,15 @@
|
||||||
|
# Installation
|
||||||
|
> `npm install --save @types/trusted-types`
|
||||||
|
|
||||||
|
# Summary
|
||||||
|
This package contains type definitions for trusted-types (https://github.com/WICG/trusted-types).
|
||||||
|
|
||||||
|
# Details
|
||||||
|
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/trusted-types.
|
||||||
|
|
||||||
|
### Additional Details
|
||||||
|
* Last updated: Mon, 20 Nov 2023 23:36:24 GMT
|
||||||
|
* Dependencies: none
|
||||||
|
|
||||||
|
# Credits
|
||||||
|
These definitions were written by [Jakub Vrana](https://github.com/vrana), [Damien Engels](https://github.com/engelsdamien), [Emanuel Tesar](https://github.com/siegrift), [Bjarki](https://github.com/bjarkler), and [Sebastian Silbermann](https://github.com/eps1lon).
|
||||||
|
|
@ -0,0 +1,53 @@
|
||||||
|
import * as lib from "./lib";
|
||||||
|
|
||||||
|
// Re-export the type definitions globally.
|
||||||
|
declare global {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation
|
||||||
|
interface TrustedHTML extends lib.TrustedHTML {}
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation
|
||||||
|
interface TrustedScript extends lib.TrustedScript {}
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation
|
||||||
|
interface TrustedScriptURL extends lib.TrustedScriptURL {}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation
|
||||||
|
interface TrustedTypePolicy extends lib.TrustedTypePolicy {}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation
|
||||||
|
interface TrustedTypePolicyFactory extends lib.TrustedTypePolicyFactory {}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation
|
||||||
|
interface TrustedTypePolicyOptions extends lib.TrustedTypePolicyOptions {}
|
||||||
|
|
||||||
|
// Attach the relevant Trusted Types properties to the Window object.
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-empty-interface -- interface to allow module augmentation
|
||||||
|
interface Window extends lib.TrustedTypesWindow {}
|
||||||
|
}
|
||||||
|
|
||||||
|
// These are the available exports when using the polyfill as npm package (e.g. in nodejs)
|
||||||
|
interface InternalTrustedTypePolicyFactory extends lib.TrustedTypePolicyFactory {
|
||||||
|
TrustedHTML: typeof lib.TrustedHTML;
|
||||||
|
TrustedScript: typeof lib.TrustedScript;
|
||||||
|
TrustedScriptURL: typeof lib.TrustedScriptURL;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare const trustedTypes: InternalTrustedTypePolicyFactory;
|
||||||
|
|
||||||
|
declare class TrustedTypesEnforcer {
|
||||||
|
constructor(config: TrustedTypeConfig);
|
||||||
|
install: () => void;
|
||||||
|
uninstall: () => void;
|
||||||
|
}
|
||||||
|
|
||||||
|
// tslint:disable-next-line no-unnecessary-class
|
||||||
|
declare class TrustedTypeConfig {
|
||||||
|
constructor(
|
||||||
|
isLoggingEnabled: boolean,
|
||||||
|
isEnforcementEnabled: boolean,
|
||||||
|
allowedPolicyNames: string[],
|
||||||
|
allowDuplicates: boolean,
|
||||||
|
cspString?: string | null,
|
||||||
|
windowObject?: Window,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export { TrustedTypeConfig, TrustedTypePolicy, TrustedTypePolicyFactory, trustedTypes, TrustedTypesEnforcer };
|
||||||
|
|
@ -0,0 +1,64 @@
|
||||||
|
// The main type definitions. Packages that do not want to pollute the global
|
||||||
|
// scope with Trusted Types (e.g. libraries whose users may not be using Trusted
|
||||||
|
// Types) can import the types directly from 'trusted-types/lib'.
|
||||||
|
|
||||||
|
export type FnNames = keyof TrustedTypePolicyOptions;
|
||||||
|
export type Args<Options extends TrustedTypePolicyOptions, K extends FnNames> = Parameters<NonNullable<Options[K]>>;
|
||||||
|
|
||||||
|
export class TrustedHTML {
|
||||||
|
private constructor(); // To prevent instantiting with 'new'.
|
||||||
|
private brand: true; // To prevent structural typing.
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TrustedScript {
|
||||||
|
private constructor(); // To prevent instantiting with 'new'.
|
||||||
|
private brand: true; // To prevent structural typing.
|
||||||
|
}
|
||||||
|
|
||||||
|
export class TrustedScriptURL {
|
||||||
|
private constructor(); // To prevent instantiting with 'new'.
|
||||||
|
private brand: true; // To prevent structural typing.
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class TrustedTypePolicyFactory {
|
||||||
|
createPolicy<Options extends TrustedTypePolicyOptions>(
|
||||||
|
policyName: string,
|
||||||
|
policyOptions?: Options,
|
||||||
|
): Pick<TrustedTypePolicy<Options>, "name" | Extract<keyof Options, FnNames>>;
|
||||||
|
isHTML(value: unknown): value is TrustedHTML;
|
||||||
|
isScript(value: unknown): value is TrustedScript;
|
||||||
|
isScriptURL(value: unknown): value is TrustedScriptURL;
|
||||||
|
readonly emptyHTML: TrustedHTML;
|
||||||
|
readonly emptyScript: TrustedScript;
|
||||||
|
getAttributeType(tagName: string, attribute: string, elementNs?: string, attrNs?: string): string | null;
|
||||||
|
getPropertyType(tagName: string, property: string, elementNs?: string): string | null;
|
||||||
|
readonly defaultPolicy: TrustedTypePolicy | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export abstract class TrustedTypePolicy<Options extends TrustedTypePolicyOptions = TrustedTypePolicyOptions> {
|
||||||
|
readonly name: string;
|
||||||
|
createHTML(...args: Args<Options, "createHTML">): TrustedHTML;
|
||||||
|
createScript(...args: Args<Options, "createScript">): TrustedScript;
|
||||||
|
createScriptURL(...args: Args<Options, "createScriptURL">): TrustedScriptURL;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface TrustedTypePolicyOptions {
|
||||||
|
createHTML?: ((input: string, ...arguments: any[]) => string) | undefined;
|
||||||
|
createScript?: ((input: string, ...arguments: any[]) => string) | undefined;
|
||||||
|
createScriptURL?: ((input: string, ...arguments: any[]) => string) | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The Window object is augmented with the following properties in browsers that
|
||||||
|
// support Trusted Types. Users of the 'trusted-types/lib' entrypoint can cast
|
||||||
|
// window as TrustedTypesWindow to access these properties.
|
||||||
|
export interface TrustedTypesWindow {
|
||||||
|
// `trustedTypes` is left intentionally optional to make sure that
|
||||||
|
// people handle the case when their code is running in a browser not
|
||||||
|
// supporting trustedTypes.
|
||||||
|
trustedTypes?: TrustedTypePolicyFactory | undefined;
|
||||||
|
TrustedHTML: typeof TrustedHTML;
|
||||||
|
TrustedScript: typeof TrustedScript;
|
||||||
|
TrustedScriptURL: typeof TrustedScriptURL;
|
||||||
|
TrustedTypePolicyFactory: typeof TrustedTypePolicyFactory;
|
||||||
|
TrustedTypePolicy: typeof TrustedTypePolicy;
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,45 @@
|
||||||
|
{
|
||||||
|
"name": "@types/trusted-types",
|
||||||
|
"version": "2.0.7",
|
||||||
|
"description": "TypeScript definitions for trusted-types",
|
||||||
|
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/trusted-types",
|
||||||
|
"license": "MIT",
|
||||||
|
"contributors": [
|
||||||
|
{
|
||||||
|
"name": "Jakub Vrana",
|
||||||
|
"githubUsername": "vrana",
|
||||||
|
"url": "https://github.com/vrana"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Damien Engels",
|
||||||
|
"githubUsername": "engelsdamien",
|
||||||
|
"url": "https://github.com/engelsdamien"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Emanuel Tesar",
|
||||||
|
"githubUsername": "siegrift",
|
||||||
|
"url": "https://github.com/siegrift"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Bjarki",
|
||||||
|
"githubUsername": "bjarkler",
|
||||||
|
"url": "https://github.com/bjarkler"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"name": "Sebastian Silbermann",
|
||||||
|
"githubUsername": "eps1lon",
|
||||||
|
"url": "https://github.com/eps1lon"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"main": "",
|
||||||
|
"types": "index.d.ts",
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
|
||||||
|
"directory": "types/trusted-types"
|
||||||
|
},
|
||||||
|
"scripts": {},
|
||||||
|
"dependencies": {},
|
||||||
|
"typesPublisherContentHash": "20982c5e0452e662515e29b41f7be5a3c69e5918a9228929a563d9f1dfdfbbc5",
|
||||||
|
"typeScriptVersion": "4.5"
|
||||||
|
}
|
||||||
|
|
@ -0,0 +1,568 @@
|
||||||
|
DOMPurify
|
||||||
|
Copyright 2025 Dr.-Ing. Mario Heiderich, Cure53
|
||||||
|
|
||||||
|
DOMPurify is free software; you can redistribute it and/or modify it under the
|
||||||
|
terms of either:
|
||||||
|
|
||||||
|
a) the Apache License Version 2.0, or
|
||||||
|
b) the Mozilla Public License Version 2.0
|
||||||
|
|
||||||
|
-----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
Apache License
|
||||||
|
Version 2.0, January 2004
|
||||||
|
http://www.apache.org/licenses/
|
||||||
|
|
||||||
|
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||||
|
|
||||||
|
1. Definitions.
|
||||||
|
|
||||||
|
"License" shall mean the terms and conditions for use, reproduction,
|
||||||
|
and distribution as defined by Sections 1 through 9 of this document.
|
||||||
|
|
||||||
|
"Licensor" shall mean the copyright owner or entity authorized by
|
||||||
|
the copyright owner that is granting the License.
|
||||||
|
|
||||||
|
"Legal Entity" shall mean the union of the acting entity and all
|
||||||
|
other entities that control, are controlled by, or are under common
|
||||||
|
control with that entity. For the purposes of this definition,
|
||||||
|
"control" means (i) the power, direct or indirect, to cause the
|
||||||
|
direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||||
|
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||||
|
|
||||||
|
"You" (or "Your") shall mean an individual or Legal Entity
|
||||||
|
exercising permissions granted by this License.
|
||||||
|
|
||||||
|
"Source" form shall mean the preferred form for making modifications,
|
||||||
|
including but not limited to software source code, documentation
|
||||||
|
source, and configuration files.
|
||||||
|
|
||||||
|
"Object" form shall mean any form resulting from mechanical
|
||||||
|
transformation or translation of a Source form, including but
|
||||||
|
not limited to compiled object code, generated documentation,
|
||||||
|
and conversions to other media types.
|
||||||
|
|
||||||
|
"Work" shall mean the work of authorship, whether in Source or
|
||||||
|
Object form, made available under the License, as indicated by a
|
||||||
|
copyright notice that is included in or attached to the work
|
||||||
|
(an example is provided in the Appendix below).
|
||||||
|
|
||||||
|
"Derivative Works" shall mean any work, whether in Source or Object
|
||||||
|
form, that is based on (or derived from) the Work and for which the
|
||||||
|
editorial revisions, annotations, elaborations, or other modifications
|
||||||
|
represent, as a whole, an original work of authorship. For the purposes
|
||||||
|
of this License, Derivative Works shall not include works that remain
|
||||||
|
separable from, or merely link (or bind by name) to the interfaces of,
|
||||||
|
the Work and Derivative Works thereof.
|
||||||
|
|
||||||
|
"Contribution" shall mean any work of authorship, including
|
||||||
|
the original version of the Work and any modifications or additions
|
||||||
|
to that Work or Derivative Works thereof, that is intentionally
|
||||||
|
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||||
|
or by an individual or Legal Entity authorized to submit on behalf of
|
||||||
|
the copyright owner. For the purposes of this definition, "submitted"
|
||||||
|
means any form of electronic, verbal, or written communication sent
|
||||||
|
to the Licensor or its representatives, including but not limited to
|
||||||
|
communication on electronic mailing lists, source code control systems,
|
||||||
|
and issue tracking systems that are managed by, or on behalf of, the
|
||||||
|
Licensor for the purpose of discussing and improving the Work, but
|
||||||
|
excluding communication that is conspicuously marked or otherwise
|
||||||
|
designated in writing by the copyright owner as "Not a Contribution."
|
||||||
|
|
||||||
|
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||||
|
on behalf of whom a Contribution has been received by Licensor and
|
||||||
|
subsequently incorporated within the Work.
|
||||||
|
|
||||||
|
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
copyright license to reproduce, prepare Derivative Works of,
|
||||||
|
publicly display, publicly perform, sublicense, and distribute the
|
||||||
|
Work and such Derivative Works in Source or Object form.
|
||||||
|
|
||||||
|
3. Grant of Patent License. Subject to the terms and conditions of
|
||||||
|
this License, each Contributor hereby grants to You a perpetual,
|
||||||
|
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||||
|
(except as stated in this section) patent license to make, have made,
|
||||||
|
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||||
|
where such license applies only to those patent claims licensable
|
||||||
|
by such Contributor that are necessarily infringed by their
|
||||||
|
Contribution(s) alone or by combination of their Contribution(s)
|
||||||
|
with the Work to which such Contribution(s) was submitted. If You
|
||||||
|
institute patent litigation against any entity (including a
|
||||||
|
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||||
|
or a Contribution incorporated within the Work constitutes direct
|
||||||
|
or contributory patent infringement, then any patent licenses
|
||||||
|
granted to You under this License for that Work shall terminate
|
||||||
|
as of the date such litigation is filed.
|
||||||
|
|
||||||
|
4. Redistribution. You may reproduce and distribute copies of the
|
||||||
|
Work or Derivative Works thereof in any medium, with or without
|
||||||
|
modifications, and in Source or Object form, provided that You
|
||||||
|
meet the following conditions:
|
||||||
|
|
||||||
|
(a) You must give any other recipients of the Work or
|
||||||
|
Derivative Works a copy of this License; and
|
||||||
|
|
||||||
|
(b) You must cause any modified files to carry prominent notices
|
||||||
|
stating that You changed the files; and
|
||||||
|
|
||||||
|
(c) You must retain, in the Source form of any Derivative Works
|
||||||
|
that You distribute, all copyright, patent, trademark, and
|
||||||
|
attribution notices from the Source form of the Work,
|
||||||
|
excluding those notices that do not pertain to any part of
|
||||||
|
the Derivative Works; and
|
||||||
|
|
||||||
|
(d) If the Work includes a "NOTICE" text file as part of its
|
||||||
|
distribution, then any Derivative Works that You distribute must
|
||||||
|
include a readable copy of the attribution notices contained
|
||||||
|
within such NOTICE file, excluding those notices that do not
|
||||||
|
pertain to any part of the Derivative Works, in at least one
|
||||||
|
of the following places: within a NOTICE text file distributed
|
||||||
|
as part of the Derivative Works; within the Source form or
|
||||||
|
documentation, if provided along with the Derivative Works; or,
|
||||||
|
within a display generated by the Derivative Works, if and
|
||||||
|
wherever such third-party notices normally appear. The contents
|
||||||
|
of the NOTICE file are for informational purposes only and
|
||||||
|
do not modify the License. You may add Your own attribution
|
||||||
|
notices within Derivative Works that You distribute, alongside
|
||||||
|
or as an addendum to the NOTICE text from the Work, provided
|
||||||
|
that such additional attribution notices cannot be construed
|
||||||
|
as modifying the License.
|
||||||
|
|
||||||
|
You may add Your own copyright statement to Your modifications and
|
||||||
|
may provide additional or different license terms and conditions
|
||||||
|
for use, reproduction, or distribution of Your modifications, or
|
||||||
|
for any such Derivative Works as a whole, provided Your use,
|
||||||
|
reproduction, and distribution of the Work otherwise complies with
|
||||||
|
the conditions stated in this License.
|
||||||
|
|
||||||
|
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||||
|
any Contribution intentionally submitted for inclusion in the Work
|
||||||
|
by You to the Licensor shall be under the terms and conditions of
|
||||||
|
this License, without any additional terms or conditions.
|
||||||
|
Notwithstanding the above, nothing herein shall supersede or modify
|
||||||
|
the terms of any separate license agreement you may have executed
|
||||||
|
with Licensor regarding such Contributions.
|
||||||
|
|
||||||
|
6. Trademarks. This License does not grant permission to use the trade
|
||||||
|
names, trademarks, service marks, or product names of the Licensor,
|
||||||
|
except as required for reasonable and customary use in describing the
|
||||||
|
origin of the Work and reproducing the content of the NOTICE file.
|
||||||
|
|
||||||
|
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||||
|
agreed to in writing, Licensor provides the Work (and each
|
||||||
|
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||||
|
implied, including, without limitation, any warranties or conditions
|
||||||
|
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||||
|
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||||
|
appropriateness of using or redistributing the Work and assume any
|
||||||
|
risks associated with Your exercise of permissions under this License.
|
||||||
|
|
||||||
|
8. Limitation of Liability. In no event and under no legal theory,
|
||||||
|
whether in tort (including negligence), contract, or otherwise,
|
||||||
|
unless required by applicable law (such as deliberate and grossly
|
||||||
|
negligent acts) or agreed to in writing, shall any Contributor be
|
||||||
|
liable to You for damages, including any direct, indirect, special,
|
||||||
|
incidental, or consequential damages of any character arising as a
|
||||||
|
result of this License or out of the use or inability to use the
|
||||||
|
Work (including but not limited to damages for loss of goodwill,
|
||||||
|
work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses), even if such Contributor
|
||||||
|
has been advised of the possibility of such damages.
|
||||||
|
|
||||||
|
9. Accepting Warranty or Additional Liability. While redistributing
|
||||||
|
the Work or Derivative Works thereof, You may choose to offer,
|
||||||
|
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||||
|
or other liability obligations and/or rights consistent with this
|
||||||
|
License. However, in accepting such obligations, You may act only
|
||||||
|
on Your own behalf and on Your sole responsibility, not on behalf
|
||||||
|
of any other Contributor, and only if You agree to indemnify,
|
||||||
|
defend, and hold each Contributor harmless for any liability
|
||||||
|
incurred by, or claims asserted against, such Contributor by reason
|
||||||
|
of your accepting any such warranty or additional liability.
|
||||||
|
|
||||||
|
END OF TERMS AND CONDITIONS
|
||||||
|
|
||||||
|
APPENDIX: How to apply the Apache License to your work.
|
||||||
|
|
||||||
|
To apply the Apache License to your work, attach the following
|
||||||
|
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||||
|
replaced with your own identifying information. (Don't include
|
||||||
|
the brackets!) The text should be enclosed in the appropriate
|
||||||
|
comment syntax for the file format. We also recommend that a
|
||||||
|
file or class name and description of purpose be included on the
|
||||||
|
same "printed page" as the copyright notice for easier
|
||||||
|
identification within third-party archives.
|
||||||
|
|
||||||
|
Copyright [yyyy] [name of copyright owner]
|
||||||
|
|
||||||
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
|
you may not use this file except in compliance with the License.
|
||||||
|
You may obtain a copy of the License at
|
||||||
|
|
||||||
|
http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
|
||||||
|
Unless required by applicable law or agreed to in writing, software
|
||||||
|
distributed under the License is distributed on an "AS IS" BASIS,
|
||||||
|
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
See the License for the specific language governing permissions and
|
||||||
|
limitations under the License.
|
||||||
|
|
||||||
|
-----------------------------------------------------------------------------
|
||||||
|
Mozilla Public License, version 2.0
|
||||||
|
|
||||||
|
1. Definitions
|
||||||
|
|
||||||
|
1.1. “Contributor”
|
||||||
|
|
||||||
|
means each individual or legal entity that creates, contributes to the
|
||||||
|
creation of, or owns Covered Software.
|
||||||
|
|
||||||
|
1.2. “Contributor Version”
|
||||||
|
|
||||||
|
means the combination of the Contributions of others (if any) used by a
|
||||||
|
Contributor and that particular Contributor’s Contribution.
|
||||||
|
|
||||||
|
1.3. “Contribution”
|
||||||
|
|
||||||
|
means Covered Software of a particular Contributor.
|
||||||
|
|
||||||
|
1.4. “Covered Software”
|
||||||
|
|
||||||
|
means Source Code Form to which the initial Contributor has attached the
|
||||||
|
notice in Exhibit A, the Executable Form of such Source Code Form, and
|
||||||
|
Modifications of such Source Code Form, in each case including portions
|
||||||
|
thereof.
|
||||||
|
|
||||||
|
1.5. “Incompatible With Secondary Licenses”
|
||||||
|
means
|
||||||
|
|
||||||
|
a. that the initial Contributor has attached the notice described in
|
||||||
|
Exhibit B to the Covered Software; or
|
||||||
|
|
||||||
|
b. that the Covered Software was made available under the terms of version
|
||||||
|
1.1 or earlier of the License, but not also under the terms of a
|
||||||
|
Secondary License.
|
||||||
|
|
||||||
|
1.6. “Executable Form”
|
||||||
|
|
||||||
|
means any form of the work other than Source Code Form.
|
||||||
|
|
||||||
|
1.7. “Larger Work”
|
||||||
|
|
||||||
|
means a work that combines Covered Software with other material, in a separate
|
||||||
|
file or files, that is not Covered Software.
|
||||||
|
|
||||||
|
1.8. “License”
|
||||||
|
|
||||||
|
means this document.
|
||||||
|
|
||||||
|
1.9. “Licensable”
|
||||||
|
|
||||||
|
means having the right to grant, to the maximum extent possible, whether at the
|
||||||
|
time of the initial grant or subsequently, any and all of the rights conveyed by
|
||||||
|
this License.
|
||||||
|
|
||||||
|
1.10. “Modifications”
|
||||||
|
|
||||||
|
means any of the following:
|
||||||
|
|
||||||
|
a. any file in Source Code Form that results from an addition to, deletion
|
||||||
|
from, or modification of the contents of Covered Software; or
|
||||||
|
|
||||||
|
b. any new file in Source Code Form that contains any Covered Software.
|
||||||
|
|
||||||
|
1.11. “Patent Claims” of a Contributor
|
||||||
|
|
||||||
|
means any patent claim(s), including without limitation, method, process,
|
||||||
|
and apparatus claims, in any patent Licensable by such Contributor that
|
||||||
|
would be infringed, but for the grant of the License, by the making,
|
||||||
|
using, selling, offering for sale, having made, import, or transfer of
|
||||||
|
either its Contributions or its Contributor Version.
|
||||||
|
|
||||||
|
1.12. “Secondary License”
|
||||||
|
|
||||||
|
means either the GNU General Public License, Version 2.0, the GNU Lesser
|
||||||
|
General Public License, Version 2.1, the GNU Affero General Public
|
||||||
|
License, Version 3.0, or any later versions of those licenses.
|
||||||
|
|
||||||
|
1.13. “Source Code Form”
|
||||||
|
|
||||||
|
means the form of the work preferred for making modifications.
|
||||||
|
|
||||||
|
1.14. “You” (or “Your”)
|
||||||
|
|
||||||
|
means an individual or a legal entity exercising rights under this
|
||||||
|
License. For legal entities, “You” includes any entity that controls, is
|
||||||
|
controlled by, or is under common control with You. For purposes of this
|
||||||
|
definition, “control” means (a) the power, direct or indirect, to cause
|
||||||
|
the direction or management of such entity, whether by contract or
|
||||||
|
otherwise, or (b) ownership of more than fifty percent (50%) of the
|
||||||
|
outstanding shares or beneficial ownership of such entity.
|
||||||
|
|
||||||
|
|
||||||
|
2. License Grants and Conditions
|
||||||
|
|
||||||
|
2.1. Grants
|
||||||
|
|
||||||
|
Each Contributor hereby grants You a world-wide, royalty-free,
|
||||||
|
non-exclusive license:
|
||||||
|
|
||||||
|
a. under intellectual property rights (other than patent or trademark)
|
||||||
|
Licensable by such Contributor to use, reproduce, make available,
|
||||||
|
modify, display, perform, distribute, and otherwise exploit its
|
||||||
|
Contributions, either on an unmodified basis, with Modifications, or as
|
||||||
|
part of a Larger Work; and
|
||||||
|
|
||||||
|
b. under Patent Claims of such Contributor to make, use, sell, offer for
|
||||||
|
sale, have made, import, and otherwise transfer either its Contributions
|
||||||
|
or its Contributor Version.
|
||||||
|
|
||||||
|
2.2. Effective Date
|
||||||
|
|
||||||
|
The licenses granted in Section 2.1 with respect to any Contribution become
|
||||||
|
effective for each Contribution on the date the Contributor first distributes
|
||||||
|
such Contribution.
|
||||||
|
|
||||||
|
2.3. Limitations on Grant Scope
|
||||||
|
|
||||||
|
The licenses granted in this Section 2 are the only rights granted under this
|
||||||
|
License. No additional rights or licenses will be implied from the distribution
|
||||||
|
or licensing of Covered Software under this License. Notwithstanding Section
|
||||||
|
2.1(b) above, no patent license is granted by a Contributor:
|
||||||
|
|
||||||
|
a. for any code that a Contributor has removed from Covered Software; or
|
||||||
|
|
||||||
|
b. for infringements caused by: (i) Your and any other third party’s
|
||||||
|
modifications of Covered Software, or (ii) the combination of its
|
||||||
|
Contributions with other software (except as part of its Contributor
|
||||||
|
Version); or
|
||||||
|
|
||||||
|
c. under Patent Claims infringed by Covered Software in the absence of its
|
||||||
|
Contributions.
|
||||||
|
|
||||||
|
This License does not grant any rights in the trademarks, service marks, or
|
||||||
|
logos of any Contributor (except as may be necessary to comply with the
|
||||||
|
notice requirements in Section 3.4).
|
||||||
|
|
||||||
|
2.4. Subsequent Licenses
|
||||||
|
|
||||||
|
No Contributor makes additional grants as a result of Your choice to
|
||||||
|
distribute the Covered Software under a subsequent version of this License
|
||||||
|
(see Section 10.2) or under the terms of a Secondary License (if permitted
|
||||||
|
under the terms of Section 3.3).
|
||||||
|
|
||||||
|
2.5. Representation
|
||||||
|
|
||||||
|
Each Contributor represents that the Contributor believes its Contributions
|
||||||
|
are its original creation(s) or it has sufficient rights to grant the
|
||||||
|
rights to its Contributions conveyed by this License.
|
||||||
|
|
||||||
|
2.6. Fair Use
|
||||||
|
|
||||||
|
This License is not intended to limit any rights You have under applicable
|
||||||
|
copyright doctrines of fair use, fair dealing, or other equivalents.
|
||||||
|
|
||||||
|
2.7. Conditions
|
||||||
|
|
||||||
|
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted in
|
||||||
|
Section 2.1.
|
||||||
|
|
||||||
|
|
||||||
|
3. Responsibilities
|
||||||
|
|
||||||
|
3.1. Distribution of Source Form
|
||||||
|
|
||||||
|
All distribution of Covered Software in Source Code Form, including any
|
||||||
|
Modifications that You create or to which You contribute, must be under the
|
||||||
|
terms of this License. You must inform recipients that the Source Code Form
|
||||||
|
of the Covered Software is governed by the terms of this License, and how
|
||||||
|
they can obtain a copy of this License. You may not attempt to alter or
|
||||||
|
restrict the recipients’ rights in the Source Code Form.
|
||||||
|
|
||||||
|
3.2. Distribution of Executable Form
|
||||||
|
|
||||||
|
If You distribute Covered Software in Executable Form then:
|
||||||
|
|
||||||
|
a. such Covered Software must also be made available in Source Code Form,
|
||||||
|
as described in Section 3.1, and You must inform recipients of the
|
||||||
|
Executable Form how they can obtain a copy of such Source Code Form by
|
||||||
|
reasonable means in a timely manner, at a charge no more than the cost
|
||||||
|
of distribution to the recipient; and
|
||||||
|
|
||||||
|
b. You may distribute such Executable Form under the terms of this License,
|
||||||
|
or sublicense it under different terms, provided that the license for
|
||||||
|
the Executable Form does not attempt to limit or alter the recipients’
|
||||||
|
rights in the Source Code Form under this License.
|
||||||
|
|
||||||
|
3.3. Distribution of a Larger Work
|
||||||
|
|
||||||
|
You may create and distribute a Larger Work under terms of Your choice,
|
||||||
|
provided that You also comply with the requirements of this License for the
|
||||||
|
Covered Software. If the Larger Work is a combination of Covered Software
|
||||||
|
with a work governed by one or more Secondary Licenses, and the Covered
|
||||||
|
Software is not Incompatible With Secondary Licenses, this License permits
|
||||||
|
You to additionally distribute such Covered Software under the terms of
|
||||||
|
such Secondary License(s), so that the recipient of the Larger Work may, at
|
||||||
|
their option, further distribute the Covered Software under the terms of
|
||||||
|
either this License or such Secondary License(s).
|
||||||
|
|
||||||
|
3.4. Notices
|
||||||
|
|
||||||
|
You may not remove or alter the substance of any license notices (including
|
||||||
|
copyright notices, patent notices, disclaimers of warranty, or limitations
|
||||||
|
of liability) contained within the Source Code Form of the Covered
|
||||||
|
Software, except that You may alter any license notices to the extent
|
||||||
|
required to remedy known factual inaccuracies.
|
||||||
|
|
||||||
|
3.5. Application of Additional Terms
|
||||||
|
|
||||||
|
You may choose to offer, and to charge a fee for, warranty, support,
|
||||||
|
indemnity or liability obligations to one or more recipients of Covered
|
||||||
|
Software. However, You may do so only on Your own behalf, and not on behalf
|
||||||
|
of any Contributor. You must make it absolutely clear that any such
|
||||||
|
warranty, support, indemnity, or liability obligation is offered by You
|
||||||
|
alone, and You hereby agree to indemnify every Contributor for any
|
||||||
|
liability incurred by such Contributor as a result of warranty, support,
|
||||||
|
indemnity or liability terms You offer. You may include additional
|
||||||
|
disclaimers of warranty and limitations of liability specific to any
|
||||||
|
jurisdiction.
|
||||||
|
|
||||||
|
4. Inability to Comply Due to Statute or Regulation
|
||||||
|
|
||||||
|
If it is impossible for You to comply with any of the terms of this License
|
||||||
|
with respect to some or all of the Covered Software due to statute, judicial
|
||||||
|
order, or regulation then You must: (a) comply with the terms of this License
|
||||||
|
to the maximum extent possible; and (b) describe the limitations and the code
|
||||||
|
they affect. Such description must be placed in a text file included with all
|
||||||
|
distributions of the Covered Software under this License. Except to the
|
||||||
|
extent prohibited by statute or regulation, such description must be
|
||||||
|
sufficiently detailed for a recipient of ordinary skill to be able to
|
||||||
|
understand it.
|
||||||
|
|
||||||
|
5. Termination
|
||||||
|
|
||||||
|
5.1. The rights granted under this License will terminate automatically if You
|
||||||
|
fail to comply with any of its terms. However, if You become compliant,
|
||||||
|
then the rights granted under this License from a particular Contributor
|
||||||
|
are reinstated (a) provisionally, unless and until such Contributor
|
||||||
|
explicitly and finally terminates Your grants, and (b) on an ongoing basis,
|
||||||
|
if such Contributor fails to notify You of the non-compliance by some
|
||||||
|
reasonable means prior to 60 days after You have come back into compliance.
|
||||||
|
Moreover, Your grants from a particular Contributor are reinstated on an
|
||||||
|
ongoing basis if such Contributor notifies You of the non-compliance by
|
||||||
|
some reasonable means, this is the first time You have received notice of
|
||||||
|
non-compliance with this License from such Contributor, and You become
|
||||||
|
compliant prior to 30 days after Your receipt of the notice.
|
||||||
|
|
||||||
|
5.2. If You initiate litigation against any entity by asserting a patent
|
||||||
|
infringement claim (excluding declaratory judgment actions, counter-claims,
|
||||||
|
and cross-claims) alleging that a Contributor Version directly or
|
||||||
|
indirectly infringes any patent, then the rights granted to You by any and
|
||||||
|
all Contributors for the Covered Software under Section 2.1 of this License
|
||||||
|
shall terminate.
|
||||||
|
|
||||||
|
5.3. In the event of termination under Sections 5.1 or 5.2 above, all end user
|
||||||
|
license agreements (excluding distributors and resellers) which have been
|
||||||
|
validly granted by You or Your distributors under this License prior to
|
||||||
|
termination shall survive termination.
|
||||||
|
|
||||||
|
6. Disclaimer of Warranty
|
||||||
|
|
||||||
|
Covered Software is provided under this License on an “as is” basis, without
|
||||||
|
warranty of any kind, either expressed, implied, or statutory, including,
|
||||||
|
without limitation, warranties that the Covered Software is free of defects,
|
||||||
|
merchantable, fit for a particular purpose or non-infringing. The entire
|
||||||
|
risk as to the quality and performance of the Covered Software is with You.
|
||||||
|
Should any Covered Software prove defective in any respect, You (not any
|
||||||
|
Contributor) assume the cost of any necessary servicing, repair, or
|
||||||
|
correction. This disclaimer of warranty constitutes an essential part of this
|
||||||
|
License. No use of any Covered Software is authorized under this License
|
||||||
|
except under this disclaimer.
|
||||||
|
|
||||||
|
7. Limitation of Liability
|
||||||
|
|
||||||
|
Under no circumstances and under no legal theory, whether tort (including
|
||||||
|
negligence), contract, or otherwise, shall any Contributor, or anyone who
|
||||||
|
distributes Covered Software as permitted above, be liable to You for any
|
||||||
|
direct, indirect, special, incidental, or consequential damages of any
|
||||||
|
character including, without limitation, damages for lost profits, loss of
|
||||||
|
goodwill, work stoppage, computer failure or malfunction, or any and all
|
||||||
|
other commercial damages or losses, even if such party shall have been
|
||||||
|
informed of the possibility of such damages. This limitation of liability
|
||||||
|
shall not apply to liability for death or personal injury resulting from such
|
||||||
|
party’s negligence to the extent applicable law prohibits such limitation.
|
||||||
|
Some jurisdictions do not allow the exclusion or limitation of incidental or
|
||||||
|
consequential damages, so this exclusion and limitation may not apply to You.
|
||||||
|
|
||||||
|
8. Litigation
|
||||||
|
|
||||||
|
Any litigation relating to this License may be brought only in the courts of
|
||||||
|
a jurisdiction where the defendant maintains its principal place of business
|
||||||
|
and such litigation shall be governed by laws of that jurisdiction, without
|
||||||
|
reference to its conflict-of-law provisions. Nothing in this Section shall
|
||||||
|
prevent a party’s ability to bring cross-claims or counter-claims.
|
||||||
|
|
||||||
|
9. Miscellaneous
|
||||||
|
|
||||||
|
This License represents the complete agreement concerning the subject matter
|
||||||
|
hereof. If any provision of this License is held to be unenforceable, such
|
||||||
|
provision shall be reformed only to the extent necessary to make it
|
||||||
|
enforceable. Any law or regulation which provides that the language of a
|
||||||
|
contract shall be construed against the drafter shall not be used to construe
|
||||||
|
this License against a Contributor.
|
||||||
|
|
||||||
|
|
||||||
|
10. Versions of the License
|
||||||
|
|
||||||
|
10.1. New Versions
|
||||||
|
|
||||||
|
Mozilla Foundation is the license steward. Except as provided in Section
|
||||||
|
10.3, no one other than the license steward has the right to modify or
|
||||||
|
publish new versions of this License. Each version will be given a
|
||||||
|
distinguishing version number.
|
||||||
|
|
||||||
|
10.2. Effect of New Versions
|
||||||
|
|
||||||
|
You may distribute the Covered Software under the terms of the version of
|
||||||
|
the License under which You originally received the Covered Software, or
|
||||||
|
under the terms of any subsequent version published by the license
|
||||||
|
steward.
|
||||||
|
|
||||||
|
10.3. Modified Versions
|
||||||
|
|
||||||
|
If you create software not governed by this License, and you want to
|
||||||
|
create a new license for such software, you may create and use a modified
|
||||||
|
version of this License if you rename the license and remove any
|
||||||
|
references to the name of the license steward (except to note that such
|
||||||
|
modified license differs from this License).
|
||||||
|
|
||||||
|
10.4. Distributing Source Code Form that is Incompatible With Secondary Licenses
|
||||||
|
If You choose to distribute Source Code Form that is Incompatible With
|
||||||
|
Secondary Licenses under the terms of this version of the License, the
|
||||||
|
notice described in Exhibit B of this License must be attached.
|
||||||
|
|
||||||
|
Exhibit A - Source Code Form License Notice
|
||||||
|
|
||||||
|
This Source Code Form is subject to the
|
||||||
|
terms of the Mozilla Public License, v.
|
||||||
|
2.0. If a copy of the MPL was not
|
||||||
|
distributed with this file, You can
|
||||||
|
obtain one at
|
||||||
|
http://mozilla.org/MPL/2.0/.
|
||||||
|
|
||||||
|
If it is not possible or desirable to put the notice in a particular file, then
|
||||||
|
You may include the notice in a location (such as a LICENSE file in a relevant
|
||||||
|
directory) where a recipient would be likely to look for such a notice.
|
||||||
|
|
||||||
|
You may add additional accurate notices of copyright ownership.
|
||||||
|
|
||||||
|
Exhibit B - “Incompatible With Secondary Licenses” Notice
|
||||||
|
|
||||||
|
This Source Code Form is “Incompatible
|
||||||
|
With Secondary Licenses”, as defined by
|
||||||
|
the Mozilla Public License, v. 2.0.
|
||||||
|
|
||||||
|
|
@ -0,0 +1,476 @@
|
||||||
|
# DOMPurify
|
||||||
|
|
||||||
|
[](http://badge.fury.io/js/dompurify)  [](https://www.npmjs.com/package/dompurify)  [](https://github.com/cure53/DOMPurify/network/dependents) [](https://cloudback.it)
|
||||||
|
|
||||||
|
DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG.
|
||||||
|
|
||||||
|
It's also very simple to use and get started with. DOMPurify was [started in February 2014](https://github.com/cure53/DOMPurify/commit/a630922616927373485e0e787ab19e73e3691b2b) and, meanwhile, has reached version **v3.3.0**.
|
||||||
|
|
||||||
|
DOMPurify is written in JavaScript and works in all modern browsers (Safari (10+), Opera (15+), Edge, Firefox and Chrome - as well as almost anything else using Blink, Gecko or WebKit). It doesn't break on MSIE or other legacy browsers. It simply does nothing.
|
||||||
|
|
||||||
|
**Note that [DOMPurify v2.5.8](https://github.com/cure53/DOMPurify/releases/tag/2.5.8) is the latest version supporting MSIE. For important security updates compatible with MSIE, please use the [2.x branch](https://github.com/cure53/DOMPurify/tree/2.x).**
|
||||||
|
|
||||||
|
Our automated tests cover [28 different browsers](https://github.com/cure53/DOMPurify/blob/main/test/karma.custom-launchers.config.js#L5) right now, more to come. We also cover Node.js v18.x, v19.x, v20.x, v21.x, v22.x and v23.x, running DOMPurify on [jsdom](https://github.com/jsdom/jsdom). Older Node versions are known to work as well, but hey... no guarantees.
|
||||||
|
|
||||||
|
DOMPurify is written by security people who have vast background in web attacks and XSS. Fear not. For more details please also read about our [Security Goals & Threat Model](https://github.com/cure53/DOMPurify/wiki/Security-Goals-&-Threat-Model). Please, read it. Like, really.
|
||||||
|
|
||||||
|
## What does it do?
|
||||||
|
|
||||||
|
DOMPurify sanitizes HTML and prevents XSS attacks. You can feed DOMPurify with string full of dirty HTML and it will return a string (unless configured otherwise) with clean HTML. DOMPurify will strip out everything that contains dangerous HTML and thereby prevent XSS attacks and other nastiness. It's also damn bloody fast. We use the technologies the browser provides and turn them into an XSS filter. The faster your browser, the faster DOMPurify will be.
|
||||||
|
|
||||||
|
## How do I use it?
|
||||||
|
|
||||||
|
It's easy. Just include DOMPurify on your website.
|
||||||
|
|
||||||
|
### Using the unminified version (source-map available)
|
||||||
|
|
||||||
|
```html
|
||||||
|
<script type="text/javascript" src="dist/purify.js"></script>
|
||||||
|
```
|
||||||
|
|
||||||
|
### Using the minified and tested production version (source-map available)
|
||||||
|
|
||||||
|
```html
|
||||||
|
<script type="text/javascript" src="dist/purify.min.js"></script>
|
||||||
|
```
|
||||||
|
|
||||||
|
Afterwards you can sanitize strings by executing the following code:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const clean = DOMPurify.sanitize(dirty);
|
||||||
|
```
|
||||||
|
|
||||||
|
Or maybe this, if you love working with Angular or alike:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import DOMPurify from 'dompurify';
|
||||||
|
|
||||||
|
const clean = DOMPurify.sanitize('<b>hello there</b>');
|
||||||
|
```
|
||||||
|
|
||||||
|
The resulting HTML can be written into a DOM element using `innerHTML` or the DOM using `document.write()`. That is fully up to you.
|
||||||
|
Note that by default, we permit HTML, SVG **and** MathML. If you only need HTML, which might be a very common use-case, you can easily set that up as well:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const clean = DOMPurify.sanitize(dirty, { USE_PROFILES: { html: true } });
|
||||||
|
```
|
||||||
|
|
||||||
|
### Is there any foot-gun potential?
|
||||||
|
|
||||||
|
Well, please note, if you _first_ sanitize HTML and then modify it _afterwards_, you might easily **void the effects of sanitization**. If you feed the sanitized markup to another library _after_ sanitization, please be certain that the library doesn't mess around with the HTML on its own.
|
||||||
|
|
||||||
|
### Okay, makes sense, let's move on
|
||||||
|
|
||||||
|
After sanitizing your markup, you can also have a look at the property `DOMPurify.removed` and find out, what elements and attributes were thrown out. Please **do not use** this property for making any security critical decisions. This is just a little helper for curious minds.
|
||||||
|
|
||||||
|
### Running DOMPurify on the server
|
||||||
|
|
||||||
|
DOMPurify technically also works server-side with Node.js. Our support strives to follow the [Node.js release cycle](https://nodejs.org/en/about/releases/).
|
||||||
|
|
||||||
|
Running DOMPurify on the server requires a DOM to be present, which is probably no surprise. Usually, [jsdom](https://github.com/jsdom/jsdom) is the tool of choice and we **strongly recommend** to use the latest version of _jsdom_.
|
||||||
|
|
||||||
|
Why? Because older versions of _jsdom_ are known to be buggy in ways that result in XSS _even if_ DOMPurify does everything 100% correctly. There are **known attack vectors** in, e.g. _jsdom v19.0.0_ that are fixed in _jsdom v20.0.0_ - and we really recommend to keep _jsdom_ up to date because of that.
|
||||||
|
|
||||||
|
Please also be aware that tools like [happy-dom](https://github.com/capricorn86/happy-dom) exist but **are not considered safe** at this point. Combining DOMPurify with _happy-dom_ is currently not recommended and will likely lead to XSS.
|
||||||
|
|
||||||
|
Other than that, you are fine to use DOMPurify on the server. Probably. This really depends on _jsdom_ or whatever DOM you utilize server-side. If you can live with that, this is how you get it to work:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install dompurify
|
||||||
|
npm install jsdom
|
||||||
|
```
|
||||||
|
|
||||||
|
For _jsdom_ (please use an up-to-date version), this should do the trick:
|
||||||
|
|
||||||
|
```js
|
||||||
|
const createDOMPurify = require('dompurify');
|
||||||
|
const { JSDOM } = require('jsdom');
|
||||||
|
|
||||||
|
const window = new JSDOM('').window;
|
||||||
|
const DOMPurify = createDOMPurify(window);
|
||||||
|
const clean = DOMPurify.sanitize('<b>hello there</b>');
|
||||||
|
```
|
||||||
|
|
||||||
|
Or even this, if you prefer working with imports:
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { JSDOM } from 'jsdom';
|
||||||
|
import DOMPurify from 'dompurify';
|
||||||
|
|
||||||
|
const window = new JSDOM('').window;
|
||||||
|
const purify = DOMPurify(window);
|
||||||
|
const clean = purify.sanitize('<b>hello there</b>');
|
||||||
|
```
|
||||||
|
|
||||||
|
If you have problems making it work in your specific setup, consider looking at the amazing [isomorphic-dompurify](https://github.com/kkomelin/isomorphic-dompurify) project which solves lots of problems people might run into.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
npm install isomorphic-dompurify
|
||||||
|
```
|
||||||
|
|
||||||
|
```js
|
||||||
|
import DOMPurify from 'isomorphic-dompurify';
|
||||||
|
|
||||||
|
const clean = DOMPurify.sanitize('<s>hello</s>');
|
||||||
|
```
|
||||||
|
|
||||||
|
## Is there a demo?
|
||||||
|
|
||||||
|
Of course there is a demo! [Play with DOMPurify](https://cure53.de/purify)
|
||||||
|
|
||||||
|
## What if I find a _security_ bug?
|
||||||
|
|
||||||
|
First of all, please immediately contact us via [email](mailto:mario@cure53.de) so we can work on a fix. [PGP key](https://keyserver.ubuntu.com/pks/lookup?op=vindex&search=0xC26C858090F70ADA)
|
||||||
|
|
||||||
|
Also, you probably qualify for a bug bounty! The fine folks over at [Fastmail](https://www.fastmail.com/) use DOMPurify for their services and added our library to their bug bounty scope. So, if you find a way to bypass or weaken DOMPurify, please also have a look at their website and the [bug bounty info](https://www.fastmail.com/about/bugbounty/).
|
||||||
|
|
||||||
|
## Some purification samples please?
|
||||||
|
|
||||||
|
How does purified markup look like? Well, [the demo](https://cure53.de/purify) shows it for a big bunch of nasty elements. But let's also show some smaller examples!
|
||||||
|
|
||||||
|
```js
|
||||||
|
DOMPurify.sanitize('<img src=x onerror=alert(1)//>'); // becomes <img src="x">
|
||||||
|
DOMPurify.sanitize('<svg><g/onload=alert(2)//<p>'); // becomes <svg><g></g></svg>
|
||||||
|
DOMPurify.sanitize('<p>abc<iframe//src=jAva	script:alert(3)>def</p>'); // becomes <p>abc</p>
|
||||||
|
DOMPurify.sanitize('<math><mi//xlink:href="data:x,<script>alert(4)</script>">'); // becomes <math><mi></mi></math>
|
||||||
|
DOMPurify.sanitize('<TABLE><tr><td>HELLO</tr></TABL>'); // becomes <table><tbody><tr><td>HELLO</td></tr></tbody></table>
|
||||||
|
DOMPurify.sanitize('<UL><li><A HREF=//google.com>click</UL>'); // becomes <ul><li><a href="//google.com">click</a></li></ul>
|
||||||
|
```
|
||||||
|
|
||||||
|
## What is supported?
|
||||||
|
|
||||||
|
DOMPurify currently supports HTML5, SVG and MathML. DOMPurify per default allows CSS, HTML custom data attributes. DOMPurify also supports the Shadow DOM - and sanitizes DOM templates recursively. DOMPurify also allows you to sanitize HTML for being used with the jQuery `$()` and `elm.html()` API without any known problems.
|
||||||
|
|
||||||
|
## What about legacy browsers like Internet Explorer?
|
||||||
|
|
||||||
|
DOMPurify does nothing at all. It simply returns exactly the string that you fed it. DOMPurify exposes a property called `isSupported`, which tells you whether it will be able to do its job, so you can come up with your own backup plan.
|
||||||
|
|
||||||
|
## What about DOMPurify and Trusted Types?
|
||||||
|
|
||||||
|
In version 1.0.9, support for [Trusted Types API](https://github.com/w3c/webappsec-trusted-types) was added to DOMPurify.
|
||||||
|
In version 2.0.0, a config flag was added to control DOMPurify's behavior regarding this.
|
||||||
|
|
||||||
|
When `DOMPurify.sanitize` is used in an environment where the Trusted Types API is available and `RETURN_TRUSTED_TYPE` is set to `true`, it tries to return a `TrustedHTML` value instead of a string (the behavior for `RETURN_DOM` and `RETURN_DOM_FRAGMENT` config options does not change).
|
||||||
|
|
||||||
|
Note that in order to create a policy in `trustedTypes` using DOMPurify, `RETURN_TRUSTED_TYPE: false` is required, as `createHTML` expects a normal string, not `TrustedHTML`. The example below shows this.
|
||||||
|
|
||||||
|
```js
|
||||||
|
window.trustedTypes!.createPolicy('default', {
|
||||||
|
createHTML: (to_escape) =>
|
||||||
|
DOMPurify.sanitize(to_escape, { RETURN_TRUSTED_TYPE: false }),
|
||||||
|
});
|
||||||
|
```
|
||||||
|
|
||||||
|
## Can I configure DOMPurify?
|
||||||
|
|
||||||
|
Yes. The included default configuration values are pretty good already - but you can of course override them. Check out the [`/demos`](https://github.com/cure53/DOMPurify/tree/main/demos) folder to see a bunch of examples on how you can [customize DOMPurify](https://github.com/cure53/DOMPurify/tree/main/demos#what-is-this).
|
||||||
|
|
||||||
|
### General settings
|
||||||
|
```js
|
||||||
|
// strip {{ ... }}, ${ ... } and <% ... %> to make output safe for template systems
|
||||||
|
// be careful please, this mode is not recommended for production usage.
|
||||||
|
// allowing template parsing in user-controlled HTML is not advised at all.
|
||||||
|
// only use this mode if there is really no alternative.
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {SAFE_FOR_TEMPLATES: true});
|
||||||
|
|
||||||
|
|
||||||
|
// change how e.g. comments containing risky HTML characters are treated.
|
||||||
|
// be very careful, this setting should only be set to `false` if you really only handle
|
||||||
|
// HTML and nothing else, no SVG, MathML or the like.
|
||||||
|
// Otherwise, changing from `true` to `false` will lead to XSS in this or some other way.
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {SAFE_FOR_XML: false});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Control our allow-lists and block-lists
|
||||||
|
```js
|
||||||
|
// allow only <b> elements, very strict
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ALLOWED_TAGS: ['b']});
|
||||||
|
|
||||||
|
// allow only <b> and <q> with style attributes
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ALLOWED_TAGS: ['b', 'q'], ALLOWED_ATTR: ['style']});
|
||||||
|
|
||||||
|
// allow all safe HTML elements but neither SVG nor MathML
|
||||||
|
// note that the USE_PROFILES setting will override the ALLOWED_TAGS setting
|
||||||
|
// so don't use them together
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {html: true}});
|
||||||
|
|
||||||
|
// allow all safe SVG elements and SVG Filters, no HTML or MathML
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {svg: true, svgFilters: true}});
|
||||||
|
|
||||||
|
// allow all safe MathML elements and SVG, but no SVG Filters
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {USE_PROFILES: {mathMl: true, svg: true}});
|
||||||
|
|
||||||
|
// change the default namespace from HTML to something different
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {NAMESPACE: 'http://www.w3.org/2000/svg'});
|
||||||
|
|
||||||
|
// leave all safe HTML as it is and add <style> elements to block-list
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {FORBID_TAGS: ['style']});
|
||||||
|
|
||||||
|
// leave all safe HTML as it is and add style attributes to block-list
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {FORBID_ATTR: ['style']});
|
||||||
|
|
||||||
|
// extend the existing array of allowed tags and add <my-tag> to allow-list
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ADD_TAGS: ['my-tag']});
|
||||||
|
|
||||||
|
// extend the existing array of allowed attributes and add my-attr to allow-list
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ADD_ATTR: ['my-attr']});
|
||||||
|
|
||||||
|
// use functions to control which additional tags and attributes are allowed
|
||||||
|
const allowlist = {
|
||||||
|
'one': ['attribute-one'],
|
||||||
|
'two': ['attribute-two']
|
||||||
|
};
|
||||||
|
const clean = DOMPurify.sanitize(
|
||||||
|
'<one attribute-one="1" attribute-two="2"></one><two attribute-one="1" attribute-two="2"></two>',
|
||||||
|
{
|
||||||
|
ADD_TAGS: (tagName) => {
|
||||||
|
return Object.keys(allowlist).includes(tagName);
|
||||||
|
},
|
||||||
|
ADD_ATTR: (attributeName, tagName) => {
|
||||||
|
|
||||||
|
return allowlist[tagName]?.includes(attributeName) || false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
); // <one attribute-one="1"></one><two attribute-two="2"></two>
|
||||||
|
|
||||||
|
// prohibit ARIA attributes, leave other safe HTML as is (default is true)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ALLOW_ARIA_ATTR: false});
|
||||||
|
|
||||||
|
// prohibit HTML5 data attributes, leave other safe HTML as is (default is true)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ALLOW_DATA_ATTR: false});
|
||||||
|
```
|
||||||
|
|
||||||
|
### Control behavior relating to Custom Elements
|
||||||
|
```js
|
||||||
|
// DOMPurify allows to define rules for Custom Elements. When using the CUSTOM_ELEMENT_HANDLING
|
||||||
|
// literal, it is possible to define exactly what elements you wish to allow (by default, none are allowed).
|
||||||
|
//
|
||||||
|
// The same goes for their attributes. By default, the built-in or configured allow.list is used.
|
||||||
|
//
|
||||||
|
// You can use a RegExp literal to specify what is allowed or a predicate, examples for both can be seen below.
|
||||||
|
// When using a predicate function for attributeNameCheck, it can optionally receive the tagName as a second parameter
|
||||||
|
// for more granular control over which attributes are allowed for specific elements.
|
||||||
|
// The default values are very restrictive to prevent accidental XSS bypasses. Handle with great care!
|
||||||
|
|
||||||
|
const clean = DOMPurify.sanitize(
|
||||||
|
'<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
|
||||||
|
{
|
||||||
|
CUSTOM_ELEMENT_HANDLING: {
|
||||||
|
tagNameCheck: null, // no custom elements are allowed
|
||||||
|
attributeNameCheck: null, // default / standard attribute allow-list is used
|
||||||
|
allowCustomizedBuiltInElements: false, // no customized built-ins allowed
|
||||||
|
},
|
||||||
|
}
|
||||||
|
); // <div is=""></div>
|
||||||
|
|
||||||
|
const clean = DOMPurify.sanitize(
|
||||||
|
'<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
|
||||||
|
{
|
||||||
|
CUSTOM_ELEMENT_HANDLING: {
|
||||||
|
tagNameCheck: /^foo-/, // allow all tags starting with "foo-"
|
||||||
|
attributeNameCheck: /baz/, // allow all attributes containing "baz"
|
||||||
|
allowCustomizedBuiltInElements: true, // customized built-ins are allowed
|
||||||
|
},
|
||||||
|
}
|
||||||
|
); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div>
|
||||||
|
|
||||||
|
const clean = DOMPurify.sanitize(
|
||||||
|
'<foo-bar baz="foobar" forbidden="true"></foo-bar><div is="foo-baz"></div>',
|
||||||
|
{
|
||||||
|
CUSTOM_ELEMENT_HANDLING: {
|
||||||
|
tagNameCheck: (tagName) => tagName.match(/^foo-/), // allow all tags starting with "foo-"
|
||||||
|
attributeNameCheck: (attr) => attr.match(/baz/), // allow all containing "baz"
|
||||||
|
allowCustomizedBuiltInElements: true, // allow customized built-ins
|
||||||
|
},
|
||||||
|
}
|
||||||
|
); // <foo-bar baz="foobar"></foo-bar><div is="foo-baz"></div>
|
||||||
|
|
||||||
|
// Example with attributeNameCheck receiving tagName as a second parameter
|
||||||
|
const clean = DOMPurify.sanitize(
|
||||||
|
'<element-one attribute-one="1" attribute-two="2"></element-one><element-two attribute-one="1" attribute-two="2"></element-two>',
|
||||||
|
{
|
||||||
|
CUSTOM_ELEMENT_HANDLING: {
|
||||||
|
tagNameCheck: (tagName) => tagName.match(/^element-(one|two)$/),
|
||||||
|
attributeNameCheck: (attr, tagName) => {
|
||||||
|
if (tagName === 'element-one') {
|
||||||
|
return ['attribute-one'].includes(attr);
|
||||||
|
} else if (tagName === 'element-two') {
|
||||||
|
return ['attribute-two'].includes(attr);
|
||||||
|
} else {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
allowCustomizedBuiltInElements: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
); // <element-one attribute-one="1"></element-one><element-two attribute-two="2"></element-two>
|
||||||
|
```
|
||||||
|
### Control behavior relating to URI values
|
||||||
|
```js
|
||||||
|
// extend the existing array of elements that can use Data URIs
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ADD_DATA_URI_TAGS: ['a', 'area']});
|
||||||
|
|
||||||
|
// extend the existing array of elements that are safe for URI-like values (be careful, XSS risk)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ADD_URI_SAFE_ATTR: ['my-attr']});
|
||||||
|
|
||||||
|
```
|
||||||
|
### Control permitted attribute values
|
||||||
|
```js
|
||||||
|
// allow external protocol handlers in URL attributes (default is false, be careful, XSS risk)
|
||||||
|
// by default only http, https, ftp, ftps, tel, mailto, callto, sms, cid and xmpp are allowed.
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ALLOW_UNKNOWN_PROTOCOLS: true});
|
||||||
|
|
||||||
|
// allow specific protocols handlers in URL attributes via regex (default is false, be careful, XSS risk)
|
||||||
|
// by default only (protocol-)relative URLs, http, https, ftp, ftps, tel, mailto, callto, sms, cid, xmpp and matrix are allowed.
|
||||||
|
// Default RegExp: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i});
|
||||||
|
|
||||||
|
```
|
||||||
|
### Influence the return-type
|
||||||
|
```js
|
||||||
|
// return a DOM HTMLBodyElement instead of an HTML string (default is false)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {RETURN_DOM: true});
|
||||||
|
|
||||||
|
// return a DOM DocumentFragment instead of an HTML string (default is false)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {RETURN_DOM_FRAGMENT: true});
|
||||||
|
|
||||||
|
// use the RETURN_TRUSTED_TYPE flag to turn on Trusted Types support if available
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {RETURN_TRUSTED_TYPE: true}); // will return a TrustedHTML object instead of a string if possible
|
||||||
|
|
||||||
|
// use a provided Trusted Types policy
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {
|
||||||
|
// supplied policy must define createHTML and createScriptURL
|
||||||
|
TRUSTED_TYPES_POLICY: trustedTypes.createPolicy({
|
||||||
|
createHTML(s) { return s},
|
||||||
|
createScriptURL(s) { return s},
|
||||||
|
})
|
||||||
|
});
|
||||||
|
```
|
||||||
|
### Influence how we sanitize
|
||||||
|
```js
|
||||||
|
// return entire document including <html> tags (default is false)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {WHOLE_DOCUMENT: true});
|
||||||
|
|
||||||
|
// disable DOM Clobbering protection on output (default is true, handle with care, minor XSS risks here)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {SANITIZE_DOM: false});
|
||||||
|
|
||||||
|
// enforce strict DOM Clobbering protection via namespace isolation (default is false)
|
||||||
|
// when enabled, isolates the namespace of named properties (i.e., `id` and `name` attributes)
|
||||||
|
// from JS variables by prefixing them with the string `user-content-`
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {SANITIZE_NAMED_PROPS: true});
|
||||||
|
|
||||||
|
// keep an element's content when the element is removed (default is true)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {KEEP_CONTENT: false});
|
||||||
|
|
||||||
|
// glue elements like style, script or others to document.body and prevent unintuitive browser behavior in several edge-cases (default is false)
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {FORCE_BODY: true});
|
||||||
|
|
||||||
|
// remove all <a> elements under <p> elements that are removed
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {FORBID_CONTENTS: ['a'], FORBID_TAGS: ['p']});
|
||||||
|
|
||||||
|
// change the parser type so sanitized data is treated as XML and not as HTML, which is the default
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {PARSER_MEDIA_TYPE: 'application/xhtml+xml'});
|
||||||
|
```
|
||||||
|
### Influence where we sanitize
|
||||||
|
```js
|
||||||
|
// use the IN_PLACE mode to sanitize a node "in place", which is much faster depending on how you use DOMPurify
|
||||||
|
const dirty = document.createElement('a');
|
||||||
|
dirty.setAttribute('href', 'javascript:alert(1)');
|
||||||
|
|
||||||
|
const clean = DOMPurify.sanitize(dirty, {IN_PLACE: true}); // see https://github.com/cure53/DOMPurify/issues/288 for more info
|
||||||
|
```
|
||||||
|
|
||||||
|
There is even [more examples here](https://github.com/cure53/DOMPurify/tree/main/demos#what-is-this), showing how you can run, customize and configure DOMPurify to fit your needs.
|
||||||
|
|
||||||
|
## Persistent Configuration
|
||||||
|
|
||||||
|
Instead of repeatedly passing the same configuration to `DOMPurify.sanitize`, you can use the `DOMPurify.setConfig` method. Your configuration will persist until your next call to `DOMPurify.setConfig`, or until you invoke `DOMPurify.clearConfig` to reset it. Remember that there is only one active configuration, which means once it is set, all extra configuration parameters passed to `DOMPurify.sanitize` are ignored.
|
||||||
|
|
||||||
|
## Hooks
|
||||||
|
|
||||||
|
DOMPurify allows you to augment its functionality by attaching one or more functions with the `DOMPurify.addHook` method to one of the following hooks:
|
||||||
|
|
||||||
|
- `beforeSanitizeElements`
|
||||||
|
- `uponSanitizeElement` (No 's' - called for every element)
|
||||||
|
- `afterSanitizeElements`
|
||||||
|
- `beforeSanitizeAttributes`
|
||||||
|
- `uponSanitizeAttribute`
|
||||||
|
- `afterSanitizeAttributes`
|
||||||
|
- `beforeSanitizeShadowDOM`
|
||||||
|
- `uponSanitizeShadowNode`
|
||||||
|
- `afterSanitizeShadowDOM`
|
||||||
|
|
||||||
|
It passes the currently processed DOM node, when needed a literal with verified node and attribute data and the DOMPurify configuration to the callback. Check out the [MentalJS hook demo](https://github.com/cure53/DOMPurify/blob/main/demos/hooks-mentaljs-demo.html) to see how the API can be used nicely.
|
||||||
|
|
||||||
|
_Example_:
|
||||||
|
|
||||||
|
```js
|
||||||
|
DOMPurify.addHook(
|
||||||
|
'uponSanitizeAttribute',
|
||||||
|
function (currentNode, hookEvent, config) {
|
||||||
|
// Do something with the current node
|
||||||
|
// You can also mutate hookEvent for current node (i.e. set hookEvent.forceKeepAttr = true)
|
||||||
|
// For other than 'uponSanitizeAttribute' hook types hookEvent equals to null
|
||||||
|
}
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Removed Configuration
|
||||||
|
|
||||||
|
| Option | Since | Note |
|
||||||
|
|-----------------|-------|--------------------------|
|
||||||
|
| SAFE_FOR_JQUERY | 2.1.0 | No replacement required. |
|
||||||
|
|
||||||
|
## Continuous Integration
|
||||||
|
|
||||||
|
We are currently using Github Actions in combination with BrowserStack. This gives us the possibility to confirm for each and every commit that all is going according to plan in all supported browsers. Check out the build logs here: https://github.com/cure53/DOMPurify/actions
|
||||||
|
|
||||||
|
You can further run local tests by executing `npm run test`.
|
||||||
|
|
||||||
|
All relevant commits will be signed with the key `0x24BB6BF4` for additional security (since 8th of April 2016).
|
||||||
|
|
||||||
|
### Development and contributing
|
||||||
|
|
||||||
|
#### Installation (`npm i`)
|
||||||
|
|
||||||
|
We support `npm` officially. GitHub Actions workflow is configured to install dependencies using `npm`. When using deprecated version of `npm` we can not fully ensure the versions of installed dependencies which might lead to unanticipated problems.
|
||||||
|
|
||||||
|
#### Scripts
|
||||||
|
|
||||||
|
We rely on npm run-scripts for integrating with our tooling infrastructure. We use ESLint as a pre-commit hook to ensure code consistency. Moreover, to ease formatting we use [prettier](https://github.com/prettier/prettier) while building the `/dist` assets happens through `rollup`.
|
||||||
|
|
||||||
|
These are our npm scripts:
|
||||||
|
|
||||||
|
- `npm run dev` to start building while watching sources for changes
|
||||||
|
- `npm run test` to run our test suite via jsdom and karma
|
||||||
|
- `test:jsdom` to only run tests through jsdom
|
||||||
|
- `test:karma` to only run tests through karma
|
||||||
|
- `npm run lint` to lint the sources using ESLint (via xo)
|
||||||
|
- `npm run format` to format our sources using prettier to ease to pass ESLint
|
||||||
|
- `npm run build` to build our distribution assets minified and unminified as a UMD module
|
||||||
|
- `npm run build:umd` to only build an unminified UMD module
|
||||||
|
- `npm run build:umd:min` to only build a minified UMD module
|
||||||
|
|
||||||
|
Note: all run scripts triggered via `npm run <script>`.
|
||||||
|
|
||||||
|
There are more npm scripts but they are mainly to integrate with CI or are meant to be "private" for instance to amend build distribution files with every commit.
|
||||||
|
|
||||||
|
## Security Mailing List
|
||||||
|
|
||||||
|
We maintain a mailing list that notifies whenever a security-critical release of DOMPurify was published. This means, if someone found a bypass and we fixed it with a release (which always happens when a bypass was found) a mail will go out to that list. This usually happens within minutes or few hours after learning about a bypass. The list can be subscribed to here:
|
||||||
|
|
||||||
|
[https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security](https://lists.ruhr-uni-bochum.de/mailman/listinfo/dompurify-security)
|
||||||
|
|
||||||
|
Feature releases will not be announced to this list.
|
||||||
|
|
||||||
|
## Who contributed?
|
||||||
|
|
||||||
|
Many people helped and help DOMPurify become what it is and need to be acknowledged here!
|
||||||
|
|
||||||
|
[Cybozu 💛💸](https://github.com/cybozu), [hata6502 💸](https://github.com/hata6502), [intra-mart-dh 💸](https://github.com/intra-mart-dh), [nelstrom ❤️](https://github.com/nelstrom), [hash_kitten ❤️](https://twitter.com/hash_kitten), [kevin_mizu ❤️](https://twitter.com/kevin_mizu), [icesfont ❤️](https://github.com/icesfont), [reduckted ❤️](https://github.com/reduckted), [dcramer 💸](https://github.com/dcramer), [JGraph 💸](https://github.com/jgraph), [baekilda 💸](https://github.com/baekilda), [Healthchecks 💸](https://github.com/healthchecks), [Sentry 💸](https://github.com/getsentry), [jarrodldavis 💸](https://github.com/jarrodldavis), [CynegeticIO](https://github.com/CynegeticIO), [ssi02014 ❤️](https://github.com/ssi02014), [GrantGryczan](https://github.com/GrantGryczan), [Lowdefy](https://twitter.com/lowdefy), [granlem](https://twitter.com/MaximeVeit), [oreoshake](https://github.com/oreoshake), [tdeekens ❤️](https://github.com/tdeekens), [peernohell ❤️](https://github.com/peernohell), [is2ei](https://github.com/is2ei), [SoheilKhodayari](https://github.com/SoheilKhodayari), [franktopel](https://github.com/franktopel), [NateScarlet](https://github.com/NateScarlet), [neilj](https://github.com/neilj), [fhemberger](https://github.com/fhemberger), [Joris-van-der-Wel](https://github.com/Joris-van-der-Wel), [ydaniv](https://github.com/ydaniv), [terjanq](https://twitter.com/terjanq), [filedescriptor](https://github.com/filedescriptor), [ConradIrwin](https://github.com/ConradIrwin), [gibson042](https://github.com/gibson042), [choumx](https://github.com/choumx), [0xSobky](https://github.com/0xSobky), [styfle](https://github.com/styfle), [koto](https://github.com/koto), [tlau88](https://github.com/tlau88), [strugee](https://github.com/strugee), [oparoz](https://github.com/oparoz), [mathiasbynens](https://github.com/mathiasbynens), [edg2s](https://github.com/edg2s), [dnkolegov](https://github.com/dnkolegov), [dhardtke](https://github.com/dhardtke), [wirehead](https://github.com/wirehead), [thorn0](https://github.com/thorn0), [styu](https://github.com/styu), [mozfreddyb](https://github.com/mozfreddyb), [mikesamuel](https://github.com/mikesamuel), [jorangreef](https://github.com/jorangreef), [jimmyhchan](https://github.com/jimmyhchan), [jameydeorio](https://github.com/jameydeorio), [jameskraus](https://github.com/jameskraus), [hyderali](https://github.com/hyderali), [hansottowirtz](https://github.com/hansottowirtz), [hackvertor](https://github.com/hackvertor), [freddyb](https://github.com/freddyb), [flavorjones](https://github.com/flavorjones), [djfarrelly](https://github.com/djfarrelly), [devd](https://github.com/devd), [camerondunford](https://github.com/camerondunford), [buu700](https://github.com/buu700), [buildog](https://github.com/buildog), [alabiaga](https://github.com/alabiaga), [Vector919](https://github.com/Vector919), [Robbert](https://github.com/Robbert), [GreLI](https://github.com/GreLI), [FuzzySockets](https://github.com/FuzzySockets), [ArtemBernatskyy](https://github.com/ArtemBernatskyy), [@garethheyes](https://twitter.com/garethheyes), [@shafigullin](https://twitter.com/shafigullin), [@mmrupp](https://twitter.com/mmrupp), [@irsdl](https://twitter.com/irsdl),[ShikariSenpai](https://github.com/ShikariSenpai), [ansjdnakjdnajkd](https://github.com/ansjdnakjdnajkd), [@asutherland](https://twitter.com/asutherland), [@mathias](https://twitter.com/mathias), [@cgvwzq](https://twitter.com/cgvwzq), [@robbertatwork](https://twitter.com/robbertatwork), [@giutro](https://twitter.com/giutro), [@CmdEngineer\_](https://twitter.com/CmdEngineer_), [@avr4mit](https://twitter.com/avr4mit), [davecardwell](https://github.com/davecardwell) and especially [@securitymb ❤️](https://twitter.com/securitymb) & [@masatokinugawa ❤️](https://twitter.com/masatokinugawa)
|
||||||
|
|
||||||
|
## Testing powered by
|
||||||
|
|
||||||
|
<a target="_blank" href="https://www.browserstack.com/"><img width="200" src="https://github.com/cure53/DOMPurify/assets/6709482/f70be7eb-8fc4-41ea-9653-9d359235328f"></a><br>
|
||||||
|
|
||||||
|
And last but not least, thanks to [BrowserStack Open-Source Program](https://www.browserstack.com/open-source) for supporting this project with their services for free and delivering excellent, dedicated and very professional support on top of that.
|
||||||
|
|
@ -0,0 +1,446 @@
|
||||||
|
/*! @license DOMPurify 3.3.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.0/LICENSE */
|
||||||
|
|
||||||
|
import { TrustedTypePolicy, TrustedHTML, TrustedTypesWindow } from 'trusted-types/lib';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration to control DOMPurify behavior.
|
||||||
|
*/
|
||||||
|
interface Config {
|
||||||
|
/**
|
||||||
|
* Extend the existing array of allowed attributes.
|
||||||
|
* Can be an array of attribute names, or a function that receives
|
||||||
|
* the attribute name and tag name to determine if the attribute is allowed.
|
||||||
|
*/
|
||||||
|
ADD_ATTR?: string[] | ((attributeName: string, tagName: string) => boolean) | undefined;
|
||||||
|
/**
|
||||||
|
* Extend the existing array of elements that can use Data URIs.
|
||||||
|
*/
|
||||||
|
ADD_DATA_URI_TAGS?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Extend the existing array of allowed tags.
|
||||||
|
* Can be an array of tag names, or a function that receives
|
||||||
|
* the tag name to determine if the tag is allowed.
|
||||||
|
*/
|
||||||
|
ADD_TAGS?: string[] | ((tagName: string) => boolean) | undefined;
|
||||||
|
/**
|
||||||
|
* Extend the existing array of elements that are safe for URI-like values (be careful, XSS risk).
|
||||||
|
*/
|
||||||
|
ADD_URI_SAFE_ATTR?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Allow ARIA attributes, leave other safe HTML as is (default is true).
|
||||||
|
*/
|
||||||
|
ALLOW_ARIA_ATTR?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow HTML5 data attributes, leave other safe HTML as is (default is true).
|
||||||
|
*/
|
||||||
|
ALLOW_DATA_ATTR?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow external protocol handlers in URL attributes (default is false, be careful, XSS risk).
|
||||||
|
* By default only `http`, `https`, `ftp`, `ftps`, `tel`, `mailto`, `callto`, `sms`, `cid` and `xmpp` are allowed.
|
||||||
|
*/
|
||||||
|
ALLOW_UNKNOWN_PROTOCOLS?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Decide if self-closing tags in attributes are allowed.
|
||||||
|
* Usually removed due to a mXSS issue in jQuery 3.0.
|
||||||
|
*/
|
||||||
|
ALLOW_SELF_CLOSE_IN_ATTR?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow only specific attributes.
|
||||||
|
*/
|
||||||
|
ALLOWED_ATTR?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Allow only specific elements.
|
||||||
|
*/
|
||||||
|
ALLOWED_TAGS?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Allow only specific namespaces. Defaults to:
|
||||||
|
* - `http://www.w3.org/1999/xhtml`
|
||||||
|
* - `http://www.w3.org/2000/svg`
|
||||||
|
* - `http://www.w3.org/1998/Math/MathML`
|
||||||
|
*/
|
||||||
|
ALLOWED_NAMESPACES?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Allow specific protocols handlers in URL attributes via regex (be careful, XSS risk).
|
||||||
|
* Default RegExp:
|
||||||
|
* ```
|
||||||
|
* /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
ALLOWED_URI_REGEXP?: RegExp | undefined;
|
||||||
|
/**
|
||||||
|
* Define how custom elements are handled.
|
||||||
|
*/
|
||||||
|
CUSTOM_ELEMENT_HANDLING?: {
|
||||||
|
/**
|
||||||
|
* Regular expression or function to match to allowed elements.
|
||||||
|
* Default is null (disallow any custom elements).
|
||||||
|
*/
|
||||||
|
tagNameCheck?: RegExp | ((tagName: string) => boolean) | null | undefined;
|
||||||
|
/**
|
||||||
|
* Regular expression or function to match to allowed attributes.
|
||||||
|
* Default is null (disallow any attributes not on the allow list).
|
||||||
|
*/
|
||||||
|
attributeNameCheck?: RegExp | ((attributeName: string, tagName?: string) => boolean) | null | undefined;
|
||||||
|
/**
|
||||||
|
* Allow custom elements derived from built-ins if they pass `tagNameCheck`. Default is false.
|
||||||
|
*/
|
||||||
|
allowCustomizedBuiltInElements?: boolean | undefined;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Add attributes to block-list.
|
||||||
|
*/
|
||||||
|
FORBID_ATTR?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Add child elements to be removed when their parent is removed.
|
||||||
|
*/
|
||||||
|
FORBID_CONTENTS?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Add elements to block-list.
|
||||||
|
*/
|
||||||
|
FORBID_TAGS?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Glue elements like style, script or others to `document.body` and prevent unintuitive browser behavior in several edge-cases (default is false).
|
||||||
|
*/
|
||||||
|
FORCE_BODY?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Map of non-standard HTML element names to support. Map to true to enable support. For example:
|
||||||
|
*
|
||||||
|
* ```
|
||||||
|
* HTML_INTEGRATION_POINTS: { foreignobject: true }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
HTML_INTEGRATION_POINTS?: Record<string, boolean> | undefined;
|
||||||
|
/**
|
||||||
|
* Sanitize a node "in place", which is much faster depending on how you use DOMPurify.
|
||||||
|
*/
|
||||||
|
IN_PLACE?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Keep an element's content when the element is removed (default is true).
|
||||||
|
*/
|
||||||
|
KEEP_CONTENT?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Map of MathML element names to support. Map to true to enable support. For example:
|
||||||
|
*
|
||||||
|
* ```
|
||||||
|
* MATHML_TEXT_INTEGRATION_POINTS: { mtext: true }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
MATHML_TEXT_INTEGRATION_POINTS?: Record<string, boolean> | undefined;
|
||||||
|
/**
|
||||||
|
* Change the default namespace from HTML to something different.
|
||||||
|
*/
|
||||||
|
NAMESPACE?: string | undefined;
|
||||||
|
/**
|
||||||
|
* Change the parser type so sanitized data is treated as XML and not as HTML, which is the default.
|
||||||
|
*/
|
||||||
|
PARSER_MEDIA_TYPE?: DOMParserSupportedType | undefined;
|
||||||
|
/**
|
||||||
|
* Return a DOM `DocumentFragment` instead of an HTML string (default is false).
|
||||||
|
*/
|
||||||
|
RETURN_DOM_FRAGMENT?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Return a DOM `HTMLBodyElement` instead of an HTML string (default is false).
|
||||||
|
*/
|
||||||
|
RETURN_DOM?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Return a TrustedHTML object instead of a string if possible.
|
||||||
|
*/
|
||||||
|
RETURN_TRUSTED_TYPE?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Strip `{{ ... }}`, `${ ... }` and `<% ... %>` to make output safe for template systems.
|
||||||
|
* Be careful please, this mode is not recommended for production usage.
|
||||||
|
* Allowing template parsing in user-controlled HTML is not advised at all.
|
||||||
|
* Only use this mode if there is really no alternative.
|
||||||
|
*/
|
||||||
|
SAFE_FOR_TEMPLATES?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Change how e.g. comments containing risky HTML characters are treated.
|
||||||
|
* Be very careful, this setting should only be set to `false` if you really only handle
|
||||||
|
* HTML and nothing else, no SVG, MathML or the like.
|
||||||
|
* Otherwise, changing from `true` to `false` will lead to XSS in this or some other way.
|
||||||
|
*/
|
||||||
|
SAFE_FOR_XML?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Use DOM Clobbering protection on output (default is true, handle with care, minor XSS risks here).
|
||||||
|
*/
|
||||||
|
SANITIZE_DOM?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Enforce strict DOM Clobbering protection via namespace isolation (default is false).
|
||||||
|
* When enabled, isolates the namespace of named properties (i.e., `id` and `name` attributes)
|
||||||
|
* from JS variables by prefixing them with the string `user-content-`
|
||||||
|
*/
|
||||||
|
SANITIZE_NAMED_PROPS?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Supplied policy must define `createHTML` and `createScriptURL`.
|
||||||
|
*/
|
||||||
|
TRUSTED_TYPES_POLICY?: TrustedTypePolicy | undefined;
|
||||||
|
/**
|
||||||
|
* Controls categories of allowed elements.
|
||||||
|
*
|
||||||
|
* Note that the `USE_PROFILES` setting will override the `ALLOWED_TAGS` setting
|
||||||
|
* so don't use them together.
|
||||||
|
*/
|
||||||
|
USE_PROFILES?: false | UseProfilesConfig | undefined;
|
||||||
|
/**
|
||||||
|
* Return entire document including <html> tags (default is false).
|
||||||
|
*/
|
||||||
|
WHOLE_DOCUMENT?: boolean | undefined;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Defines categories of allowed elements.
|
||||||
|
*/
|
||||||
|
interface UseProfilesConfig {
|
||||||
|
/**
|
||||||
|
* Allow all safe MathML elements.
|
||||||
|
*/
|
||||||
|
mathMl?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow all safe SVG elements.
|
||||||
|
*/
|
||||||
|
svg?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow all save SVG Filters.
|
||||||
|
*/
|
||||||
|
svgFilters?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow all safe HTML elements.
|
||||||
|
*/
|
||||||
|
html?: boolean | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare const _default: DOMPurify;
|
||||||
|
|
||||||
|
interface DOMPurify {
|
||||||
|
/**
|
||||||
|
* Creates a DOMPurify instance using the given window-like object. Defaults to `window`.
|
||||||
|
*/
|
||||||
|
(root?: WindowLike): DOMPurify;
|
||||||
|
/**
|
||||||
|
* Version label, exposed for easier checks
|
||||||
|
* if DOMPurify is up to date or not
|
||||||
|
*/
|
||||||
|
version: string;
|
||||||
|
/**
|
||||||
|
* Array of elements that DOMPurify removed during sanitation.
|
||||||
|
* Empty if nothing was removed.
|
||||||
|
*/
|
||||||
|
removed: Array<RemovedElement | RemovedAttribute>;
|
||||||
|
/**
|
||||||
|
* Expose whether this browser supports running the full DOMPurify.
|
||||||
|
*/
|
||||||
|
isSupported: boolean;
|
||||||
|
/**
|
||||||
|
* Set the configuration once.
|
||||||
|
*
|
||||||
|
* @param cfg configuration object
|
||||||
|
*/
|
||||||
|
setConfig(cfg?: Config): void;
|
||||||
|
/**
|
||||||
|
* Removes the configuration.
|
||||||
|
*/
|
||||||
|
clearConfig(): void;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty string or DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized TrustedHTML.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: string | Node, cfg: Config & {
|
||||||
|
RETURN_TRUSTED_TYPE: true;
|
||||||
|
}): TrustedHTML;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized DOM node.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: Node, cfg: Config & {
|
||||||
|
IN_PLACE: true;
|
||||||
|
}): Node;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty string or DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized DOM node.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: string | Node, cfg: Config & {
|
||||||
|
RETURN_DOM: true;
|
||||||
|
}): Node;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty string or DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized document fragment.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: string | Node, cfg: Config & {
|
||||||
|
RETURN_DOM_FRAGMENT: true;
|
||||||
|
}): DocumentFragment;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty string or DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized string.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: string | Node, cfg?: Config): string;
|
||||||
|
/**
|
||||||
|
* Checks if an attribute value is valid.
|
||||||
|
* Uses last set config, if any. Otherwise, uses config defaults.
|
||||||
|
*
|
||||||
|
* @param tag Tag name of containing element.
|
||||||
|
* @param attr Attribute name.
|
||||||
|
* @param value Attribute value.
|
||||||
|
* @returns Returns true if `value` is valid. Otherwise, returns false.
|
||||||
|
*/
|
||||||
|
isValidAttribute(tag: string, attr: string, value: string): boolean;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: BasicHookName, hookFunction: NodeHook): void;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: ElementHookName, hookFunction: ElementHook): void;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: DocumentFragmentHookName, hookFunction: DocumentFragmentHook): void;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: 'uponSanitizeElement', hookFunction: UponSanitizeElementHook): void;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: 'uponSanitizeAttribute', hookFunction: UponSanitizeAttributeHook): void;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: BasicHookName, hookFunction?: NodeHook): NodeHook | undefined;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: ElementHookName, hookFunction?: ElementHook): ElementHook | undefined;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: DocumentFragmentHookName, hookFunction?: DocumentFragmentHook): DocumentFragmentHook | undefined;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: 'uponSanitizeElement', hookFunction?: UponSanitizeElementHook): UponSanitizeElementHook | undefined;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: 'uponSanitizeAttribute', hookFunction?: UponSanitizeAttributeHook): UponSanitizeAttributeHook | undefined;
|
||||||
|
/**
|
||||||
|
* Removes all DOMPurify hooks at a given entryPoint
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hooks to remove
|
||||||
|
*/
|
||||||
|
removeHooks(entryPoint: HookName): void;
|
||||||
|
/**
|
||||||
|
* Removes all DOMPurify hooks.
|
||||||
|
*/
|
||||||
|
removeAllHooks(): void;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* An element removed by DOMPurify.
|
||||||
|
*/
|
||||||
|
interface RemovedElement {
|
||||||
|
/**
|
||||||
|
* The element that was removed.
|
||||||
|
*/
|
||||||
|
element: Node;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* An element removed by DOMPurify.
|
||||||
|
*/
|
||||||
|
interface RemovedAttribute {
|
||||||
|
/**
|
||||||
|
* The attribute that was removed.
|
||||||
|
*/
|
||||||
|
attribute: Attr | null;
|
||||||
|
/**
|
||||||
|
* The element that the attribute was removed.
|
||||||
|
*/
|
||||||
|
from: Node;
|
||||||
|
}
|
||||||
|
type BasicHookName = 'beforeSanitizeElements' | 'afterSanitizeElements' | 'uponSanitizeShadowNode';
|
||||||
|
type ElementHookName = 'beforeSanitizeAttributes' | 'afterSanitizeAttributes';
|
||||||
|
type DocumentFragmentHookName = 'beforeSanitizeShadowDOM' | 'afterSanitizeShadowDOM';
|
||||||
|
type UponSanitizeElementHookName = 'uponSanitizeElement';
|
||||||
|
type UponSanitizeAttributeHookName = 'uponSanitizeAttribute';
|
||||||
|
type HookName = BasicHookName | ElementHookName | DocumentFragmentHookName | UponSanitizeElementHookName | UponSanitizeAttributeHookName;
|
||||||
|
type NodeHook = (this: DOMPurify, currentNode: Node, hookEvent: null, config: Config) => void;
|
||||||
|
type ElementHook = (this: DOMPurify, currentNode: Element, hookEvent: null, config: Config) => void;
|
||||||
|
type DocumentFragmentHook = (this: DOMPurify, currentNode: DocumentFragment, hookEvent: null, config: Config) => void;
|
||||||
|
type UponSanitizeElementHook = (this: DOMPurify, currentNode: Node, hookEvent: UponSanitizeElementHookEvent, config: Config) => void;
|
||||||
|
type UponSanitizeAttributeHook = (this: DOMPurify, currentNode: Element, hookEvent: UponSanitizeAttributeHookEvent, config: Config) => void;
|
||||||
|
interface UponSanitizeElementHookEvent {
|
||||||
|
tagName: string;
|
||||||
|
allowedTags: Record<string, boolean>;
|
||||||
|
}
|
||||||
|
interface UponSanitizeAttributeHookEvent {
|
||||||
|
attrName: string;
|
||||||
|
attrValue: string;
|
||||||
|
keepAttr: boolean;
|
||||||
|
allowedAttributes: Record<string, boolean>;
|
||||||
|
forceKeepAttr: boolean | undefined;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* A `Window`-like object containing the properties and types that DOMPurify requires.
|
||||||
|
*/
|
||||||
|
type WindowLike = Pick<typeof globalThis, 'DocumentFragment' | 'HTMLTemplateElement' | 'Node' | 'Element' | 'NodeFilter' | 'NamedNodeMap' | 'HTMLFormElement' | 'DOMParser'> & {
|
||||||
|
document?: Document;
|
||||||
|
MozNamedAttrMap?: typeof window.NamedNodeMap;
|
||||||
|
} & Pick<TrustedTypesWindow, 'trustedTypes'>;
|
||||||
|
|
||||||
|
export { type Config, type DOMPurify, type DocumentFragmentHook, type ElementHook, type HookName, type NodeHook, type RemovedAttribute, type RemovedElement, type UponSanitizeAttributeHook, type UponSanitizeAttributeHookEvent, type UponSanitizeElementHook, type UponSanitizeElementHookEvent, type WindowLike };
|
||||||
|
|
||||||
|
// @ts-ignore
|
||||||
|
export = _default;
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,443 @@
|
||||||
|
/*! @license DOMPurify 3.3.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.3.0/LICENSE */
|
||||||
|
|
||||||
|
import { TrustedTypePolicy, TrustedHTML, TrustedTypesWindow } from 'trusted-types/lib';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Configuration to control DOMPurify behavior.
|
||||||
|
*/
|
||||||
|
interface Config {
|
||||||
|
/**
|
||||||
|
* Extend the existing array of allowed attributes.
|
||||||
|
* Can be an array of attribute names, or a function that receives
|
||||||
|
* the attribute name and tag name to determine if the attribute is allowed.
|
||||||
|
*/
|
||||||
|
ADD_ATTR?: string[] | ((attributeName: string, tagName: string) => boolean) | undefined;
|
||||||
|
/**
|
||||||
|
* Extend the existing array of elements that can use Data URIs.
|
||||||
|
*/
|
||||||
|
ADD_DATA_URI_TAGS?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Extend the existing array of allowed tags.
|
||||||
|
* Can be an array of tag names, or a function that receives
|
||||||
|
* the tag name to determine if the tag is allowed.
|
||||||
|
*/
|
||||||
|
ADD_TAGS?: string[] | ((tagName: string) => boolean) | undefined;
|
||||||
|
/**
|
||||||
|
* Extend the existing array of elements that are safe for URI-like values (be careful, XSS risk).
|
||||||
|
*/
|
||||||
|
ADD_URI_SAFE_ATTR?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Allow ARIA attributes, leave other safe HTML as is (default is true).
|
||||||
|
*/
|
||||||
|
ALLOW_ARIA_ATTR?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow HTML5 data attributes, leave other safe HTML as is (default is true).
|
||||||
|
*/
|
||||||
|
ALLOW_DATA_ATTR?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow external protocol handlers in URL attributes (default is false, be careful, XSS risk).
|
||||||
|
* By default only `http`, `https`, `ftp`, `ftps`, `tel`, `mailto`, `callto`, `sms`, `cid` and `xmpp` are allowed.
|
||||||
|
*/
|
||||||
|
ALLOW_UNKNOWN_PROTOCOLS?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Decide if self-closing tags in attributes are allowed.
|
||||||
|
* Usually removed due to a mXSS issue in jQuery 3.0.
|
||||||
|
*/
|
||||||
|
ALLOW_SELF_CLOSE_IN_ATTR?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow only specific attributes.
|
||||||
|
*/
|
||||||
|
ALLOWED_ATTR?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Allow only specific elements.
|
||||||
|
*/
|
||||||
|
ALLOWED_TAGS?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Allow only specific namespaces. Defaults to:
|
||||||
|
* - `http://www.w3.org/1999/xhtml`
|
||||||
|
* - `http://www.w3.org/2000/svg`
|
||||||
|
* - `http://www.w3.org/1998/Math/MathML`
|
||||||
|
*/
|
||||||
|
ALLOWED_NAMESPACES?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Allow specific protocols handlers in URL attributes via regex (be careful, XSS risk).
|
||||||
|
* Default RegExp:
|
||||||
|
* ```
|
||||||
|
* /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i;
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
ALLOWED_URI_REGEXP?: RegExp | undefined;
|
||||||
|
/**
|
||||||
|
* Define how custom elements are handled.
|
||||||
|
*/
|
||||||
|
CUSTOM_ELEMENT_HANDLING?: {
|
||||||
|
/**
|
||||||
|
* Regular expression or function to match to allowed elements.
|
||||||
|
* Default is null (disallow any custom elements).
|
||||||
|
*/
|
||||||
|
tagNameCheck?: RegExp | ((tagName: string) => boolean) | null | undefined;
|
||||||
|
/**
|
||||||
|
* Regular expression or function to match to allowed attributes.
|
||||||
|
* Default is null (disallow any attributes not on the allow list).
|
||||||
|
*/
|
||||||
|
attributeNameCheck?: RegExp | ((attributeName: string, tagName?: string) => boolean) | null | undefined;
|
||||||
|
/**
|
||||||
|
* Allow custom elements derived from built-ins if they pass `tagNameCheck`. Default is false.
|
||||||
|
*/
|
||||||
|
allowCustomizedBuiltInElements?: boolean | undefined;
|
||||||
|
};
|
||||||
|
/**
|
||||||
|
* Add attributes to block-list.
|
||||||
|
*/
|
||||||
|
FORBID_ATTR?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Add child elements to be removed when their parent is removed.
|
||||||
|
*/
|
||||||
|
FORBID_CONTENTS?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Add elements to block-list.
|
||||||
|
*/
|
||||||
|
FORBID_TAGS?: string[] | undefined;
|
||||||
|
/**
|
||||||
|
* Glue elements like style, script or others to `document.body` and prevent unintuitive browser behavior in several edge-cases (default is false).
|
||||||
|
*/
|
||||||
|
FORCE_BODY?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Map of non-standard HTML element names to support. Map to true to enable support. For example:
|
||||||
|
*
|
||||||
|
* ```
|
||||||
|
* HTML_INTEGRATION_POINTS: { foreignobject: true }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
HTML_INTEGRATION_POINTS?: Record<string, boolean> | undefined;
|
||||||
|
/**
|
||||||
|
* Sanitize a node "in place", which is much faster depending on how you use DOMPurify.
|
||||||
|
*/
|
||||||
|
IN_PLACE?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Keep an element's content when the element is removed (default is true).
|
||||||
|
*/
|
||||||
|
KEEP_CONTENT?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Map of MathML element names to support. Map to true to enable support. For example:
|
||||||
|
*
|
||||||
|
* ```
|
||||||
|
* MATHML_TEXT_INTEGRATION_POINTS: { mtext: true }
|
||||||
|
* ```
|
||||||
|
*/
|
||||||
|
MATHML_TEXT_INTEGRATION_POINTS?: Record<string, boolean> | undefined;
|
||||||
|
/**
|
||||||
|
* Change the default namespace from HTML to something different.
|
||||||
|
*/
|
||||||
|
NAMESPACE?: string | undefined;
|
||||||
|
/**
|
||||||
|
* Change the parser type so sanitized data is treated as XML and not as HTML, which is the default.
|
||||||
|
*/
|
||||||
|
PARSER_MEDIA_TYPE?: DOMParserSupportedType | undefined;
|
||||||
|
/**
|
||||||
|
* Return a DOM `DocumentFragment` instead of an HTML string (default is false).
|
||||||
|
*/
|
||||||
|
RETURN_DOM_FRAGMENT?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Return a DOM `HTMLBodyElement` instead of an HTML string (default is false).
|
||||||
|
*/
|
||||||
|
RETURN_DOM?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Return a TrustedHTML object instead of a string if possible.
|
||||||
|
*/
|
||||||
|
RETURN_TRUSTED_TYPE?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Strip `{{ ... }}`, `${ ... }` and `<% ... %>` to make output safe for template systems.
|
||||||
|
* Be careful please, this mode is not recommended for production usage.
|
||||||
|
* Allowing template parsing in user-controlled HTML is not advised at all.
|
||||||
|
* Only use this mode if there is really no alternative.
|
||||||
|
*/
|
||||||
|
SAFE_FOR_TEMPLATES?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Change how e.g. comments containing risky HTML characters are treated.
|
||||||
|
* Be very careful, this setting should only be set to `false` if you really only handle
|
||||||
|
* HTML and nothing else, no SVG, MathML or the like.
|
||||||
|
* Otherwise, changing from `true` to `false` will lead to XSS in this or some other way.
|
||||||
|
*/
|
||||||
|
SAFE_FOR_XML?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Use DOM Clobbering protection on output (default is true, handle with care, minor XSS risks here).
|
||||||
|
*/
|
||||||
|
SANITIZE_DOM?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Enforce strict DOM Clobbering protection via namespace isolation (default is false).
|
||||||
|
* When enabled, isolates the namespace of named properties (i.e., `id` and `name` attributes)
|
||||||
|
* from JS variables by prefixing them with the string `user-content-`
|
||||||
|
*/
|
||||||
|
SANITIZE_NAMED_PROPS?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Supplied policy must define `createHTML` and `createScriptURL`.
|
||||||
|
*/
|
||||||
|
TRUSTED_TYPES_POLICY?: TrustedTypePolicy | undefined;
|
||||||
|
/**
|
||||||
|
* Controls categories of allowed elements.
|
||||||
|
*
|
||||||
|
* Note that the `USE_PROFILES` setting will override the `ALLOWED_TAGS` setting
|
||||||
|
* so don't use them together.
|
||||||
|
*/
|
||||||
|
USE_PROFILES?: false | UseProfilesConfig | undefined;
|
||||||
|
/**
|
||||||
|
* Return entire document including <html> tags (default is false).
|
||||||
|
*/
|
||||||
|
WHOLE_DOCUMENT?: boolean | undefined;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* Defines categories of allowed elements.
|
||||||
|
*/
|
||||||
|
interface UseProfilesConfig {
|
||||||
|
/**
|
||||||
|
* Allow all safe MathML elements.
|
||||||
|
*/
|
||||||
|
mathMl?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow all safe SVG elements.
|
||||||
|
*/
|
||||||
|
svg?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow all save SVG Filters.
|
||||||
|
*/
|
||||||
|
svgFilters?: boolean | undefined;
|
||||||
|
/**
|
||||||
|
* Allow all safe HTML elements.
|
||||||
|
*/
|
||||||
|
html?: boolean | undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
declare const _default: DOMPurify;
|
||||||
|
|
||||||
|
interface DOMPurify {
|
||||||
|
/**
|
||||||
|
* Creates a DOMPurify instance using the given window-like object. Defaults to `window`.
|
||||||
|
*/
|
||||||
|
(root?: WindowLike): DOMPurify;
|
||||||
|
/**
|
||||||
|
* Version label, exposed for easier checks
|
||||||
|
* if DOMPurify is up to date or not
|
||||||
|
*/
|
||||||
|
version: string;
|
||||||
|
/**
|
||||||
|
* Array of elements that DOMPurify removed during sanitation.
|
||||||
|
* Empty if nothing was removed.
|
||||||
|
*/
|
||||||
|
removed: Array<RemovedElement | RemovedAttribute>;
|
||||||
|
/**
|
||||||
|
* Expose whether this browser supports running the full DOMPurify.
|
||||||
|
*/
|
||||||
|
isSupported: boolean;
|
||||||
|
/**
|
||||||
|
* Set the configuration once.
|
||||||
|
*
|
||||||
|
* @param cfg configuration object
|
||||||
|
*/
|
||||||
|
setConfig(cfg?: Config): void;
|
||||||
|
/**
|
||||||
|
* Removes the configuration.
|
||||||
|
*/
|
||||||
|
clearConfig(): void;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty string or DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized TrustedHTML.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: string | Node, cfg: Config & {
|
||||||
|
RETURN_TRUSTED_TYPE: true;
|
||||||
|
}): TrustedHTML;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized DOM node.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: Node, cfg: Config & {
|
||||||
|
IN_PLACE: true;
|
||||||
|
}): Node;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty string or DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized DOM node.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: string | Node, cfg: Config & {
|
||||||
|
RETURN_DOM: true;
|
||||||
|
}): Node;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty string or DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized document fragment.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: string | Node, cfg: Config & {
|
||||||
|
RETURN_DOM_FRAGMENT: true;
|
||||||
|
}): DocumentFragment;
|
||||||
|
/**
|
||||||
|
* Provides core sanitation functionality.
|
||||||
|
*
|
||||||
|
* @param dirty string or DOM node
|
||||||
|
* @param cfg object
|
||||||
|
* @returns Sanitized string.
|
||||||
|
*/
|
||||||
|
sanitize(dirty: string | Node, cfg?: Config): string;
|
||||||
|
/**
|
||||||
|
* Checks if an attribute value is valid.
|
||||||
|
* Uses last set config, if any. Otherwise, uses config defaults.
|
||||||
|
*
|
||||||
|
* @param tag Tag name of containing element.
|
||||||
|
* @param attr Attribute name.
|
||||||
|
* @param value Attribute value.
|
||||||
|
* @returns Returns true if `value` is valid. Otherwise, returns false.
|
||||||
|
*/
|
||||||
|
isValidAttribute(tag: string, attr: string, value: string): boolean;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: BasicHookName, hookFunction: NodeHook): void;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: ElementHookName, hookFunction: ElementHook): void;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: DocumentFragmentHookName, hookFunction: DocumentFragmentHook): void;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: 'uponSanitizeElement', hookFunction: UponSanitizeElementHook): void;
|
||||||
|
/**
|
||||||
|
* Adds a DOMPurify hook.
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to add
|
||||||
|
* @param hookFunction function to execute
|
||||||
|
*/
|
||||||
|
addHook(entryPoint: 'uponSanitizeAttribute', hookFunction: UponSanitizeAttributeHook): void;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: BasicHookName, hookFunction?: NodeHook): NodeHook | undefined;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: ElementHookName, hookFunction?: ElementHook): ElementHook | undefined;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: DocumentFragmentHookName, hookFunction?: DocumentFragmentHook): DocumentFragmentHook | undefined;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: 'uponSanitizeElement', hookFunction?: UponSanitizeElementHook): UponSanitizeElementHook | undefined;
|
||||||
|
/**
|
||||||
|
* Remove a DOMPurify hook at a given entryPoint
|
||||||
|
* (pops it from the stack of hooks if hook not specified)
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hook to remove
|
||||||
|
* @param hookFunction optional specific hook to remove
|
||||||
|
* @returns removed hook
|
||||||
|
*/
|
||||||
|
removeHook(entryPoint: 'uponSanitizeAttribute', hookFunction?: UponSanitizeAttributeHook): UponSanitizeAttributeHook | undefined;
|
||||||
|
/**
|
||||||
|
* Removes all DOMPurify hooks at a given entryPoint
|
||||||
|
*
|
||||||
|
* @param entryPoint entry point for the hooks to remove
|
||||||
|
*/
|
||||||
|
removeHooks(entryPoint: HookName): void;
|
||||||
|
/**
|
||||||
|
* Removes all DOMPurify hooks.
|
||||||
|
*/
|
||||||
|
removeAllHooks(): void;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* An element removed by DOMPurify.
|
||||||
|
*/
|
||||||
|
interface RemovedElement {
|
||||||
|
/**
|
||||||
|
* The element that was removed.
|
||||||
|
*/
|
||||||
|
element: Node;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* An element removed by DOMPurify.
|
||||||
|
*/
|
||||||
|
interface RemovedAttribute {
|
||||||
|
/**
|
||||||
|
* The attribute that was removed.
|
||||||
|
*/
|
||||||
|
attribute: Attr | null;
|
||||||
|
/**
|
||||||
|
* The element that the attribute was removed.
|
||||||
|
*/
|
||||||
|
from: Node;
|
||||||
|
}
|
||||||
|
type BasicHookName = 'beforeSanitizeElements' | 'afterSanitizeElements' | 'uponSanitizeShadowNode';
|
||||||
|
type ElementHookName = 'beforeSanitizeAttributes' | 'afterSanitizeAttributes';
|
||||||
|
type DocumentFragmentHookName = 'beforeSanitizeShadowDOM' | 'afterSanitizeShadowDOM';
|
||||||
|
type UponSanitizeElementHookName = 'uponSanitizeElement';
|
||||||
|
type UponSanitizeAttributeHookName = 'uponSanitizeAttribute';
|
||||||
|
type HookName = BasicHookName | ElementHookName | DocumentFragmentHookName | UponSanitizeElementHookName | UponSanitizeAttributeHookName;
|
||||||
|
type NodeHook = (this: DOMPurify, currentNode: Node, hookEvent: null, config: Config) => void;
|
||||||
|
type ElementHook = (this: DOMPurify, currentNode: Element, hookEvent: null, config: Config) => void;
|
||||||
|
type DocumentFragmentHook = (this: DOMPurify, currentNode: DocumentFragment, hookEvent: null, config: Config) => void;
|
||||||
|
type UponSanitizeElementHook = (this: DOMPurify, currentNode: Node, hookEvent: UponSanitizeElementHookEvent, config: Config) => void;
|
||||||
|
type UponSanitizeAttributeHook = (this: DOMPurify, currentNode: Element, hookEvent: UponSanitizeAttributeHookEvent, config: Config) => void;
|
||||||
|
interface UponSanitizeElementHookEvent {
|
||||||
|
tagName: string;
|
||||||
|
allowedTags: Record<string, boolean>;
|
||||||
|
}
|
||||||
|
interface UponSanitizeAttributeHookEvent {
|
||||||
|
attrName: string;
|
||||||
|
attrValue: string;
|
||||||
|
keepAttr: boolean;
|
||||||
|
allowedAttributes: Record<string, boolean>;
|
||||||
|
forceKeepAttr: boolean | undefined;
|
||||||
|
}
|
||||||
|
/**
|
||||||
|
* A `Window`-like object containing the properties and types that DOMPurify requires.
|
||||||
|
*/
|
||||||
|
type WindowLike = Pick<typeof globalThis, 'DocumentFragment' | 'HTMLTemplateElement' | 'Node' | 'Element' | 'NodeFilter' | 'NamedNodeMap' | 'HTMLFormElement' | 'DOMParser'> & {
|
||||||
|
document?: Document;
|
||||||
|
MozNamedAttrMap?: typeof window.NamedNodeMap;
|
||||||
|
} & Pick<TrustedTypesWindow, 'trustedTypes'>;
|
||||||
|
|
||||||
|
export { type Config, type DOMPurify, type DocumentFragmentHook, type ElementHook, type HookName, type NodeHook, type RemovedAttribute, type RemovedElement, type UponSanitizeAttributeHook, type UponSanitizeAttributeHookEvent, type UponSanitizeElementHook, type UponSanitizeElementHookEvent, type WindowLike, _default as default };
|
||||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because it is too large
Load Diff
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
|
|
@ -0,0 +1,171 @@
|
||||||
|
{
|
||||||
|
"scripts": {
|
||||||
|
"lint": "xo src/*.ts",
|
||||||
|
"format": "npm run format:js && npm run format:md",
|
||||||
|
"format:md": "prettier --write --parser markdown '**/*.md'",
|
||||||
|
"format:js": "prettier --write '{src,demos,scripts,test,website}/*.{js,ts}'",
|
||||||
|
"commit-amend-build": "scripts/commit-amend-build.sh",
|
||||||
|
"prebuild": "rimraf dist/**",
|
||||||
|
"dev": "cross-env NODE_ENV=development BABEL_ENV=rollup rollup -w -c -o dist/purify.js",
|
||||||
|
"build": "run-s build:types build:rollup build:fix-types build:cleanup",
|
||||||
|
"build:types": "tsc --outDir dist/types --declaration --emitDeclarationOnly",
|
||||||
|
"build:rollup": "rollup -c",
|
||||||
|
"build:fix-types": "node ./scripts/fix-types.js",
|
||||||
|
"build:umd": "rollup -c -f umd -o dist/purify.js",
|
||||||
|
"build:umd:min": "rollup -c -f umd -o dist/purify.min.js -p terser",
|
||||||
|
"build:es": "rollup -c -f es -o dist/purify.es.mjs",
|
||||||
|
"build:cjs": "rollup -c -f cjs -o dist/purify.cjs.js",
|
||||||
|
"build:cleanup": "rimraf dist/types",
|
||||||
|
"test:jsdom": "cross-env NODE_ENV=test BABEL_ENV=rollup node test/jsdom-node-runner --dot",
|
||||||
|
"test:karma": "cross-env NODE_ENV=test BABEL_ENV=rollup karma start test/karma.conf.js --log-level warn ",
|
||||||
|
"test:ci": "cross-env NODE_ENV=test BABEL_ENV=rollup npm run test:jsdom && npm run test:karma -- --log-level error --reporters dots --single-run --shouldTestOnBrowserStack=\"${TEST_BROWSERSTACK}\" --shouldProbeOnly=\"${TEST_PROBE_ONLY}\"",
|
||||||
|
"test": "cross-env NODE_ENV=test BABEL_ENV=rollup npm run lint && npm run test:jsdom && npm run test:karma -- --browsers Chrome",
|
||||||
|
"verify-typescript": "node ./typescript/verify.js"
|
||||||
|
},
|
||||||
|
"main": "./dist/purify.cjs.js",
|
||||||
|
"module": "./dist/purify.es.mjs",
|
||||||
|
"browser": "./dist/purify.js",
|
||||||
|
"production": "./dist/purify.min.js",
|
||||||
|
"types": "./dist/purify.cjs.d.ts",
|
||||||
|
"exports": {
|
||||||
|
".": {
|
||||||
|
"import": {
|
||||||
|
"types": "./dist/purify.es.d.mts",
|
||||||
|
"default": "./dist/purify.es.mjs"
|
||||||
|
},
|
||||||
|
"default": {
|
||||||
|
"types": "./dist/purify.cjs.d.ts",
|
||||||
|
"default": "./dist/purify.cjs.js"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"./purify.min.js": "./dist/purify.min.js",
|
||||||
|
"./purify.js": "./dist/purify.js",
|
||||||
|
"./dist/purify.min.js": "./dist/purify.min.js",
|
||||||
|
"./dist/purify.js": "./dist/purify.js"
|
||||||
|
},
|
||||||
|
"files": [
|
||||||
|
"dist"
|
||||||
|
],
|
||||||
|
"pre-commit": [
|
||||||
|
"lint",
|
||||||
|
"build",
|
||||||
|
"commit-amend-build"
|
||||||
|
],
|
||||||
|
"xo": {
|
||||||
|
"semicolon": true,
|
||||||
|
"space": 2,
|
||||||
|
"extends": [
|
||||||
|
"prettier"
|
||||||
|
],
|
||||||
|
"plugins": [
|
||||||
|
"prettier"
|
||||||
|
],
|
||||||
|
"rules": {
|
||||||
|
"import/no-useless-path-segments": 0,
|
||||||
|
"unicorn/prefer-optional-catch-binding": 0,
|
||||||
|
"unicorn/prefer-node-remove": 0,
|
||||||
|
"prettier/prettier": [
|
||||||
|
"error",
|
||||||
|
{
|
||||||
|
"trailingComma": "es5",
|
||||||
|
"singleQuote": true
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"camelcase": [
|
||||||
|
"error",
|
||||||
|
{
|
||||||
|
"properties": "never"
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"@typescript-eslint/ban-types": 0,
|
||||||
|
"@typescript-eslint/consistent-type-definitions": 0,
|
||||||
|
"@typescript-eslint/indent": 0,
|
||||||
|
"@typescript-eslint/naming-convention": 0,
|
||||||
|
"@typescript-eslint/no-throw-literal": 0,
|
||||||
|
"@typescript-eslint/no-unnecessary-boolean-literal-compare": 0,
|
||||||
|
"@typescript-eslint/no-unsafe-argument": 0,
|
||||||
|
"@typescript-eslint/no-unsafe-assignment": 0,
|
||||||
|
"@typescript-eslint/no-unsafe-call": 0,
|
||||||
|
"@typescript-eslint/no-unsafe-return": 0,
|
||||||
|
"@typescript-eslint/prefer-includes": 0,
|
||||||
|
"@typescript-eslint/prefer-optional-chain": 0,
|
||||||
|
"@typescript-eslint/prefer-nullish-coalescing": 0,
|
||||||
|
"@typescript-eslint/restrict-plus-operands": 0
|
||||||
|
},
|
||||||
|
"globals": [
|
||||||
|
"window",
|
||||||
|
"VERSION"
|
||||||
|
]
|
||||||
|
},
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@types/trusted-types": "^2.0.7"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@babel/core": "^7.17.8",
|
||||||
|
"@babel/preset-env": "^7.16.11",
|
||||||
|
"@rollup/plugin-babel": "^6.0.4",
|
||||||
|
"@rollup/plugin-node-resolve": "^15.3.0",
|
||||||
|
"@rollup/plugin-replace": "^6.0.1",
|
||||||
|
"@rollup/plugin-terser": "^0.4.4",
|
||||||
|
"@types/estree": "^1.0.0",
|
||||||
|
"@types/node": "^16.18.120",
|
||||||
|
"cross-env": "^7.0.3",
|
||||||
|
"eslint-config-prettier": "^8.5.0",
|
||||||
|
"eslint-plugin-prettier": "^4.0.0",
|
||||||
|
"jquery": "^3.6.0",
|
||||||
|
"jsdom": "^20.0.0",
|
||||||
|
"karma": "^6.3.17",
|
||||||
|
"karma-browserstack-launcher": "^1.5.1",
|
||||||
|
"karma-chrome-launcher": "^3.1.0",
|
||||||
|
"karma-firefox-launcher": "^2.1.2",
|
||||||
|
"karma-qunit": "^4.1.2",
|
||||||
|
"karma-rollup-preprocessor": "^7.0.8",
|
||||||
|
"lodash.sample": "^4.2.1",
|
||||||
|
"minimist": "^1.2.6",
|
||||||
|
"npm-run-all": "^4.1.5",
|
||||||
|
"pre-commit": "^1.2.2",
|
||||||
|
"prettier": "^2.5.1",
|
||||||
|
"qunit": "^2.4.1",
|
||||||
|
"qunit-tap": "^1.5.0",
|
||||||
|
"rimraf": "^3.0.2",
|
||||||
|
"rollup": "^3.29.5",
|
||||||
|
"rollup-plugin-dts": "^6.1.1",
|
||||||
|
"rollup-plugin-includepaths": "^0.2.4",
|
||||||
|
"rollup-plugin-typescript2": "^0.36.0",
|
||||||
|
"tslib": "^2.7.0",
|
||||||
|
"typescript": "^5.6.3",
|
||||||
|
"xo": "^0.54.1"
|
||||||
|
},
|
||||||
|
"resolutions": {
|
||||||
|
"natives": "1.1.6"
|
||||||
|
},
|
||||||
|
"name": "dompurify",
|
||||||
|
"description": "DOMPurify is a DOM-only, super-fast, uber-tolerant XSS sanitizer for HTML, MathML and SVG. It's written in JavaScript and works in all modern browsers (Safari, Opera (15+), Internet Explorer (10+), Firefox and Chrome - as well as almost anything else using Blink or WebKit). DOMPurify is written by security people who have vast background in web attacks and XSS. Fear not.",
|
||||||
|
"version": "3.3.0",
|
||||||
|
"directories": {
|
||||||
|
"test": "test"
|
||||||
|
},
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "git://github.com/cure53/DOMPurify.git"
|
||||||
|
},
|
||||||
|
"keywords": [
|
||||||
|
"dom",
|
||||||
|
"xss",
|
||||||
|
"html",
|
||||||
|
"svg",
|
||||||
|
"mathml",
|
||||||
|
"security",
|
||||||
|
"secure",
|
||||||
|
"sanitizer",
|
||||||
|
"sanitize",
|
||||||
|
"filter",
|
||||||
|
"purify"
|
||||||
|
],
|
||||||
|
"author": "Dr.-Ing. Mario Heiderich, Cure53 <mario@cure53.de> (https://cure53.de/)",
|
||||||
|
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||||
|
"bugs": {
|
||||||
|
"url": "https://github.com/cure53/DOMPurify/issues"
|
||||||
|
},
|
||||||
|
"homepage": "https://github.com/cure53/DOMPurify"
|
||||||
|
}
|
||||||
|
|
@ -9,6 +9,7 @@
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.5.0",
|
"axios": "^1.5.0",
|
||||||
|
"dompurify": "^3.3.0",
|
||||||
"katex": "^0.16.22",
|
"katex": "^0.16.22",
|
||||||
"mammoth": "^1.10.0",
|
"mammoth": "^1.10.0",
|
||||||
"marked": "^16.2.1",
|
"marked": "^16.2.1",
|
||||||
|
|
@ -654,6 +655,13 @@
|
||||||
"node": ">= 10"
|
"node": ">= 10"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/@types/trusted-types": {
|
||||||
|
"version": "2.0.7",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||||
|
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"optional": true
|
||||||
|
},
|
||||||
"node_modules/@vitejs/plugin-vue": {
|
"node_modules/@vitejs/plugin-vue": {
|
||||||
"version": "4.6.2",
|
"version": "4.6.2",
|
||||||
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-4.6.2.tgz",
|
"resolved": "https://registry.npmjs.org/@vitejs/plugin-vue/-/plugin-vue-4.6.2.tgz",
|
||||||
|
|
@ -1441,6 +1449,15 @@
|
||||||
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
"url": "https://github.com/fb55/domhandler?sponsor=1"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
"node_modules/dompurify": {
|
||||||
|
"version": "3.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.3.0.tgz",
|
||||||
|
"integrity": "sha512-r+f6MYR1gGN1eJv0TVQbhA7if/U7P87cdPl3HN5rikqaBSBxLiCb/b9O+2eG0cxz0ghyU+mU1QkbsOwERMYlWQ==",
|
||||||
|
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||||
|
"optionalDependencies": {
|
||||||
|
"@types/trusted-types": "^2.0.7"
|
||||||
|
}
|
||||||
|
},
|
||||||
"node_modules/domutils": {
|
"node_modules/domutils": {
|
||||||
"version": "3.2.2",
|
"version": "3.2.2",
|
||||||
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
|
"resolved": "https://registry.npmjs.org/domutils/-/domutils-3.2.2.tgz",
|
||||||
|
|
|
||||||
|
|
@ -9,6 +9,7 @@
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"axios": "^1.5.0",
|
"axios": "^1.5.0",
|
||||||
|
"dompurify": "^3.3.0",
|
||||||
"katex": "^0.16.22",
|
"katex": "^0.16.22",
|
||||||
"mammoth": "^1.10.0",
|
"mammoth": "^1.10.0",
|
||||||
"marked": "^16.2.1",
|
"marked": "^16.2.1",
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,5 @@
|
||||||
<template>
|
<template>
|
||||||
<div id="app">« <!-- 测试模式切换按钮 -->
|
<div id="app">«
|
||||||
<div class="test-mode-toggle" style="display: none;">
|
|
||||||
<button @click="toggleTestMode" class="test-btn">
|
|
||||||
{{ isTestMode ? '切换到思维导图' : '测试Markdown渲染' }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 测试模式 -->
|
|
||||||
<div v-if="isTestMode" class="test-mode">
|
|
||||||
<MarkdownTest />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<!-- 正常模式 -->
|
|
||||||
<div v-else>
|
|
||||||
<!-- AI侧边栏 -->
|
<!-- AI侧边栏 -->
|
||||||
<AISidebar @start-realtime-generation="handleStartRealtimeGeneration" />
|
<AISidebar @start-realtime-generation="handleStartRealtimeGeneration" />
|
||||||
|
|
||||||
|
|
@ -21,22 +8,15 @@
|
||||||
<MindMap ref="mindMapRef" />
|
<MindMap ref="mindMapRef" />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
|
||||||
</template>
|
</template>
|
||||||
|
|
||||||
<script setup>
|
<script setup>
|
||||||
import { ref } from 'vue';
|
import { ref } from 'vue';
|
||||||
import MindMap from "./components/MindMap.vue";
|
import MindMap from "./components/MindMap.vue";
|
||||||
import AISidebar from "./components/AISidebar.vue";
|
import AISidebar from "./components/AISidebar.vue";
|
||||||
import MarkdownTest from "./components/MarkdownTest.vue";
|
|
||||||
|
|
||||||
const mindMapRef = ref(null);
|
const mindMapRef = ref(null);
|
||||||
const isTestMode = ref(false);
|
|
||||||
|
|
||||||
// 切换测试模式
|
|
||||||
const toggleTestMode = () => {
|
|
||||||
isTestMode.value = !isTestMode.value;
|
|
||||||
};
|
|
||||||
|
|
||||||
// 处理开始实时生成事件
|
// 处理开始实时生成事件
|
||||||
const handleStartRealtimeGeneration = () => {
|
const handleStartRealtimeGeneration = () => {
|
||||||
|
|
@ -118,4 +98,37 @@ body {
|
||||||
height: 100vh;
|
height: 100vh;
|
||||||
overflow: auto;
|
overflow: auto;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* 全局表格样式(作用于思维导图节点内渲染出的 table) */
|
||||||
|
.mind-elixir .map-container me-tpc table,
|
||||||
|
.mind-elixir .map-container me-tpc .text table,
|
||||||
|
.mind-elixir .map-container .topic table {
|
||||||
|
width: 100%;
|
||||||
|
table-layout: fixed !important;
|
||||||
|
border-collapse: collapse !important;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #d9d9d9 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mind-elixir .map-container me-tpc th,
|
||||||
|
.mind-elixir .map-container me-tpc td,
|
||||||
|
.mind-elixir .map-container me-tpc .text th,
|
||||||
|
.mind-elixir .map-container me-tpc .text td,
|
||||||
|
.mind-elixir .map-container .topic th,
|
||||||
|
.mind-elixir .map-container .topic td {
|
||||||
|
padding: 14px 18px !important;
|
||||||
|
text-align: left !important;
|
||||||
|
vertical-align: top !important;
|
||||||
|
border: 1px solid #d9d9d9 !important;
|
||||||
|
word-break: break-word !important;
|
||||||
|
white-space: normal !important;
|
||||||
|
line-height: 1.8 !important;
|
||||||
|
}
|
||||||
|
|
||||||
|
.mind-elixir .map-container me-tpc thead th,
|
||||||
|
.mind-elixir .map-container me-tpc .text thead th,
|
||||||
|
.mind-elixir .map-container .topic thead th {
|
||||||
|
background: #f5f5f5 !important;
|
||||||
|
font-weight: 600 !important;
|
||||||
|
}
|
||||||
</style>
|
</style>
|
||||||
|
|
|
||||||
|
|
@ -175,7 +175,8 @@ import {
|
||||||
renderMarkdownToHTML,
|
renderMarkdownToHTML,
|
||||||
createNodeSkeleton,
|
createNodeSkeleton,
|
||||||
renderNodeWithVditor,
|
renderNodeWithVditor,
|
||||||
updateNodeContent
|
updateNodeContent,
|
||||||
|
updateNodeModelAndRefresh
|
||||||
} from '../utils/markdownRenderer.js';
|
} from '../utils/markdownRenderer.js';
|
||||||
import Vditor from 'vditor';
|
import Vditor from 'vditor';
|
||||||
|
|
||||||
|
|
@ -403,16 +404,16 @@ const generateMarkdownFromFile = async () => {
|
||||||
- 图片描述要准确反映图片内容,图片路径可以是相对路径或占位符
|
- 图片描述要准确反映图片内容,图片路径可以是相对路径或占位符
|
||||||
- 确保图片占位符放在逻辑上合适的位置**
|
- 确保图片占位符放在逻辑上合适的位置**
|
||||||
7. **重要:如果原文档中包含表格,请完整保留表格结构:
|
7. **重要:如果原文档中包含表格,请完整保留表格结构:
|
||||||
- 保持表格的Markdown格式
|
- 简单表格(无合并单元格)请使用 GitHub-Flavored Markdown 表格语法:第二行为分隔线(如 | --- | :---: |),各行列数一致,表格块前后各空一行,单元格内换行使用 <br>,不要 4 空格/Tab 缩进。
|
||||||
- 确保所有表格行都被包含
|
- 需要合并单元格(colspan/rowspan)或结构复杂的表格,请输出"纯 HTML 表格",仅使用 <table><thead><tbody><tr><th><td> 与 <br>,正确设置 colspan/rowspan,禁止任何内联样式、脚本和事件属性;不要放入 \`\`\` 代码块。
|
||||||
- 不要省略任何表格内容
|
- 一律使用半角 ASCII 符号,禁止全角|、—、全角空格、NBSP/ZWSP 等特殊空白。
|
||||||
- 对于合并单元格的表格,请使用HTML格式并正确使用rowspan和colspan属性
|
- 绝对禁止将图片放在表格单元格内;图片必须与表格分离,位于表格之后的独立段落中。
|
||||||
- 如果表格结构复杂,优先使用HTML table标签而不是Markdown表格语法**
|
- 绝对禁止生成只有一个单元格的一整行表格项;若非表格内容(如段落/图片)请移出表格。**
|
||||||
8. **重要:确保内容完整性:
|
8. **重要:确保内容完整性:
|
||||||
- 不要截断任何内容
|
- 不要截断任何内容
|
||||||
- 保持原文的完整性
|
- 保持原文的完整性
|
||||||
- 所有重要信息都要包含在思维导图中**
|
- 所有重要信息都要包含在思维导图中**
|
||||||
9. 输出格式:直接输出Markdown内容,不要添加任何说明文字或代码块标记`;
|
9. 输出格式:直接输出内容,不要添加说明文字或代码块标记(若为 HTML 表格则直接输出 <table>,若为 Markdown 则直接输出 Markdown)。`;
|
||||||
const userPrompt = `请分析以下文档内容并生成结构化Markdown:\n\n${fileContent}`;
|
const userPrompt = `请分析以下文档内容并生成结构化Markdown:\n\n${fileContent}`;
|
||||||
|
|
||||||
// 关键修改:使用流式API而不是非流式API
|
// 关键修改:使用流式API而不是非流式API
|
||||||
|
|
@ -739,6 +740,13 @@ Level 4 标题用 #####
|
||||||
|
|
||||||
保持段落和换行不变。
|
保持段落和换行不变。
|
||||||
|
|
||||||
|
**重要:表格输出规则**:
|
||||||
|
- 无合并单元格时,使用 GitHub-Flavored Markdown 表格:第二行为分隔线(如 | --- | :---: |),各行列数一致,表格块前后各空一行,单元格内换行使用 <br>,不要 4 空格/Tab 缩进。
|
||||||
|
- 需要合并单元格(colspan/rowspan)或结构复杂时,ONLY 输出纯 HTML 表格,使用 <table><thead><tbody><tr><th><td> 与 <br>,正确设置 colspan/rowspan;禁止内联样式/脚本/事件属性;不要放入 \`\`\` 代码块。
|
||||||
|
- 一律使用半角 ASCII 符号,禁止全角|、—、全角空格、NBSP/ZWSP 等特殊空白。
|
||||||
|
- 不允许将图片放入表格单元格;图片需与表格分离、作为独立段落输出。
|
||||||
|
- 不允许出现单一表格项(单元格行);非表格段落/图片不得包入表格。
|
||||||
|
|
||||||
**重要:如果原文档中包含图片,请按以下方式处理:
|
**重要:如果原文档中包含图片,请按以下方式处理:
|
||||||
1. 识别图片在文档中的位置和上下文
|
1. 识别图片在文档中的位置和上下文
|
||||||
2. 根据图片内容生成准确的描述文字
|
2. 根据图片内容生成准确的描述文字
|
||||||
|
|
@ -746,7 +754,7 @@ Level 4 标题用 #####
|
||||||
4. 图片描述要准确反映图片内容,图片路径可以是相对路径或占位符
|
4. 图片描述要准确反映图片内容,图片路径可以是相对路径或占位符
|
||||||
5. 确保图片占位符放在逻辑上合适的位置**
|
5. 确保图片占位符放在逻辑上合适的位置**
|
||||||
|
|
||||||
输出格式: 输出必须是纯Markdown格式的文本,不得包含任何额外说明、JSON或非Markdown元素。确保输出与示例风格一致。直接输出Markdown内容,不要添加任何说明文字。`;
|
输出格式: 输出必须是纯Markdown或纯HTML表格,不得包含任何额外说明、JSON或非Markdown元素。直接输出内容,不要添加说明文字。`;
|
||||||
|
|
||||||
const finalSystemPrompt = systemPrompt || defaultSystemPrompt;
|
const finalSystemPrompt = systemPrompt || defaultSystemPrompt;
|
||||||
const finalUserPrompt = userPrompt || `请将以下内容转换为结构化的Markdown格式:`;
|
const finalUserPrompt = userPrompt || `请将以下内容转换为结构化的Markdown格式:`;
|
||||||
|
|
@ -991,6 +999,13 @@ Level 4 标题用 #####
|
||||||
|
|
||||||
保持段落和换行不变。
|
保持段落和换行不变。
|
||||||
|
|
||||||
|
**重要:表格输出规则**:
|
||||||
|
- 无合并单元格时,使用 GitHub-Flavored Markdown 表格:第二行为分隔线(如 | --- | :---: |),各行列数一致,表格块前后各空一行,单元格内换行使用 <br>,不要 4 空格/Tab 缩进。
|
||||||
|
- 需要合并单元格(colspan/rowspan)或结构复杂时,ONLY 输出纯 HTML 表格,使用 <table><thead><tbody><tr><th><td> 与 <br>,正确设置 colspan/rowspan;禁止内联样式/脚本/事件属性;不要放入 \`\`\` 代码块。
|
||||||
|
- 一律使用半角 ASCII 符号,禁止全角|、—、全角空格、NBSP/ZWSP 等特殊空白。
|
||||||
|
- 不允许将图片放入表格单元格;图片需与表格分离、作为独立段落输出。
|
||||||
|
- 不允许出现单一表格项(单元格行);非表格段落/图片不得包入表格。
|
||||||
|
|
||||||
**重要:如果原文档中包含图片,请按以下方式处理:
|
**重要:如果原文档中包含图片,请按以下方式处理:
|
||||||
1. 识别图片在文档中的位置和上下文
|
1. 识别图片在文档中的位置和上下文
|
||||||
2. 根据图片内容生成准确的描述文字
|
2. 根据图片内容生成准确的描述文字
|
||||||
|
|
@ -998,7 +1013,7 @@ Level 4 标题用 #####
|
||||||
4. 图片描述要准确反映图片内容,图片路径可以是相对路径或占位符
|
4. 图片描述要准确反映图片内容,图片路径可以是相对路径或占位符
|
||||||
5. 确保图片占位符放在逻辑上合适的位置**
|
5. 确保图片占位符放在逻辑上合适的位置**
|
||||||
|
|
||||||
输出格式: 输出必须是纯Markdown格式的文本,不得包含任何额外说明、JSON或非Markdown元素。确保输出与示例风格一致。直接输出Markdown内容,不要添加任何说明文字。`;
|
输出格式: 输出必须是纯Markdown或纯HTML表格,不得包含任何额外说明、JSON或非Markdown元素。直接输出内容,不要添加说明文字。`;
|
||||||
|
|
||||||
// 如果没有提供系统提示词,使用默认的
|
// 如果没有提供系统提示词,使用默认的
|
||||||
const finalSystemPrompt = systemPrompt || defaultSystemPrompt;
|
const finalSystemPrompt = systemPrompt || defaultSystemPrompt;
|
||||||
|
|
@ -1473,8 +1488,8 @@ const markdownToJSON = async (markdown) => {
|
||||||
// 使用Markdown格式存储图片内容,让Vditor异步渲染
|
// 使用Markdown格式存储图片内容,让Vditor异步渲染
|
||||||
const titleMarkdown = ``;
|
const titleMarkdown = ``;
|
||||||
|
|
||||||
node.topic = cleanTitle || '图片节点'; // 保留topic作为备用显示
|
node.topic = renderMarkdownToHTML(titleMarkdown);
|
||||||
node.dangerouslySetInnerHTML = titleMarkdown; // 存储Markdown,让Vditor渲染
|
node.markdown = titleMarkdown;
|
||||||
console.log(`✅ 成功为标题节点设置图片Markdown: ${titleMarkdown}`);
|
console.log(`✅ 成功为标题节点设置图片Markdown: ${titleMarkdown}`);
|
||||||
} else {
|
} else {
|
||||||
console.error(`❌ 标题图片URL无效:`, firstImage);
|
console.error(`❌ 标题图片URL无效:`, firstImage);
|
||||||
|
|
@ -1609,20 +1624,16 @@ const processContentIntelligently = async (content, parentNode, nodeCounter, dep
|
||||||
|
|
||||||
const imageNode = {
|
const imageNode = {
|
||||||
id: `node_${nodeCounter++}`,
|
id: `node_${nodeCounter++}`,
|
||||||
topic: image.alt || '图片节点', // 保留topic作为备用显示
|
topic: renderMarkdownToHTML(imageMarkdown),
|
||||||
dangerouslySetInnerHTML: imageMarkdown, // 存储Markdown,让Vditor渲染
|
markdown: imageMarkdown,
|
||||||
|
dangerouslySetInnerHTML: renderMarkdownToHTML(imageMarkdown),
|
||||||
children: [],
|
children: [],
|
||||||
level: (parentNode.level || 0) + 1,
|
level: (parentNode.level || 0) + 1,
|
||||||
data: {},
|
data: {},
|
||||||
expanded: true // 🔧 关键修复:确保图片节点展开
|
expanded: true // 🔧 关键修复:确保图片节点展开
|
||||||
};
|
};
|
||||||
|
// 同步模型(无刷新实例时跳过)
|
||||||
// 验证图片节点数据
|
updateNodeModelAndRefresh(imageNode, imageMarkdown);
|
||||||
if (!imageUrl || imageUrl.trim() === '') {
|
|
||||||
console.error(`❌ 图片节点 ${index + 1} URL为空:`, imageNode);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
parentNode.children.push(imageNode);
|
parentNode.children.push(imageNode);
|
||||||
console.log(`✅ 成功创建图片节点: ${image.alt || `图片 ${index + 1}`} - ${imageUrl}`);
|
console.log(`✅ 成功创建图片节点: ${image.alt || `图片 ${index + 1}`} - ${imageUrl}`);
|
||||||
});
|
});
|
||||||
|
|
@ -1636,7 +1647,8 @@ const processContentIntelligently = async (content, parentNode, nodeCounter, dep
|
||||||
// 没有更多图片,直接作为文本节点处理
|
// 没有更多图片,直接作为文本节点处理
|
||||||
const textNode = {
|
const textNode = {
|
||||||
id: `node_${nodeCounter++}`,
|
id: `node_${nodeCounter++}`,
|
||||||
topic: contentWithoutImages.trim(), // 保留完整内容
|
topic: renderMarkdownToHTML(contentWithoutImages.trim()),
|
||||||
|
markdown: contentWithoutImages.trim(),
|
||||||
children: [],
|
children: [],
|
||||||
level: (parentNode.level || 0) + 1,
|
level: (parentNode.level || 0) + 1,
|
||||||
data: {},
|
data: {},
|
||||||
|
|
@ -1657,14 +1669,15 @@ const processContentIntelligently = async (content, parentNode, nodeCounter, dep
|
||||||
|
|
||||||
const tableNode = {
|
const tableNode = {
|
||||||
id: `node_${nodeCounter++}`,
|
id: `node_${nodeCounter++}`,
|
||||||
topic: '', // 清空topic,使用dangerouslySetInnerHTML
|
topic: renderMarkdownToHTML(content),
|
||||||
dangerouslySetInnerHTML: content, // 直接存储Markdown内容,让Vditor异步渲染
|
markdown: content,
|
||||||
|
dangerouslySetInnerHTML: renderMarkdownToHTML(content),
|
||||||
children: [],
|
children: [],
|
||||||
level: (parentNode.level || 0) + 1,
|
level: (parentNode.level || 0) + 1,
|
||||||
data: {},
|
data: {},
|
||||||
expanded: true // 🔧 关键修复:确保表格节点展开
|
expanded: true // 🔧 关键修复:确保表格节点展开
|
||||||
};
|
};
|
||||||
|
updateNodeModelAndRefresh(tableNode, content);
|
||||||
parentNode.children.push(tableNode);
|
parentNode.children.push(tableNode);
|
||||||
return { nodeCounter };
|
return { nodeCounter };
|
||||||
}
|
}
|
||||||
|
|
@ -1684,7 +1697,8 @@ const processContentIntelligently = async (content, parentNode, nodeCounter, dep
|
||||||
const leafTitle = leafMatch[1].trim();
|
const leafTitle = leafMatch[1].trim();
|
||||||
const leafNode = {
|
const leafNode = {
|
||||||
id: `node_${currentNodeCounter++}`,
|
id: `node_${currentNodeCounter++}`,
|
||||||
topic: leafTitle,
|
topic: renderMarkdownToHTML(leafTitle),
|
||||||
|
markdown: leafTitle,
|
||||||
children: [],
|
children: [],
|
||||||
level: (parentNode.level || 0) + 1,
|
level: (parentNode.level || 0) + 1,
|
||||||
data: {},
|
data: {},
|
||||||
|
|
@ -1740,14 +1754,15 @@ const processContentIntelligently = async (content, parentNode, nodeCounter, dep
|
||||||
|
|
||||||
const tableNode = {
|
const tableNode = {
|
||||||
id: `node_${currentNodeCounter++}`,
|
id: `node_${currentNodeCounter++}`,
|
||||||
topic: image.alt || '图片节点', // 保留topic作为备用显示
|
topic: renderMarkdownToHTML(finalContent),
|
||||||
dangerouslySetInnerHTML: finalContent, // 直接存储Markdown内容,让Vditor异步渲染
|
markdown: finalContent,
|
||||||
|
dangerouslySetInnerHTML: renderMarkdownToHTML(finalContent),
|
||||||
children: [],
|
children: [],
|
||||||
level: (parentNode.level || 0) + 1,
|
level: (parentNode.level || 0) + 1,
|
||||||
data: {},
|
data: {},
|
||||||
expanded: true
|
expanded: true
|
||||||
};
|
};
|
||||||
|
updateNodeModelAndRefresh(tableNode, finalContent);
|
||||||
parentNode.children.push(tableNode);
|
parentNode.children.push(tableNode);
|
||||||
} else {
|
} else {
|
||||||
// 如果不是表格,按换行符切分内容
|
// 如果不是表格,按换行符切分内容
|
||||||
|
|
@ -1758,13 +1773,15 @@ const processContentIntelligently = async (content, parentNode, nodeCounter, dep
|
||||||
if (cleanParagraph) {
|
if (cleanParagraph) {
|
||||||
const paragraphNode = {
|
const paragraphNode = {
|
||||||
id: `node_${currentNodeCounter++}`,
|
id: `node_${currentNodeCounter++}`,
|
||||||
topic: cleanParagraph,
|
topic: renderMarkdownToHTML(cleanParagraph),
|
||||||
|
markdown: cleanParagraph,
|
||||||
|
dangerouslySetInnerHTML: renderMarkdownToHTML(cleanParagraph),
|
||||||
children: [],
|
children: [],
|
||||||
level: (parentNode.level || 0) + 1,
|
level: (parentNode.level || 0) + 1,
|
||||||
data: {},
|
data: {},
|
||||||
expanded: true
|
expanded: true
|
||||||
};
|
};
|
||||||
|
updateNodeModelAndRefresh(paragraphNode, cleanParagraph);
|
||||||
parentNode.children.push(paragraphNode);
|
parentNode.children.push(paragraphNode);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
|
||||||
|
|
@ -1,228 +0,0 @@
|
||||||
<template>
|
|
||||||
<div class="markdown-test">
|
|
||||||
<h2>Markdown渲染测试</h2>
|
|
||||||
|
|
||||||
<div class="test-section">
|
|
||||||
<h3>输入Markdown内容</h3>
|
|
||||||
<textarea
|
|
||||||
v-model="markdownInput"
|
|
||||||
placeholder="输入markdown内容..."
|
|
||||||
rows="10"
|
|
||||||
class="markdown-input"
|
|
||||||
></textarea>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="test-section">
|
|
||||||
<h3>渲染结果</h3>
|
|
||||||
<div class="rendered-content" v-html="renderedHTML"></div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div class="test-section">
|
|
||||||
<h3>测试用例</h3>
|
|
||||||
<button @click="loadTestCases" class="test-btn">加载测试用例</button>
|
|
||||||
<div class="test-cases">
|
|
||||||
<button
|
|
||||||
v-for="(testCase, index) in testCases"
|
|
||||||
:key="index"
|
|
||||||
@click="loadTestCase(testCase)"
|
|
||||||
class="test-case-btn"
|
|
||||||
>
|
|
||||||
{{ testCase.name }}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
</template>
|
|
||||||
|
|
||||||
<script setup>
|
|
||||||
import { ref, computed } from 'vue';
|
|
||||||
import { renderMarkdownToHTML, hasMarkdownSyntax } from '../utils/markdownRenderer.js';
|
|
||||||
|
|
||||||
// 响应式数据
|
|
||||||
const markdownInput = ref(`# 测试标题
|
|
||||||
|
|
||||||
这是一个**粗体**和*斜体*的测试。
|
|
||||||
|
|
||||||
## 表格测试
|
|
||||||
|
|
||||||
| 产品 | 价格 | 库存 |
|
|
||||||
|------|------|------|
|
|
||||||
| 苹果 | 4元 | 100个 |
|
|
||||||
| 香蕉 | 2元 | 50个 |
|
|
||||||
|
|
||||||
## 代码测试
|
|
||||||
|
|
||||||
\`\`\`javascript
|
|
||||||
function hello() {
|
|
||||||
console.log('Hello World!');
|
|
||||||
}
|
|
||||||
\`\`\`
|
|
||||||
|
|
||||||
行内代码:\`const name = 'test'\`
|
|
||||||
|
|
||||||
## 列表测试
|
|
||||||
|
|
||||||
- 项目1
|
|
||||||
- 项目2
|
|
||||||
- 子项目2.1
|
|
||||||
- 子项目2.2
|
|
||||||
- 项目3
|
|
||||||
|
|
||||||
## 链接测试
|
|
||||||
|
|
||||||
- [GitHub](https://github.com)
|
|
||||||
- [Vue.js](https://vuejs.org)`);
|
|
||||||
|
|
||||||
// 测试用例
|
|
||||||
const testCases = ref([
|
|
||||||
{
|
|
||||||
name: '基础表格',
|
|
||||||
content: `# 产品价格表
|
|
||||||
|
|
||||||
| 产品 | 价格 |
|
|
||||||
|------|------|
|
|
||||||
| 苹果 | 4元 |
|
|
||||||
| 香蕉 | 2元 |`
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: '复杂表格',
|
|
||||||
content: `# 技术栈对比
|
|
||||||
|
|
||||||
| 技术 | 前端 | 后端 | 数据库 |
|
|
||||||
|------|------|------|--------|
|
|
||||||
| Vue.js | ✅ | ❌ | ❌ |
|
|
||||||
| Django | ❌ | ✅ | ❌ |
|
|
||||||
| PostgreSQL | ❌ | ❌ | ✅ |`
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: '代码块',
|
|
||||||
content: `# 代码示例
|
|
||||||
|
|
||||||
\`\`\`javascript
|
|
||||||
function markdownToJSON(markdown) {
|
|
||||||
const lines = markdown.split('\\n');
|
|
||||||
// 处理逻辑...
|
|
||||||
return result;
|
|
||||||
}
|
|
||||||
\`\`\``
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: '混合内容',
|
|
||||||
content: `# 混合内容测试
|
|
||||||
|
|
||||||
这是一个包含**粗体**、*斜体*和\`行内代码\`的段落。
|
|
||||||
|
|
||||||
## 表格
|
|
||||||
|
|
||||||
| 功能 | 状态 | 说明 |
|
|
||||||
|------|------|------|
|
|
||||||
| 表格渲染 | ✅ | 支持markdown表格 |
|
|
||||||
| 代码高亮 | ✅ | 支持代码块 |
|
|
||||||
|
|
||||||
## 代码
|
|
||||||
|
|
||||||
\`\`\`python
|
|
||||||
def hello_world():
|
|
||||||
print("Hello, World!")
|
|
||||||
\`\`\``
|
|
||||||
}
|
|
||||||
]);
|
|
||||||
|
|
||||||
// 计算属性:渲染后的HTML
|
|
||||||
const renderedHTML = computed(() => {
|
|
||||||
if (!markdownInput.value) return '';
|
|
||||||
|
|
||||||
try {
|
|
||||||
return renderMarkdownToHTML(markdownInput.value);
|
|
||||||
} catch (error) {
|
|
||||||
return `<div class="error">渲染失败: ${error.message}</div>`;
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// 方法
|
|
||||||
const loadTestCases = () => {
|
|
||||||
// 测试用例已经定义在响应式数据中
|
|
||||||
};
|
|
||||||
|
|
||||||
const loadTestCase = (testCase) => {
|
|
||||||
markdownInput.value = testCase.content;
|
|
||||||
};
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<style scoped>
|
|
||||||
.markdown-test {
|
|
||||||
max-width: 1200px;
|
|
||||||
margin: 0 auto;
|
|
||||||
padding: 20px;
|
|
||||||
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
|
||||||
}
|
|
||||||
|
|
||||||
.test-section {
|
|
||||||
margin-bottom: 30px;
|
|
||||||
padding: 20px;
|
|
||||||
border: 1px solid #e0e0e0;
|
|
||||||
border-radius: 8px;
|
|
||||||
background: #f9f9f9;
|
|
||||||
}
|
|
||||||
|
|
||||||
.markdown-input {
|
|
||||||
width: 100%;
|
|
||||||
padding: 12px;
|
|
||||||
border: 1px solid #ddd;
|
|
||||||
border-radius: 4px;
|
|
||||||
font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
|
|
||||||
font-size: 14px;
|
|
||||||
line-height: 1.5;
|
|
||||||
resize: vertical;
|
|
||||||
}
|
|
||||||
|
|
||||||
.rendered-content {
|
|
||||||
background: white;
|
|
||||||
padding: 20px;
|
|
||||||
border-radius: 4px;
|
|
||||||
border: 1px solid #ddd;
|
|
||||||
min-height: 200px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.test-cases {
|
|
||||||
display: flex;
|
|
||||||
flex-wrap: wrap;
|
|
||||||
gap: 10px;
|
|
||||||
margin-top: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.test-btn,
|
|
||||||
.test-case-btn {
|
|
||||||
padding: 8px 16px;
|
|
||||||
border: 1px solid #007bff;
|
|
||||||
background: white;
|
|
||||||
color: #007bff;
|
|
||||||
border-radius: 4px;
|
|
||||||
cursor: pointer;
|
|
||||||
transition: all 0.2s ease;
|
|
||||||
}
|
|
||||||
|
|
||||||
.test-btn:hover,
|
|
||||||
.test-case-btn:hover {
|
|
||||||
background: #007bff;
|
|
||||||
color: white;
|
|
||||||
}
|
|
||||||
|
|
||||||
h2, h3 {
|
|
||||||
color: #333;
|
|
||||||
margin-bottom: 15px;
|
|
||||||
}
|
|
||||||
|
|
||||||
h2 {
|
|
||||||
border-bottom: 2px solid #007bff;
|
|
||||||
padding-bottom: 10px;
|
|
||||||
}
|
|
||||||
|
|
||||||
.error {
|
|
||||||
color: #dc3545;
|
|
||||||
background: #f8d7da;
|
|
||||||
border: 1px solid #f5c6cb;
|
|
||||||
padding: 10px;
|
|
||||||
border-radius: 4px;
|
|
||||||
}
|
|
||||||
</style>
|
|
||||||
|
|
@ -206,7 +206,7 @@ import { ref, onMounted, onUnmounted, nextTick } from 'vue';
|
||||||
import VditorEditor from './VditorEditor.vue';
|
import VditorEditor from './VditorEditor.vue';
|
||||||
import MindElixir from '../lib/mind-elixir/dist/MindElixir.js';
|
import MindElixir from '../lib/mind-elixir/dist/MindElixir.js';
|
||||||
import '../lib/mind-elixir/dist/style.css';
|
import '../lib/mind-elixir/dist/style.css';
|
||||||
import { renderMarkdownToHTML } from '../utils/markdownRenderer.js';
|
import { renderMarkdownToHTML, updateNodeModelAndRefresh } from '../utils/markdownRenderer.js';
|
||||||
import Vditor from 'vditor';
|
import Vditor from 'vditor';
|
||||||
import 'vditor/dist/index.css';
|
import 'vditor/dist/index.css';
|
||||||
import { marked } from 'marked';
|
import { marked } from 'marked';
|
||||||
|
|
@ -725,7 +725,6 @@ const convertHTMLToMarkdownImproved = (html) => {
|
||||||
return html; // 回退到原始HTML
|
return html; // 回退到原始HTML
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 富文本编辑器相关函数
|
// 富文本编辑器相关函数
|
||||||
const openRichTextEditor = (nodeObj, nodeElement) => {
|
const openRichTextEditor = (nodeObj, nodeElement) => {
|
||||||
console.log('📝 打开富文本编辑器:', { nodeObj, nodeElement });
|
console.log('📝 打开富文本编辑器:', { nodeObj, nodeElement });
|
||||||
|
|
@ -745,7 +744,7 @@ const openRichTextEditor = (nodeObj, nodeElement) => {
|
||||||
console.log('📝 节点完整数据:', {
|
console.log('📝 节点完整数据:', {
|
||||||
title: nodeObj.title,
|
title: nodeObj.title,
|
||||||
topic: nodeObj.topic,
|
topic: nodeObj.topic,
|
||||||
dangerouslySetInnerHTML: nodeObj.dangerouslySetInnerHTML,
|
// 兼容字段(已废弃):dangerouslySetInnerHTML
|
||||||
image: nodeObj.image,
|
image: nodeObj.image,
|
||||||
hasImage: !!nodeObj.image,
|
hasImage: !!nodeObj.image,
|
||||||
htmlContent: nodeObj.htmlContent,
|
htmlContent: nodeObj.htmlContent,
|
||||||
|
|
@ -755,52 +754,70 @@ const openRichTextEditor = (nodeObj, nodeElement) => {
|
||||||
// 使用新的节点结构逻辑
|
// 使用新的节点结构逻辑
|
||||||
let htmlContent = '';
|
let htmlContent = '';
|
||||||
|
|
||||||
// 优先使用dangerouslySetInnerHTML(用于WYSIWYG编辑)
|
// 优先使用节点的 topic 作为 HTML 内容
|
||||||
if (nodeObj.dangerouslySetInnerHTML) {
|
if (nodeObj.topic && /<\w+[^>]*>/.test(nodeObj.topic)) {
|
||||||
htmlContent = nodeObj.dangerouslySetInnerHTML;
|
htmlContent = nodeObj.topic;
|
||||||
console.log('📝 使用dangerouslySetInnerHTML内容:', htmlContent.substring(0, 200) + '...');
|
console.log('📝 使用topic(HTML)内容:', htmlContent.substring(0, 200) + '...');
|
||||||
}
|
}
|
||||||
// 其次使用markdown字段(如果存在)
|
// 其次使用markdown字段(如果存在)
|
||||||
else if (nodeObj.markdown) {
|
else if (nodeObj.markdown) {
|
||||||
console.log('📝 使用markdown内容,转换为HTML:', nodeObj.markdown.substring(0, 200) + '...');
|
console.log('📝 使用markdown内容,转换为HTML:', nodeObj.markdown.substring(0, 200) + '...');
|
||||||
try {
|
try {
|
||||||
htmlContent = marked.parse(nodeObj.markdown);
|
htmlContent = marked.parse(nodeObj.markdown);
|
||||||
// 更新dangerouslySetInnerHTML
|
// 同步生成的 HTML 到 topic
|
||||||
nodeObj.dangerouslySetInnerHTML = htmlContent;
|
nodeObj.topic = htmlContent;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('❌ Markdown转HTML失败:', error);
|
console.error('❌ Markdown转HTML失败:', error);
|
||||||
htmlContent = nodeObj.markdown;
|
htmlContent = nodeObj.markdown;
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
// 最后回退到data或topic(兼容旧数据)
|
// 兼容旧数据:使用 dangerouslySetInnerHTML
|
||||||
else {
|
else if (nodeObj.dangerouslySetInnerHTML) {
|
||||||
const markdownContent = nodeObj.data || nodeObj.topic || '';
|
htmlContent = nodeObj.dangerouslySetInnerHTML;
|
||||||
console.log('📝 使用兼容模式,从data/topic获取内容:', markdownContent.substring(0, 200) + '...');
|
console.log('📝 使用dangerouslySetInnerHTML(兼容)内容:', htmlContent.substring(0, 200) + '...');
|
||||||
|
}
|
||||||
|
// 简化并稳妥地确定编辑器初始内容:优先 markdown,其次 topic,再次 data;若是 HTML 则转 Markdown
|
||||||
|
const primarySrc = (typeof nodeObj.markdown === 'string' && nodeObj.markdown.trim())
|
||||||
|
? nodeObj.markdown
|
||||||
|
: (
|
||||||
|
typeof nodeObj.topic === 'string' && nodeObj.topic.trim()
|
||||||
|
? nodeObj.topic
|
||||||
|
: (
|
||||||
|
typeof nodeObj.data === 'string' ? nodeObj.data
|
||||||
|
: (nodeObj.data && typeof nodeObj.data === 'object'
|
||||||
|
? (nodeObj.data.markdown || nodeObj.data.note || nodeObj.data.text || nodeObj.data.content || '')
|
||||||
|
: ''
|
||||||
|
)
|
||||||
|
)
|
||||||
|
);
|
||||||
|
|
||||||
// 检查是否包含Markdown格式内容
|
|
||||||
const hasMarkdownContent = markdownContent.includes('|') && markdownContent.includes('-') || // 表格
|
|
||||||
markdownContent.includes('![') || // 图片
|
|
||||||
markdownContent.includes('#') || // 标题
|
|
||||||
markdownContent.includes('**') || // 粗体
|
|
||||||
markdownContent.includes('`'); // 代码
|
|
||||||
|
|
||||||
if (hasMarkdownContent) {
|
|
||||||
try {
|
try {
|
||||||
htmlContent = marked.parse(markdownContent);
|
if (/<\w|<table/i.test(String(primarySrc || ''))) {
|
||||||
// 更新节点结构
|
editorContent.value = convertHTMLToMarkdownImproved(String(primarySrc || '')) || String(primarySrc || '');
|
||||||
nodeObj.markdown = markdownContent;
|
|
||||||
nodeObj.dangerouslySetInnerHTML = htmlContent;
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ Markdown转HTML失败:', error);
|
|
||||||
htmlContent = markdownContent;
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
htmlContent = markdownContent;
|
editorContent.value = String(primarySrc || '');
|
||||||
}
|
}
|
||||||
|
} catch {
|
||||||
|
editorContent.value = String(primarySrc || '');
|
||||||
}
|
}
|
||||||
|
// 暴露调试钩子与源内容,兼容两种命名
|
||||||
|
try {
|
||||||
|
window._debugEditorContent = () => editorContent.value;
|
||||||
|
window._nodeTopic = String(nodeObj.topic || htmlContent || '');
|
||||||
|
window.nodeTopic = window._nodeTopic;
|
||||||
|
} catch {}
|
||||||
|
|
||||||
editorContent.value = htmlContent;
|
// 兜底:若仍为空,直接用 topic 转 Markdown
|
||||||
console.log('🎯 WYSIWYG模式HTML内容:', htmlContent.substring(0, 200) + '...');
|
if (!editorContent.value && typeof nodeObj.topic === 'string' && nodeObj.topic.trim()) {
|
||||||
|
try {
|
||||||
|
const md2 = convertHTMLToMarkdownImproved(nodeObj.topic);
|
||||||
|
editorContent.value = md2 || nodeObj.topic;
|
||||||
|
} catch {
|
||||||
|
editorContent.value = nodeObj.topic;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
console.log('🎯 设置编辑器初始 Markdown:', String(editorContent.value).substring(0, 200) + '...');
|
||||||
|
|
||||||
// 检查是否有MindElixir原生图片
|
// 检查是否有MindElixir原生图片
|
||||||
if (nodeObj.image && !editorContent.value.includes('![')) {
|
if (nodeObj.image && !editorContent.value.includes('![')) {
|
||||||
|
|
@ -811,10 +828,16 @@ const openRichTextEditor = (nodeObj, nodeElement) => {
|
||||||
editorContent.value = editorContent.value + '\n' + imageMarkdown;
|
editorContent.value = editorContent.value + '\n' + imageMarkdown;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 解析已有图片
|
// 解析已有图片(若有实现再调用)
|
||||||
parseExistingImages();
|
try {
|
||||||
|
if (typeof window !== 'undefined' && typeof window.parseExistingImages === 'function') {
|
||||||
|
window.parseExistingImages();
|
||||||
|
}
|
||||||
|
} catch {}
|
||||||
|
|
||||||
showRichTextEditor.value = true;
|
showRichTextEditor.value = true;
|
||||||
|
// 弹窗渲染完成后再初始化 Vditor,避免空白
|
||||||
|
try { nextTick(() => initVditor()); } catch {}
|
||||||
console.log('📝 富文本编辑器已打开');
|
console.log('📝 富文本编辑器已打开');
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
@ -860,6 +883,8 @@ const initVditor = async () => {
|
||||||
placeholder: '请输入节点内容...',
|
placeholder: '请输入节点内容...',
|
||||||
mode: 'wysiwyg', // 所见即所得模式,使用HTML内容
|
mode: 'wysiwyg', // 所见即所得模式,使用HTML内容
|
||||||
theme: 'classic',
|
theme: 'classic',
|
||||||
|
// 设置初始值,确保首次渲染不为空
|
||||||
|
value: String(editorContent.value || ''),
|
||||||
toolbarConfig: {
|
toolbarConfig: {
|
||||||
pin: true // 固定工具栏
|
pin: true // 固定工具栏
|
||||||
},
|
},
|
||||||
|
|
@ -936,6 +961,8 @@ const initVditor = async () => {
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
const toolbar = document.querySelector('.vditor-toolbar');
|
const toolbar = document.querySelector('.vditor-toolbar');
|
||||||
const editor = document.querySelector('.vditor-wysiwyg');
|
const editor = document.querySelector('.vditor-wysiwyg');
|
||||||
|
try { vditorInstance && vditorInstance.setValue(String(editorContent.value || '')); } catch {}
|
||||||
|
try { window.vditorInstance = vditorInstance; } catch {}
|
||||||
}, 100);
|
}, 100);
|
||||||
}, 100);
|
}, 100);
|
||||||
}
|
}
|
||||||
|
|
@ -1019,67 +1046,28 @@ const saveRichTextChanges = async () => {
|
||||||
}
|
}
|
||||||
|
|
||||||
// ✅ 使用Vditor内置API获取内容
|
// ✅ 使用Vditor内置API获取内容
|
||||||
// 从编辑器获取 Markdown 与 HTML,两者都保留
|
|
||||||
const markdownContent = vditorInstance ? vditorInstance.getValue() : editorContent.value;
|
const markdownContent = vditorInstance ? vditorInstance.getValue() : editorContent.value;
|
||||||
// 使用 Vditor 的预览引擎将 Markdown 渲染为 HTML,确保表格在渲染时仍是 <table>
|
|
||||||
let htmlContent = '';
|
|
||||||
try {
|
|
||||||
if (vditorInstance?.preview) {
|
|
||||||
// 借用预览渲染
|
|
||||||
const temp = document.createElement('div');
|
|
||||||
await Vditor.preview(temp, markdownContent, { mode: 'light' });
|
|
||||||
htmlContent = temp.innerHTML;
|
|
||||||
} else {
|
|
||||||
htmlContent = markdownContent;
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
htmlContent = markdownContent;
|
|
||||||
}
|
|
||||||
|
|
||||||
console.log('📝 获取到的HTML内容:', htmlContent.substring(0, 100) + '...');
|
// 统一入口:从 markdown 生成 html 并刷新
|
||||||
console.log('📝 获取到的Markdown内容:', markdownContent.substring(0, 100) + '...');
|
updateNodeModelAndRefresh(currentNode.value, markdownContent, mindElixir.value);
|
||||||
|
// 兼容 dist 双击判断:同步一份旧字段(仅内存)
|
||||||
// 更新节点数据 - 使用新的节点结构
|
currentNode.value.dangerouslySetInnerHTML = currentNode.value.topic;
|
||||||
const titleChanged = editorTitle.value !== (currentNode.value.title || '');
|
const oldTitle = String(currentNode.value.title || '');
|
||||||
console.log('🔍 标题变化检查:', {
|
|
||||||
editorTitle: editorTitle.value,
|
|
||||||
currentNodeTitle: currentNode.value.title || '',
|
|
||||||
titleChanged: titleChanged
|
|
||||||
});
|
|
||||||
|
|
||||||
// 更新节点内容 - 新的节点结构
|
|
||||||
currentNode.value.dangerouslySetInnerHTML = htmlContent; // 保存HTML内容(用于渲染)
|
|
||||||
currentNode.value.markdown = markdownContent || htmlContent; // 保存Markdown内容(用于导出)
|
|
||||||
currentNode.value.topic = generateTopicFromMarkdown(markdownContent || htmlContent); // 生成简短标题
|
|
||||||
currentNode.value.title = editorTitle.value; // 更新标题
|
currentNode.value.title = editorTitle.value; // 更新标题
|
||||||
|
const titleChanged = oldTitle !== String(editorTitle.value || '');
|
||||||
// 更新DOM元素
|
|
||||||
if (currentNodeElement.value) {
|
|
||||||
currentNodeElement.value.innerHTML = htmlContent;
|
|
||||||
|
|
||||||
// 如果标题有变化,也更新节点的文本显示
|
|
||||||
if (titleChanged) {
|
|
||||||
// 查找并更新节点文本元素
|
|
||||||
const textElement = currentNodeElement.value.querySelector('.tpc');
|
|
||||||
if (textElement) {
|
|
||||||
textElement.textContent = editorTitle.value;
|
|
||||||
console.log('📝 DOM文本元素已更新:', editorTitle.value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 直接调用后端API保存数据,不依赖operation事件
|
// 直接调用后端API保存数据,不依赖operation事件
|
||||||
try {
|
try {
|
||||||
// 清理节点ID - 去除可能的"me"前缀
|
// 清理节点ID - 去除可能的"me"前缀
|
||||||
const cleanNodeId = currentNode.value.id.replace(/^me/, '');
|
const cleanNodeId = currentNode.value.id.replace(/^me/, '');
|
||||||
|
|
||||||
|
const htmlForSave = renderMarkdownToHTML(markdownContent || '');
|
||||||
const updateData = {
|
const updateData = {
|
||||||
newTitle: editorTitle.value, // 使用更新后的标题
|
newTitle: currentNode.value.title || generateTopicFromMarkdown(markdownContent || htmlForSave),
|
||||||
newDes: currentNode.value.data?.des || "",
|
newDes: currentNode.value.data?.des || "",
|
||||||
newParentId: currentNode.value.parentId || currentNode.value.parent?.id,
|
newParentId: currentNode.value.parentId || currentNode.value.parent?.id,
|
||||||
newDangerouslySetInnerHTML: htmlContent || "", // 保存HTML内容(用于渲染)
|
newDangerouslySetInnerHTML: htmlForSave, // 后端当前字段名
|
||||||
newMarkdown: markdownContent || htmlContent, // 保存Markdown内容(用于导出)
|
newMarkdown: markdownContent || htmlForSave
|
||||||
newTopic: currentNode.value.topic // 保存生成的简短标题
|
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("🔍 直接发送到后端的更新数据:", updateData);
|
console.log("🔍 直接发送到后端的更新数据:", updateData);
|
||||||
|
|
@ -1096,8 +1084,8 @@ const saveRichTextChanges = async () => {
|
||||||
const nodeElement = currentNodeElement.value;
|
const nodeElement = currentNodeElement.value;
|
||||||
const tpcElement = nodeElement.querySelector('.tpc');
|
const tpcElement = nodeElement.querySelector('.tpc');
|
||||||
if (tpcElement) {
|
if (tpcElement) {
|
||||||
// 直接设置HTML内容
|
const htmlForView = currentNode.value.topic || renderMarkdownToHTML(markdownContent || '');
|
||||||
tpcElement.innerHTML = htmlContent;
|
tpcElement.innerHTML = htmlForView;
|
||||||
console.log('📝 节点显示内容已更新 - 直接设置HTML');
|
console.log('📝 节点显示内容已更新 - 直接设置HTML');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -1216,7 +1204,6 @@ const loadExistingMindmap = async () => {
|
||||||
// 暂时先创建一个新的思维导图
|
// 暂时先创建一个新的思维导图
|
||||||
await createNewMindmap();
|
await createNewMindmap();
|
||||||
};
|
};
|
||||||
|
|
||||||
// 创建新思维导图
|
// 创建新思维导图
|
||||||
const createNewMindmap = async () => {
|
const createNewMindmap = async () => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -1237,23 +1224,47 @@ const createNewMindmap = async () => {
|
||||||
// 隐藏欢迎页面
|
// 隐藏欢迎页面
|
||||||
hideWelcomePage();
|
hideWelcomePage();
|
||||||
|
|
||||||
// 加载新创建的思维导图
|
// 直接按“历史记录方式”获取完整数据并加载,确保 me-tpc/事件完全就绪
|
||||||
await loadMindmapData(response.data);
|
|
||||||
|
|
||||||
// 显示成功通知
|
|
||||||
|
|
||||||
|
|
||||||
// 延迟后重新加载思维导图数据
|
|
||||||
setTimeout(async () => {
|
|
||||||
try {
|
try {
|
||||||
const refreshResponse = await mindmapAPI.getMindmap(mindmapId);
|
const refreshResponse = await mindmapAPI.getMindmap(mindmapId);
|
||||||
if (refreshResponse.data && refreshResponse.data.nodeData) {
|
if (refreshResponse.data && refreshResponse.data.nodeData) {
|
||||||
await loadMindmapData(refreshResponse.data);
|
await loadMindmapData(refreshResponse.data, false, true);
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
// 静默处理错误
|
// 静默处理错误
|
||||||
}
|
}
|
||||||
}, 1500);
|
|
||||||
|
// 绑定双击监听兜底,并打印节点就绪情况
|
||||||
|
try {
|
||||||
|
await nextTick();
|
||||||
|
const tpcs = mindmapEl.value?.querySelectorAll('me-tpc') || [];
|
||||||
|
console.log('🔍 新建导图节点(me-tpc)数量:', tpcs.length);
|
||||||
|
addCustomDoubleClickListeners();
|
||||||
|
|
||||||
|
// 模拟“从历史记录点击最新导图”的效果:
|
||||||
|
// 1) 找到根节点元素
|
||||||
|
const firstTpc = tpcs[0];
|
||||||
|
if (firstTpc) {
|
||||||
|
// 2) 从 data-nodeid 解析出纯ID,拿到真实节点对象
|
||||||
|
const nodeIdAttr = firstTpc.getAttribute('data-nodeid') || '';
|
||||||
|
const pureId = nodeIdAttr.startsWith('me') ? nodeIdAttr.substring(2) : nodeIdAttr;
|
||||||
|
let nodeForEdit = null;
|
||||||
|
if (mindElixir.value && typeof mindElixir.value.getNodeById === 'function') {
|
||||||
|
nodeForEdit = mindElixir.value.getNodeById(pureId);
|
||||||
|
}
|
||||||
|
// 3) 直接触发编辑事件,等同于历史列表点击后双击
|
||||||
|
if (nodeForEdit) {
|
||||||
|
console.log('🎯 新建完成后主动打开编辑器(根节点):', nodeForEdit);
|
||||||
|
mindElixir.value.bus.fire('showRichTextEditor', nodeForEdit, firstTpc);
|
||||||
|
} else {
|
||||||
|
// 兜底:派发一次双击事件
|
||||||
|
const dbl = new MouseEvent('dblclick', { bubbles: true, cancelable: true, composed: true });
|
||||||
|
firstTpc.dispatchEvent(dbl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('⚠️ 绑定双击监听失败:', e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
@ -1304,7 +1315,6 @@ const restorePosition = (position) => {
|
||||||
console.warn('恢复位置失败:', error);
|
console.warn('恢复位置失败:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 加载思维导图数据 - 支持位置保持
|
// 加载思维导图数据 - 支持位置保持
|
||||||
const loadMindmapData = async (data, keepPosition = false, shouldCenterRoot = true) => {
|
const loadMindmapData = async (data, keepPosition = false, shouldCenterRoot = true) => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -1392,6 +1402,7 @@ const loadMindmapData = async (data, keepPosition = false, shouldCenterRoot = tr
|
||||||
mindElixir.value = new MindElixir({
|
mindElixir.value = new MindElixir({
|
||||||
el: mindmapEl.value,
|
el: mindmapEl.value,
|
||||||
direction: MindElixir.RIGHT,
|
direction: MindElixir.RIGHT,
|
||||||
|
editable: true,
|
||||||
draggable: true,
|
draggable: true,
|
||||||
contextMenu: false,
|
contextMenu: false,
|
||||||
toolBar: true,
|
toolBar: true,
|
||||||
|
|
@ -1441,18 +1452,6 @@ const loadMindmapData = async (data, keepPosition = false, shouldCenterRoot = tr
|
||||||
// 初始化数据
|
// 初始化数据
|
||||||
console.log('🔍 初始化Mind Elixir数据:', data);
|
console.log('🔍 初始化Mind Elixir数据:', data);
|
||||||
|
|
||||||
// 检查数据中是否包含dangerouslySetInnerHTML字段
|
|
||||||
if (data && data.nodeData) {
|
|
||||||
const nodeIds = Object.keys(data.nodeData);
|
|
||||||
console.log('🔍 节点数量:', nodeIds.length);
|
|
||||||
nodeIds.forEach(nodeId => {
|
|
||||||
const node = data.nodeData[nodeId];
|
|
||||||
if (node.dangerouslySetInnerHTML) {
|
|
||||||
console.log(`🔍 节点 ${nodeId} 有 dangerouslySetInnerHTML:`, node.dangerouslySetInnerHTML.substring(0, 100));
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
const result = mindElixir.value.init(data);
|
const result = mindElixir.value.init(data);
|
||||||
console.log('✅ Mind Elixir实例创建成功,初始化结果:', result);
|
console.log('✅ Mind Elixir实例创建成功,初始化结果:', result);
|
||||||
|
|
||||||
|
|
@ -1512,6 +1511,7 @@ const loadMindmapData = async (data, keepPosition = false, shouldCenterRoot = tr
|
||||||
mindElixir.value = new MindElixir({
|
mindElixir.value = new MindElixir({
|
||||||
el: mindmapEl.value,
|
el: mindmapEl.value,
|
||||||
direction: MindElixir.RIGHT,
|
direction: MindElixir.RIGHT,
|
||||||
|
editable: true,
|
||||||
draggable: true,
|
draggable: true,
|
||||||
contextMenu: false,
|
contextMenu: false,
|
||||||
toolBar: true,
|
toolBar: true,
|
||||||
|
|
@ -1860,7 +1860,6 @@ const addNodeDescriptions = () => {
|
||||||
});
|
});
|
||||||
}, 1000); // 等待1秒让MindElixir完全渲染
|
}, 1000); // 等待1秒让MindElixir完全渲染
|
||||||
};
|
};
|
||||||
|
|
||||||
// 移除强制样式,恢复MindElixir原始样式
|
// 移除强制样式,恢复MindElixir原始样式
|
||||||
const removeForcedStyles = () => {
|
const removeForcedStyles = () => {
|
||||||
if (!mindmapEl.value) return;
|
if (!mindmapEl.value) return;
|
||||||
|
|
@ -2100,7 +2099,6 @@ const applyCustomNodePositions = () => {
|
||||||
|
|
||||||
// console.log('已应用自定义节点位置');
|
// console.log('已应用自定义节点位置');
|
||||||
};
|
};
|
||||||
|
|
||||||
// 计算思维导图整体位置并居中显示
|
// 计算思维导图整体位置并居中显示
|
||||||
const centerMindMap = () => {
|
const centerMindMap = () => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -2450,7 +2448,6 @@ const submitAIQuestion = async () => {
|
||||||
const userPrompt = `节点信息:
|
const userPrompt = `节点信息:
|
||||||
当前节点:${currentQuestionNode.value.topic}
|
当前节点:${currentQuestionNode.value.topic}
|
||||||
上下文:${getNodeContext(currentQuestionNode.value)}
|
上下文:${getNodeContext(currentQuestionNode.value)}
|
||||||
|
|
||||||
用户问题:${aiQuestion.value}
|
用户问题:${aiQuestion.value}
|
||||||
|
|
||||||
请给出详细的回答,回答应该:
|
请给出详细的回答,回答应该:
|
||||||
|
|
@ -2874,9 +2871,6 @@ const copyNodeText = async () => {
|
||||||
// 操作完成后隐藏菜单
|
// 操作完成后隐藏菜单
|
||||||
selectedNode.value = null;
|
selectedNode.value = null;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
// 显示复制成功提示
|
// 显示复制成功提示
|
||||||
const showCopySuccess = () => {
|
const showCopySuccess = () => {
|
||||||
// 创建临时提示元素
|
// 创建临时提示元素
|
||||||
|
|
@ -3064,7 +3058,6 @@ const handleNodeMove = async (node, oldParent, newParent) => {
|
||||||
// 静默处理错误
|
// 静默处理错误
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 处理节点拖拽操作(更新节点的父子关系)
|
// 处理节点拖拽操作(更新节点的父子关系)
|
||||||
const handleNodeDragOperation = async (operation) => {
|
const handleNodeDragOperation = async (operation) => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -3173,7 +3166,7 @@ const handleEditFinish = async (operation) => {
|
||||||
console.log("🔍 保存编辑的节点:", {
|
console.log("🔍 保存编辑的节点:", {
|
||||||
nodeId: editedNode.id,
|
nodeId: editedNode.id,
|
||||||
nodeTopic: editedNode.topic,
|
nodeTopic: editedNode.topic,
|
||||||
hasDangerouslySetInnerHTML: !!editedNode.dangerouslySetInnerHTML
|
hasHtml: /<\\w+[^>]*>/.test(editedNode.topic || '')
|
||||||
});
|
});
|
||||||
|
|
||||||
// 调用后端API更新节点
|
// 调用后端API更新节点
|
||||||
|
|
@ -3200,7 +3193,6 @@ const updateNodeEdit = async (node) => {
|
||||||
originalNodeId: node.id,
|
originalNodeId: node.id,
|
||||||
cleanNodeId: cleanNodeId,
|
cleanNodeId: cleanNodeId,
|
||||||
nodeTopic: node.topic,
|
nodeTopic: node.topic,
|
||||||
dangerouslySetInnerHTML: node.dangerouslySetInnerHTML,
|
|
||||||
currentMindmapId: currentMindmapId.value
|
currentMindmapId: currentMindmapId.value
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -3215,7 +3207,7 @@ const updateNodeEdit = async (node) => {
|
||||||
newTitle: node.topic,
|
newTitle: node.topic,
|
||||||
newDes: node.data?.des || "",
|
newDes: node.data?.des || "",
|
||||||
newParentId: node.parentId || node.parent?.id,
|
newParentId: node.parentId || node.parent?.id,
|
||||||
newDangerouslySetInnerHTML: node.dangerouslySetInnerHTML || "" // 保存富文本内容
|
newDangerouslySetInnerHTML: node.topic || ""
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("🔍 发送到后端的更新数据:", updateData);
|
console.log("🔍 发送到后端的更新数据:", updateData);
|
||||||
|
|
@ -3245,7 +3237,7 @@ const updateNodeEdit = async (node) => {
|
||||||
console.log('🔍 调试信息 - node对象:', {
|
console.log('🔍 调试信息 - node对象:', {
|
||||||
id: node.id,
|
id: node.id,
|
||||||
topic: node.topic?.substring(0, 50) + '...',
|
topic: node.topic?.substring(0, 50) + '...',
|
||||||
hasDangerouslySetInnerHTML: !!node.dangerouslySetInnerHTML
|
hasHtml: /<\w+[^>]*>/.test(node.topic || '')
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
|
@ -3256,18 +3248,13 @@ const updateNodeEdit = async (node) => {
|
||||||
console.log('✅ DOM元素存在,直接更新内容...');
|
console.log('✅ DOM元素存在,直接更新内容...');
|
||||||
// findEle返回的就是me-tpc元素本身,直接使用它
|
// findEle返回的就是me-tpc元素本身,直接使用它
|
||||||
// 直接更新节点内容,不使用异步的shapeTpc
|
// 直接更新节点内容,不使用异步的shapeTpc
|
||||||
if (node.dangerouslySetInnerHTML) {
|
if (node.topic) {
|
||||||
console.log('🔍 更新HTML内容:', node.dangerouslySetInnerHTML.substring(0, 100) + '...');
|
|
||||||
// 使用同步方式直接设置内容
|
|
||||||
nodeElement.innerHTML = node.dangerouslySetInnerHTML;
|
|
||||||
console.log('📝 节点显示内容已更新 (updateNodeEdit) - 直接设置HTML');
|
|
||||||
} else if (node.topic) {
|
|
||||||
console.log('🔍 更新文本内容:', node.topic.substring(0, 100) + '...');
|
console.log('🔍 更新文本内容:', node.topic.substring(0, 100) + '...');
|
||||||
// 如果没有HTML内容,使用topic
|
// 直接设置为 HTML 以渲染富文本
|
||||||
nodeElement.textContent = node.topic;
|
nodeElement.innerHTML = node.topic;
|
||||||
console.log('📝 节点显示内容已更新 (updateNodeEdit) - 设置文本');
|
console.log('📝 节点显示内容已更新 (updateNodeEdit) - 设置HTML');
|
||||||
} else {
|
} else {
|
||||||
console.warn('⚠️ node对象没有dangerouslySetInnerHTML或topic');
|
console.warn('⚠️ node对象没有topic');
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.warn('⚠️ findEle返回了null或undefined');
|
console.warn('⚠️ findEle返回了null或undefined');
|
||||||
|
|
@ -3604,9 +3591,9 @@ const createNodesRecursively = async (node, mindmapId, parentId) => {
|
||||||
parentId: currentParentId
|
parentId: currentParentId
|
||||||
};
|
};
|
||||||
|
|
||||||
// 如果有HTML内容,添加到节点数据中
|
// 如果有HTML内容,添加到节点数据中(后端字段名为 dangerouslySetInnerHTML)
|
||||||
if (currentNode.dangerouslySetInnerHTML) {
|
if (currentNode.topic) {
|
||||||
nodeData.dangerouslySetInnerHTML = currentNode.dangerouslySetInnerHTML;
|
nodeData.dangerouslySetInnerHTML = currentNode.topic;
|
||||||
}
|
}
|
||||||
|
|
||||||
nodesToCreate.push({ nodeData, children: currentNode.children || [] });
|
nodesToCreate.push({ nodeData, children: currentNode.children || [] });
|
||||||
|
|
@ -3646,12 +3633,10 @@ const createNodesRecursively = async (node, mindmapId, parentId) => {
|
||||||
console.error("❌ 创建节点失败:", error);
|
console.error("❌ 创建节点失败:", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 绑定事件监听器
|
// 绑定事件监听器
|
||||||
// 保存事件监听器引用,用于清理
|
// 保存事件监听器引用,用于清理
|
||||||
let wheelHandler = null;
|
let wheelHandler = null;
|
||||||
let clickHandler = null;
|
let clickHandler = null;
|
||||||
|
|
||||||
// 添加自定义双击编辑事件监听器
|
// 添加自定义双击编辑事件监听器
|
||||||
const addCustomDoubleClickListeners = () => {
|
const addCustomDoubleClickListeners = () => {
|
||||||
if (!mindmapEl.value) return;
|
if (!mindmapEl.value) return;
|
||||||
|
|
@ -3666,29 +3651,17 @@ const addCustomDoubleClickListeners = () => {
|
||||||
// 监听所有节点的双击事件
|
// 监听所有节点的双击事件
|
||||||
const handleDoubleClick = (event) => {
|
const handleDoubleClick = (event) => {
|
||||||
console.log('🎯 检测到双击事件:', event.target);
|
console.log('🎯 检测到双击事件:', event.target);
|
||||||
|
// 直接用 closest 查询实际的 me-tpc 节点
|
||||||
// 查找最近的节点元素 - 修复:Mind Elixir使用的是me-tpc标签
|
let nodeElement = event.target && event.target.closest ? event.target.closest('.me-tpc') : null;
|
||||||
let nodeElement = event.target;
|
if (!nodeElement) {
|
||||||
while (nodeElement && !nodeElement.classList.contains('topic') && nodeElement.tagName !== 'ME-TPC') {
|
// 兼容旧结构
|
||||||
nodeElement = nodeElement.parentElement;
|
nodeElement = event.target && event.target.closest ? event.target.closest('.topic') : null;
|
||||||
if (!nodeElement) break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// 如果没找到topic类名,尝试查找me-tpc标签
|
|
||||||
if (!nodeElement || (!nodeElement.classList.contains('topic') && nodeElement.tagName !== 'ME-TPC')) {
|
|
||||||
nodeElement = event.target;
|
|
||||||
while (nodeElement && nodeElement.tagName !== 'ME-TPC') {
|
|
||||||
nodeElement = nodeElement.parentElement;
|
|
||||||
if (!nodeElement) break;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log('🎯 找到的节点元素:', nodeElement, '标签名:', nodeElement?.tagName, '类名:', nodeElement?.className);
|
console.log('🎯 找到的节点元素:', nodeElement, '标签名:', nodeElement?.tagName, '类名:', nodeElement?.className);
|
||||||
|
|
||||||
if (nodeElement && (nodeElement.classList.contains('topic') || nodeElement.tagName === 'ME-TPC')) {
|
if (nodeElement) {
|
||||||
console.log('🎯 确认是节点元素,阻止默认行为');
|
console.log('🎯 确认是节点元素,交由内置与自定义编辑处理');
|
||||||
event.preventDefault();
|
|
||||||
event.stopPropagation();
|
|
||||||
|
|
||||||
// 获取节点数据 - 修复:Mind Elixir使用的是data-nodeid
|
// 获取节点数据 - 修复:Mind Elixir使用的是data-nodeid
|
||||||
const nodeId = nodeElement.getAttribute('data-nodeid') || nodeElement.getAttribute('data-id');
|
const nodeId = nodeElement.getAttribute('data-nodeid') || nodeElement.getAttribute('data-id');
|
||||||
|
|
@ -3750,7 +3723,7 @@ const addCustomDoubleClickListeners = () => {
|
||||||
id: nodeId,
|
id: nodeId,
|
||||||
topic: textContent,
|
topic: textContent,
|
||||||
data: textContent,
|
data: textContent,
|
||||||
dangerouslySetInnerHTML: htmlContent,
|
dangerouslySetInnerHTML: undefined,
|
||||||
hasImage: hasImage,
|
hasImage: hasImage,
|
||||||
hasTable: hasTable
|
hasTable: hasTable
|
||||||
};
|
};
|
||||||
|
|
@ -3774,10 +3747,34 @@ const addCustomDoubleClickListeners = () => {
|
||||||
};
|
};
|
||||||
|
|
||||||
// 添加双击事件监听器到思维导图容器
|
// 添加双击事件监听器到思维导图容器
|
||||||
|
// 使用捕获阶段,确保能拿到所有双击事件,但不阻断默认行为
|
||||||
mindmapEl.value.addEventListener('dblclick', handleDoubleClick, true);
|
mindmapEl.value.addEventListener('dblclick', handleDoubleClick, true);
|
||||||
|
|
||||||
// 存储监听器引用,以便后续移除
|
// 存储监听器引用,以便后续移除
|
||||||
mindmapEl.value._customDoubleClickHandler = handleDoubleClick;
|
mindmapEl.value._customDoubleClickHandler = handleDoubleClick;
|
||||||
|
|
||||||
|
// 额外兜底:在document层监听,不阻断默认事件
|
||||||
|
const docDblClickHandler = (event) => {
|
||||||
|
try {
|
||||||
|
const target = event.target;
|
||||||
|
if (!target || !target.closest) return;
|
||||||
|
const nodeEl = target.closest('me-tpc');
|
||||||
|
if (!nodeEl) return;
|
||||||
|
const idAttr = nodeEl.getAttribute('data-nodeid') || '';
|
||||||
|
const pureId = idAttr.startsWith('me') ? idAttr.substring(2) : idAttr;
|
||||||
|
if (mindElixir.value && typeof mindElixir.value.getNodeById === 'function') {
|
||||||
|
const obj = mindElixir.value.getNodeById(pureId);
|
||||||
|
if (obj) {
|
||||||
|
console.log('🎯 document层兜底打开编辑器:', pureId);
|
||||||
|
mindElixir.value.bus.fire('showRichTextEditor', obj, nodeEl);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
// 忽略
|
||||||
|
}
|
||||||
|
};
|
||||||
|
document.addEventListener('dblclick', docDblClickHandler, true);
|
||||||
|
mindmapEl.value._docDblClickHandler = docDblClickHandler;
|
||||||
};
|
};
|
||||||
|
|
||||||
// 查找节点数据的辅助函数
|
// 查找节点数据的辅助函数
|
||||||
|
|
@ -3831,83 +3828,9 @@ const openCustomEditModal = (nodeObj, nodeElement) => {
|
||||||
} else if (nodeObj.note) {
|
} else if (nodeObj.note) {
|
||||||
markdownContent = nodeObj.note;
|
markdownContent = nodeObj.note;
|
||||||
console.log('✅ 从node.note获取Markdown源码:', markdownContent.substring(0, 100) + '...');
|
console.log('✅ 从node.note获取Markdown源码:', markdownContent.substring(0, 100) + '...');
|
||||||
} else if (nodeObj.topic && !nodeObj.dangerouslySetInnerHTML) {
|
} else if (nodeObj.topic) {
|
||||||
// 如果topic是纯文本,可能也是Markdown
|
|
||||||
markdownContent = nodeObj.topic;
|
markdownContent = nodeObj.topic;
|
||||||
console.log('✅ 从node.topic获取内容:', markdownContent.substring(0, 100) + '...');
|
console.log('✅ 从node.topic获取内容:', markdownContent.substring(0, 100) + '...');
|
||||||
} else if (nodeObj.dangerouslySetInnerHTML) {
|
|
||||||
// ✅ 在传给Vditor之前先把HTML转成Markdown(优先支持表格为 GFM 语法)
|
|
||||||
console.log('⚠️ 没有找到Markdown字段,转换HTML为Markdown:', nodeObj.dangerouslySetInnerHTML.substring(0, 100) + '...');
|
|
||||||
try {
|
|
||||||
const rawHtml = nodeObj?.dangerouslySetInnerHTML || '';
|
|
||||||
|
|
||||||
// 先尝试把 <table> 转成 GFM 表格,避免转换成纯文本
|
|
||||||
const tableToMarkdown = (html) => {
|
|
||||||
if (!/<table[\s\S]*<\/table>/i.test(html)) return null;
|
|
||||||
const temp = document.createElement('div');
|
|
||||||
temp.innerHTML = html;
|
|
||||||
const table = temp.querySelector('table');
|
|
||||||
if (!table) return null;
|
|
||||||
const getText = (el) => (el?.textContent || '').replace(/\n+/g, ' ').trim();
|
|
||||||
let headers = [];
|
|
||||||
let rows = [];
|
|
||||||
const thead = table.querySelector('thead');
|
|
||||||
const tbody = table.querySelector('tbody');
|
|
||||||
if (thead) {
|
|
||||||
const tr = thead.querySelector('tr');
|
|
||||||
if (tr) headers = Array.from(tr.children).map(getText);
|
|
||||||
}
|
|
||||||
const bodyTrs = (tbody || table).querySelectorAll('tr');
|
|
||||||
bodyTrs.forEach((tr, index) => {
|
|
||||||
const cells = Array.from(tr.children).map(getText);
|
|
||||||
if (index === 0 && headers.length === 0) headers = cells; else rows.push(cells);
|
|
||||||
});
|
|
||||||
if (headers.length === 0) return null;
|
|
||||||
const headerLine = `| ${headers.join(' | ')} |`;
|
|
||||||
const alignLine = `| ${headers.map(() => '---').join(' | ')} |`;
|
|
||||||
const rowLines = rows.map(r => `| ${r.join(' | ')} |`);
|
|
||||||
return [headerLine, alignLine, ...rowLines].join('\n');
|
|
||||||
};
|
|
||||||
|
|
||||||
const mdFromTable = tableToMarkdown(rawHtml);
|
|
||||||
if (mdFromTable) {
|
|
||||||
markdownContent = mdFromTable;
|
|
||||||
console.log('✅ 使用自定义表格转换为Markdown');
|
|
||||||
} else if (typeof Vditor?.html2md === 'function') {
|
|
||||||
markdownContent = Vditor.html2md(rawHtml);
|
|
||||||
console.log('✅ 使用 Vditor.html2md 转换成功:', markdownContent.substring(0, 100) + '...');
|
|
||||||
} else {
|
|
||||||
console.warn('⚠️ Vditor.html2md 不可用,使用简单转换逻辑');
|
|
||||||
markdownContent = String(rawHtml)
|
|
||||||
// 图片:alt 可为空
|
|
||||||
.replace(/<img[^>]*src="([^"]+)"[^>]*alt="([^"]*)"[^>]*>/gi, '')
|
|
||||||
.replace(/<img[^>]*src="([^"]+)"[^>]*>/gi, '')
|
|
||||||
// 换行与段落
|
|
||||||
.replace(/<br\s*\/?>/gi, '\n')
|
|
||||||
.replace(/<\/p>/gi, '\n\n')
|
|
||||||
.replace(/<p[^>]*>/gi, '')
|
|
||||||
// 加粗与斜体
|
|
||||||
.replace(/<strong>(.*?)<\/strong>/gi, '**$1**')
|
|
||||||
.replace(/<b>(.*?)<\/b>/gi, '**$1**')
|
|
||||||
.replace(/<em>(.*?)<\/em>/gi, '*$1*')
|
|
||||||
.replace(/<i>(.*?)<\/i>/gi, '*$1*')
|
|
||||||
// 列表
|
|
||||||
.replace(/<ul[^>]*>/gi, '\n')
|
|
||||||
.replace(/<\/ul>/gi, '\n')
|
|
||||||
.replace(/<li[^>]*>/gi, '- ')
|
|
||||||
.replace(/<\/li>/gi, '\n')
|
|
||||||
// 清除剩余标签
|
|
||||||
.replace(/<[^>]+>/g, '')
|
|
||||||
// 规范换行
|
|
||||||
.replace(/\n{3,}/g, '\n\n')
|
|
||||||
.trim();
|
|
||||||
|
|
||||||
console.log('✅ 使用简单转换逻辑成功:', markdownContent.substring(0, 100) + '...');
|
|
||||||
}
|
|
||||||
} catch (error) {
|
|
||||||
console.error('❌ HTML 转 Markdown 失败:', error);
|
|
||||||
markdownContent = nodeObj?.dangerouslySetInnerHTML || '';
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
console.warn('⚠️ 没有找到任何可用的内容字段');
|
console.warn('⚠️ 没有找到任何可用的内容字段');
|
||||||
markdownContent = '';
|
markdownContent = '';
|
||||||
|
|
@ -4190,7 +4113,6 @@ const maintainZoomLevel = () => {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 保存思维导图
|
// 保存思维导图
|
||||||
const saveMindMap = async () => {
|
const saveMindMap = async () => {
|
||||||
console.log("🚀🚀🚀 保存函数被调用 🚀🚀🚀");
|
console.log("🚀🚀🚀 保存函数被调用 🚀🚀🚀");
|
||||||
|
|
@ -4430,7 +4352,6 @@ const saveMindMap = async () => {
|
||||||
console.error("❌ 保存思维导图失败:", error);
|
console.error("❌ 保存思维导图失败:", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 刷新思维导图(优化版本,减少不必要的刷新)
|
// 刷新思维导图(优化版本,减少不必要的刷新)
|
||||||
const refreshMindMap = async () => {
|
const refreshMindMap = async () => {
|
||||||
if (!currentMindmapId.value) {
|
if (!currentMindmapId.value) {
|
||||||
|
|
@ -4564,8 +4485,16 @@ const savePreviewToDatabase = async (data, title) => {
|
||||||
// 强制隐藏欢迎页面
|
// 强制隐藏欢迎页面
|
||||||
hideWelcomePage();
|
hideWelcomePage();
|
||||||
|
|
||||||
// 🔧 关键修复:不要重新加载数据,保持当前显示状态
|
// 按历史记录方式:从后端取一次完整数据再加载,确保事件与DOM完全就绪
|
||||||
// await loadMindmapData(response.data, true, false);
|
try {
|
||||||
|
const full = await mindmapAPI.getMindmap(mindmapId);
|
||||||
|
if (full.data && full.data.nodeData) {
|
||||||
|
await loadMindmapData(full.data, true, false);
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('获取完整导图数据失败,改用响应数据加载');
|
||||||
|
await loadMindmapData(response.data, true, false);
|
||||||
|
}
|
||||||
|
|
||||||
// 通知AISidebar组件更新历史记录,保存真实的思维导图ID
|
// 通知AISidebar组件更新历史记录,保存真实的思维导图ID
|
||||||
window.dispatchEvent(new CustomEvent('mindmap-saved', {
|
window.dispatchEvent(new CustomEvent('mindmap-saved', {
|
||||||
|
|
@ -4811,7 +4740,6 @@ const cleanupIntervals = () => {
|
||||||
onUnmounted(() => {
|
onUnmounted(() => {
|
||||||
cleanupIntervals();
|
cleanupIntervals();
|
||||||
});
|
});
|
||||||
|
|
||||||
// 编辑完成后刷新思维导图的函数
|
// 编辑完成后刷新思维导图的函数
|
||||||
const refreshMindmapAfterEdit = async (mindmapId, savedPosition) => {
|
const refreshMindmapAfterEdit = async (mindmapId, savedPosition) => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -5213,7 +5141,6 @@ const updateMindMapRealtime = async (data, title, eventDetail = null) => {
|
||||||
console.error('❌ 实时更新思维导图失败:', error);
|
console.error('❌ 实时更新思维导图失败:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 增量更新节点内容,避免完整重新渲染
|
// 增量更新节点内容,避免完整重新渲染
|
||||||
const updateNodesIncremental = (newNodes, existingNodeData) => {
|
const updateNodesIncremental = (newNodes, existingNodeData) => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -5259,7 +5186,6 @@ const updateNodesIncremental = (newNodes, existingNodeData) => {
|
||||||
console.error('❌ 增量更新节点失败:', error);
|
console.error('❌ 增量更新节点失败:', error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
// 在现有节点数据中查找指定ID的节点
|
// 在现有节点数据中查找指定ID的节点
|
||||||
const findNodeInData = (nodeData, targetId) => {
|
const findNodeInData = (nodeData, targetId) => {
|
||||||
if (!nodeData) return null;
|
if (!nodeData) return null;
|
||||||
|
|
@ -5329,49 +5255,71 @@ const findNodeInData = (nodeData, targetId) => {
|
||||||
100% { transform: rotate(360deg); }
|
100% { transform: rotate(360deg); }
|
||||||
}
|
}
|
||||||
|
|
||||||
/* Vditor表格样式 */
|
/* 表格:统一为扁平网格风格(右图效果) */
|
||||||
.vditor-preview .vditor-table {
|
:deep(.vditor-preview) { overflow-x: auto; }
|
||||||
border-collapse: collapse;
|
:deep(.vditor-preview .vditor-table),
|
||||||
|
:deep(.vditor-preview table),
|
||||||
|
:deep(.markdown-table) {
|
||||||
width: 100%;
|
width: 100%;
|
||||||
margin: 16px 0;
|
table-layout: fixed;
|
||||||
font-size: 14px;
|
border-collapse: collapse;
|
||||||
background: white;
|
background: #fff;
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
|
border: 1px solid #d9d9d9;
|
||||||
border-radius: 8px;
|
margin: 8px 0;
|
||||||
overflow: hidden;
|
box-shadow: none;
|
||||||
|
border-radius: 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
.vditor-preview .vditor-th,
|
:deep(.vditor-preview .vditor-th),
|
||||||
.vditor-preview .vditor-td {
|
:deep(.vditor-preview .vditor-td),
|
||||||
padding: 12px 16px;
|
:deep(.vditor-preview table th),
|
||||||
|
:deep(.vditor-preview table td),
|
||||||
|
:deep(.markdown-table th),
|
||||||
|
:deep(.markdown-table td) {
|
||||||
|
padding: 14px 18px;
|
||||||
text-align: left;
|
text-align: left;
|
||||||
border-bottom: 1px solid #e8eaed;
|
vertical-align: top;
|
||||||
border-right: 1px solid #e8eaed;
|
border: 1px solid #d9d9d9;
|
||||||
|
word-break: break-word;
|
||||||
|
white-space: normal;
|
||||||
|
color: #1f1f1f;
|
||||||
|
line-height: 1.8;
|
||||||
}
|
}
|
||||||
|
|
||||||
.vditor-preview .vditor-th {
|
:deep(.vditor-preview thead .vditor-th),
|
||||||
background: #f8f9fa;
|
:deep(.vditor-preview table thead th),
|
||||||
|
:deep(.markdown-table thead th) {
|
||||||
|
background: #f5f5f5;
|
||||||
font-weight: 600;
|
font-weight: 600;
|
||||||
color: #202124;
|
|
||||||
border-bottom: 2px solid #dadce0;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.vditor-preview .vditor-td {
|
/* 将相同表格风格应用到思维导图节点显示(me-tpc/.topic 内的 table) */
|
||||||
background: white;
|
:deep(.mind-elixir .map-container me-tpc table),
|
||||||
color: #3c4043;
|
:deep(.mind-elixir .map-container .topic table) {
|
||||||
|
width: 100%;
|
||||||
|
table-layout: fixed;
|
||||||
|
border-collapse: collapse;
|
||||||
|
background: #fff;
|
||||||
|
border: 1px solid #d9d9d9;
|
||||||
}
|
}
|
||||||
|
|
||||||
.vditor-preview .vditor-tr:hover .vditor-td {
|
:deep(.mind-elixir .map-container me-tpc th),
|
||||||
background: #f8f9fa;
|
:deep(.mind-elixir .map-container me-tpc td),
|
||||||
|
:deep(.mind-elixir .map-container .topic th),
|
||||||
|
:deep(.mind-elixir .map-container .topic td) {
|
||||||
|
padding: 14px 18px;
|
||||||
|
text-align: left;
|
||||||
|
vertical-align: top;
|
||||||
|
border: 1px solid #d9d9d9;
|
||||||
|
word-break: break-word;
|
||||||
|
white-space: normal;
|
||||||
|
line-height: 1.8;
|
||||||
}
|
}
|
||||||
|
|
||||||
.vditor-preview .vditor-thead .vditor-th:last-child,
|
:deep(.mind-elixir .map-container me-tpc thead th),
|
||||||
.vditor-preview .vditor-tbody .vditor-td:last-child {
|
:deep(.mind-elixir .map-container .topic thead th) {
|
||||||
border-right: none;
|
background: #f5f5f5;
|
||||||
}
|
font-weight: 600;
|
||||||
|
|
||||||
.vditor-preview .vditor-tbody .vditor-tr:last-child .vditor-td {
|
|
||||||
border-bottom: none;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
.mindmap-container {
|
.mindmap-container {
|
||||||
|
|
@ -5432,7 +5380,6 @@ const findNodeInData = (nodeData, targetId) => {
|
||||||
stroke-width: 2;
|
stroke-width: 2;
|
||||||
fill: none;
|
fill: none;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 刷新按钮样式 */
|
/* 刷新按钮样式 */
|
||||||
.refresh-btn {
|
.refresh-btn {
|
||||||
display: flex;
|
display: flex;
|
||||||
|
|
@ -5983,7 +5930,6 @@ const findNodeInData = (nodeData, targetId) => {
|
||||||
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
|
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1) !important;
|
||||||
border: 1px solid #e0e0e0 !important;
|
border: 1px solid #e0e0e0 !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 强制所有节点都显示为框样式 */
|
/* 强制所有节点都显示为框样式 */
|
||||||
.topic {
|
.topic {
|
||||||
background: white !important;
|
background: white !important;
|
||||||
|
|
@ -6036,7 +5982,6 @@ const findNodeInData = (nodeData, targetId) => {
|
||||||
.topic::after {
|
.topic::after {
|
||||||
display: none !important;
|
display: none !important;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 移除所有可能的线样式 */
|
/* 移除所有可能的线样式 */
|
||||||
.topic[style*="border-radius: 50%"] {
|
.topic[style*="border-radius: 50%"] {
|
||||||
border-radius: 8px !important;
|
border-radius: 8px !important;
|
||||||
|
|
@ -6081,7 +6026,6 @@ const findNodeInData = (nodeData, targetId) => {
|
||||||
font-size: 12px;
|
font-size: 12px;
|
||||||
line-height: 1.3;
|
line-height: 1.3;
|
||||||
}
|
}
|
||||||
|
|
||||||
/* 强制表格样式 - 最高优先级 */
|
/* 强制表格样式 - 最高优先级 */
|
||||||
.topic table,
|
.topic table,
|
||||||
.topic .text table,
|
.topic .text table,
|
||||||
|
|
@ -6730,7 +6674,6 @@ const findNodeInData = (nodeData, targetId) => {
|
||||||
font-size: 16px;
|
font-size: 16px;
|
||||||
color: #374151;
|
color: #374151;
|
||||||
}
|
}
|
||||||
|
|
||||||
.delete-warning {
|
.delete-warning {
|
||||||
font-size: 14px;
|
font-size: 14px;
|
||||||
color: #ef4444;
|
color: #ef4444;
|
||||||
|
|
@ -6783,7 +6726,6 @@ const findNodeInData = (nodeData, targetId) => {
|
||||||
font-size: 10px;
|
font-size: 10px;
|
||||||
color: #666;
|
color: #666;
|
||||||
}
|
}
|
||||||
|
|
||||||
.new-image-preview {
|
.new-image-preview {
|
||||||
margin-top: 16px;
|
margin-top: 16px;
|
||||||
padding: 12px;
|
padding: 12px;
|
||||||
|
|
@ -6838,7 +6780,6 @@ const findNodeInData = (nodeData, targetId) => {
|
||||||
.cancel-button:hover {
|
.cancel-button:hover {
|
||||||
background: #5a6268;
|
background: #5a6268;
|
||||||
}
|
}
|
||||||
|
|
||||||
.save-button {
|
.save-button {
|
||||||
padding: 8px 20px;
|
padding: 8px 20px;
|
||||||
background: #660874;
|
background: #660874;
|
||||||
|
|
|
||||||
|
|
@ -50,6 +50,9 @@ const initVditor = async () => {
|
||||||
enable: false, // 禁用缓存
|
enable: false, // 禁用缓存
|
||||||
id: 'vditor-' + Date.now() // 添加唯一的缓存ID
|
id: 'vditor-' + Date.now() // 添加唯一的缓存ID
|
||||||
},
|
},
|
||||||
|
// 某些版本要求提供该回调,否则会报 customwysiwygToolbar is not a function
|
||||||
|
// 这里提供一个空实现,保持兼容
|
||||||
|
customWysiwygToolbar: () => {},
|
||||||
preview: {
|
preview: {
|
||||||
theme: {
|
theme: {
|
||||||
current: 'light'
|
current: 'light'
|
||||||
|
|
@ -61,6 +64,11 @@ const initVditor = async () => {
|
||||||
fieldName: 'file',
|
fieldName: 'file',
|
||||||
...props.upload
|
...props.upload
|
||||||
},
|
},
|
||||||
|
// 用内置 input 回调代替实例 .on('input'),兼容构建差异
|
||||||
|
input: (content) => {
|
||||||
|
emit('update:value', content)
|
||||||
|
emit('change', content)
|
||||||
|
},
|
||||||
toolbar: [
|
toolbar: [
|
||||||
'emoji',
|
'emoji',
|
||||||
'headings',
|
'headings',
|
||||||
|
|
@ -112,12 +120,6 @@ const initVditor = async () => {
|
||||||
if (props.value) {
|
if (props.value) {
|
||||||
vditorInstance.setValue(props.value)
|
vditorInstance.setValue(props.value)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 监听内容变化
|
|
||||||
vditorInstance.on('input', (content) => {
|
|
||||||
emit('update:value', content)
|
|
||||||
emit('change', content)
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
|
|
||||||
|
|
@ -72,7 +72,7 @@ export default function (mind: MindElixirInstance) {
|
||||||
const topic = target as Topic
|
const topic = target as Topic
|
||||||
|
|
||||||
// 优先检查是否是表格节点(表格也是富文本内容的一种)
|
// 优先检查是否是表格节点(表格也是富文本内容的一种)
|
||||||
if (topic.nodeObj?.dangerouslySetInnerHTML && topic.innerHTML.includes('<table')) {
|
if (((topic.nodeObj?.topic && /<\w+[^>]*>/.test(topic.nodeObj.topic)) || topic.innerHTML.includes('<table')) && topic.innerHTML.includes('<table')) {
|
||||||
console.log('📊 双击表格节点,准备编辑:', topic.nodeObj.topic)
|
console.log('📊 双击表格节点,准备编辑:', topic.nodeObj.topic)
|
||||||
if (mind.editable) {
|
if (mind.editable) {
|
||||||
mind.beginEdit(target)
|
mind.beginEdit(target)
|
||||||
|
|
@ -90,15 +90,13 @@ export default function (mind: MindElixirInstance) {
|
||||||
}
|
}
|
||||||
|
|
||||||
// 检查节点是否有富文本内容(但不包括表格)
|
// 检查节点是否有富文本内容(但不包括表格)
|
||||||
if (topic.nodeObj?.dangerouslySetInnerHTML && !topic.innerHTML.includes('<table')) {
|
if ((topic.nodeObj?.topic && /<\w+[^>]*>/.test(topic.nodeObj.topic)) && !topic.innerHTML.includes('<table')) {
|
||||||
console.log('📝 双击富文本节点,准备编辑:', topic.nodeObj?.topic || '')
|
console.log('📝 双击富文本节点,准备编辑:', topic.nodeObj?.topic || '')
|
||||||
mind.bus.fire('showRichTextEditor', topic.nodeObj, topic)
|
mind.bus.fire('showRichTextEditor', topic.nodeObj, topic)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
// 如果没有图片或富文本内容,则进入普通编辑模式
|
// 如果没有图片或富文本内容:也进入富文本编辑器
|
||||||
// 使用宿主应用的自定义编辑器(如果已集成)
|
|
||||||
// 通过事件总线通知外层打开富文本编辑器
|
|
||||||
mind.bus.fire('showRichTextEditor', topic.nodeObj, topic)
|
mind.bus.fire('showRichTextEditor', topic.nodeObj, topic)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -304,14 +304,13 @@ export const beginEdit = function (this: MindElixirInstance, el?: Topic) {
|
||||||
const nodeEle = el || this.currentNode
|
const nodeEle = el || this.currentNode
|
||||||
if (!nodeEle) return
|
if (!nodeEle) return
|
||||||
|
|
||||||
// 检查是否是表格节点
|
// 检查是否是表格节点(基于 topic 的 HTML)
|
||||||
if (nodeEle.nodeObj.dangerouslySetInnerHTML) {
|
if (nodeEle.nodeObj.topic && /<\w+[^>]*>/.test(nodeEle.nodeObj.topic)) {
|
||||||
// 检查是否包含表格
|
|
||||||
if (nodeEle.innerHTML.includes('<table')) {
|
if (nodeEle.innerHTML.includes('<table')) {
|
||||||
this.editTableNode(nodeEle)
|
this.editTableNode(nodeEle)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
// 其他dangerouslySetInnerHTML节点暂时不支持编辑
|
// 其他富文本节点交由外层编辑器处理
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -100,11 +100,11 @@ export default function (mind: MindElixirInstance, option: true | ContextMenuOpt
|
||||||
|
|
||||||
// 检查节点是否有富文本内容,决定是否显示编辑选项
|
// 检查节点是否有富文本内容,决定是否显示编辑选项
|
||||||
const topic = target as Topic
|
const topic = target as Topic
|
||||||
const hasRichContent = topic.nodeObj?.image || topic.nodeObj?.dangerouslySetInnerHTML || topic.querySelector('img')
|
const hasRichContent = topic.nodeObj?.image || (topic.nodeObj?.topic && /<\w+[^>]*>/.test(topic.nodeObj.topic)) || topic.querySelector('img')
|
||||||
|
|
||||||
console.log('🔍 右键菜单检查富文本内容:', {
|
console.log('🔍 右键菜单检查富文本内容:', {
|
||||||
hasNodeImage: !!topic.nodeObj?.image,
|
hasNodeImage: !!topic.nodeObj?.image,
|
||||||
hasHTMLContent: !!topic.nodeObj?.dangerouslySetInnerHTML,
|
hasHTMLContent: !!(topic.nodeObj?.topic && /<\w+[^>]*>/.test(topic.nodeObj.topic || '')),
|
||||||
hasHTMLImage: !!topic.querySelector('img'),
|
hasHTMLImage: !!topic.querySelector('img'),
|
||||||
hasRichContent: !!hasRichContent
|
hasRichContent: !!hasRichContent
|
||||||
})
|
})
|
||||||
|
|
|
||||||
|
|
@ -445,10 +445,10 @@ function generateSvgTextUsingForeignObject(tpc: HTMLElement, tpcStyle: CSSStyleD
|
||||||
const tpcWithNodeObj = tpc as Topic
|
const tpcWithNodeObj = tpc as Topic
|
||||||
let htmlContent = ''
|
let htmlContent = ''
|
||||||
|
|
||||||
// 优先使用dangerouslySetInnerHTML,其次使用text.innerHTML
|
// 优先使用 node.topic 作为 HTML,其次使用 text.innerHTML
|
||||||
if (tpcWithNodeObj.nodeObj && tpcWithNodeObj.nodeObj.dangerouslySetInnerHTML) {
|
if (tpcWithNodeObj.nodeObj && tpcWithNodeObj.nodeObj.topic && /<\w+[^>]*>/.test(tpcWithNodeObj.nodeObj.topic)) {
|
||||||
htmlContent = tpcWithNodeObj.nodeObj.dangerouslySetInnerHTML
|
htmlContent = tpcWithNodeObj.nodeObj.topic
|
||||||
console.log('🔍 使用dangerouslySetInnerHTML内容:', htmlContent.substring(0, 200))
|
console.log('🔍 使用topic(HTML)内容:', htmlContent.substring(0, 200))
|
||||||
} else if (tpcWithNodeObj.text && tpcWithNodeObj.text.innerHTML) {
|
} else if (tpcWithNodeObj.text && tpcWithNodeObj.text.innerHTML) {
|
||||||
htmlContent = tpcWithNodeObj.text.innerHTML
|
htmlContent = tpcWithNodeObj.text.innerHTML
|
||||||
console.log('🔍 使用text.innerHTML内容:', htmlContent.substring(0, 200))
|
console.log('🔍 使用text.innerHTML内容:', htmlContent.substring(0, 200))
|
||||||
|
|
@ -457,11 +457,7 @@ function generateSvgTextUsingForeignObject(tpc: HTMLElement, tpcStyle: CSSStyleD
|
||||||
const hasHTMLContent = htmlContent && htmlContent !== tpc.textContent
|
const hasHTMLContent = htmlContent && htmlContent !== tpc.textContent
|
||||||
const hasTableContent = htmlContent && htmlContent.includes('<table')
|
const hasTableContent = htmlContent && htmlContent.includes('<table')
|
||||||
|
|
||||||
console.log('🔍 HTML内容分析:', {
|
console.log('🔍 HTML内容分析:', { hasHTMLContent, hasTableContent, contentLength: htmlContent.length })
|
||||||
hasHTMLContent,
|
|
||||||
hasTableContent,
|
|
||||||
contentLength: htmlContent.length
|
|
||||||
})
|
|
||||||
|
|
||||||
// 如果包含表格,使用foreignObject方式渲染HTML表格
|
// 如果包含表格,使用foreignObject方式渲染HTML表格
|
||||||
if (hasTableContent) {
|
if (hasTableContent) {
|
||||||
|
|
@ -884,8 +880,8 @@ function convertDivToSvg(mei: MindElixirInstance, tpc: HTMLElement, useForeignOb
|
||||||
|
|
||||||
// 检查是否有HTML内容或节点图片,如果有则增加高度
|
// 检查是否有HTML内容或节点图片,如果有则增加高度
|
||||||
const tpcWithNodeObj2 = tpc as Topic
|
const tpcWithNodeObj2 = tpc as Topic
|
||||||
const hasHTMLContent2 = tpcWithNodeObj2.nodeObj && tpcWithNodeObj2.nodeObj.dangerouslySetInnerHTML
|
const hasHTMLContent2 = tpcWithNodeObj2.nodeObj && tpcWithNodeObj2.nodeObj.topic
|
||||||
const hasImages2 = hasHTMLContent2 && tpcWithNodeObj2.nodeObj.dangerouslySetInnerHTML?.includes('<img')
|
const hasImages2 = hasHTMLContent2 && tpcWithNodeObj2.nodeObj.topic?.includes('<img')
|
||||||
const hasNodeImage2 = tpcWithNodeObj2.nodeObj && tpcWithNodeObj2.nodeObj.image
|
const hasNodeImage2 = tpcWithNodeObj2.nodeObj && tpcWithNodeObj2.nodeObj.image
|
||||||
|
|
||||||
const g = document.createElementNS(ns, 'g')
|
const g = document.createElementNS(ns, 'g')
|
||||||
|
|
@ -900,17 +896,17 @@ function convertDivToSvg(mei: MindElixirInstance, tpc: HTMLElement, useForeignOb
|
||||||
|
|
||||||
// 检查是否有dangerouslySetInnerHTML内容
|
// 检查是否有dangerouslySetInnerHTML内容
|
||||||
const tpcWithNodeObj3 = tpc as Topic
|
const tpcWithNodeObj3 = tpc as Topic
|
||||||
const hasTableContent3 = tpcWithNodeObj3.nodeObj && tpcWithNodeObj3.nodeObj.dangerouslySetInnerHTML && tpcWithNodeObj3.nodeObj.dangerouslySetInnerHTML.includes('<table')
|
const hasTableContent3 = tpcWithNodeObj3.nodeObj && tpcWithNodeObj3.nodeObj.topic && tpcWithNodeObj3.nodeObj.topic.includes('<table')
|
||||||
|
|
||||||
console.log('🔍 convertDivToSvg 表格检测:', {
|
console.log('🔍 convertDivToSvg 表格检测:', {
|
||||||
hasNodeObj: !!tpcWithNodeObj3.nodeObj,
|
hasNodeObj: !!tpcWithNodeObj3.nodeObj,
|
||||||
hasDangerouslySetInnerHTML: !!(tpcWithNodeObj3.nodeObj && tpcWithNodeObj3.nodeObj.dangerouslySetInnerHTML),
|
hasTopicHtml: !!(tpcWithNodeObj3.nodeObj && tpcWithNodeObj3.nodeObj.topic),
|
||||||
hasTableContent3: hasTableContent3,
|
hasTableContent3: hasTableContent3,
|
||||||
content: tpcWithNodeObj3.nodeObj?.dangerouslySetInnerHTML?.substring(0, 100)
|
content: tpcWithNodeObj3.nodeObj?.topic?.substring(0, 100)
|
||||||
})
|
})
|
||||||
|
|
||||||
if (tpcWithNodeObj3.nodeObj && tpcWithNodeObj3.nodeObj.dangerouslySetInnerHTML) {
|
if (tpcWithNodeObj3.nodeObj && tpcWithNodeObj3.nodeObj.topic) {
|
||||||
console.log('🔍 处理dangerouslySetInnerHTML内容:', tpcWithNodeObj3.nodeObj.dangerouslySetInnerHTML.substring(0, 200))
|
console.log('🔍 处理topic(HTML)内容:', tpcWithNodeObj3.nodeObj.topic.substring(0, 200))
|
||||||
|
|
||||||
if (hasTableContent3) {
|
if (hasTableContent3) {
|
||||||
console.log('✅ 检测到表格内容,使用foreignObject方式渲染')
|
console.log('✅ 检测到表格内容,使用foreignObject方式渲染')
|
||||||
|
|
|
||||||
|
|
@ -27,6 +27,13 @@ export const shapeTpc = function (this: MindElixirInstance, tpc: Topic, nodeObj:
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 优先使用 topic 作为渲染 HTML
|
||||||
|
if (nodeObj.topic && /<\w+[^>]*>/.test(nodeObj.topic)) {
|
||||||
|
tpc.innerHTML = nodeObj.topic
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
// 兼容:如果存在旧字段,按旧逻辑处理
|
||||||
if (nodeObj.dangerouslySetInnerHTML) {
|
if (nodeObj.dangerouslySetInnerHTML) {
|
||||||
// 检查是否是Markdown内容(包含表格、图片等)
|
// 检查是否是Markdown内容(包含表格、图片等)
|
||||||
const content = nodeObj.dangerouslySetInnerHTML
|
const content = nodeObj.dangerouslySetInnerHTML
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import { marked } from 'marked';
|
||||||
import Prism from 'prismjs';
|
import Prism from 'prismjs';
|
||||||
import katex from 'katex';
|
import katex from 'katex';
|
||||||
import Vditor from 'vditor';
|
import Vditor from 'vditor';
|
||||||
|
import DOMPurify from 'dompurify';
|
||||||
import 'prismjs/components/prism-javascript';
|
import 'prismjs/components/prism-javascript';
|
||||||
import 'prismjs/components/prism-css';
|
import 'prismjs/components/prism-css';
|
||||||
import 'prismjs/components/prism-json';
|
import 'prismjs/components/prism-json';
|
||||||
|
|
@ -88,29 +89,56 @@ export const renderMarkdownToHTML = (markdown) => {
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
// 预处理markdown
|
// 预处理markdown(包含宽容的表格归一化 + 数学公式处理)
|
||||||
const processedMarkdown = preprocessMarkdown(markdown);
|
const processedMarkdown = preprocessMarkdown(markdown);
|
||||||
|
|
||||||
// 使用marked渲染
|
// 稳妥处理“HTML 表格 + Markdown 混排”:表格块保留,其他块按 Markdown 渲染
|
||||||
const html = marked.parse(processedMarkdown);
|
const segments = splitByHtmlTables(processedMarkdown);
|
||||||
|
const renderedParts = segments.map(seg => seg.isTable ? seg.content : marked.parse(seg.content || ''));
|
||||||
|
const mixedHTML = renderedParts.join('');
|
||||||
|
|
||||||
// 后处理HTML
|
// 后处理 + 安全净化
|
||||||
const finalHTML = postprocessHTML(html);
|
const finalHTML = postprocessHTML(mixedHTML);
|
||||||
|
return sanitizeHTML(finalHTML);
|
||||||
return finalHTML;
|
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.error('Markdown渲染失败:', error);
|
console.error('Markdown渲染失败:', error);
|
||||||
return `<div class="markdown-error">渲染失败: ${error.message}</div>`;
|
return `<div class="markdown-error">渲染失败: ${error.message}</div>`;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* HTML 安全净化
|
||||||
|
* @param {string} html
|
||||||
|
* @returns {string}
|
||||||
|
*/
|
||||||
|
export const sanitizeHTML = (html) => {
|
||||||
|
try {
|
||||||
|
return DOMPurify.sanitize(html, {
|
||||||
|
ALLOWED_ATTR: [
|
||||||
|
'href','src','alt','title','width','height','style','class','target','rel','colspan','rowspan','align'
|
||||||
|
],
|
||||||
|
ALLOWED_TAGS: [
|
||||||
|
'div','span','p','h1','h2','h3','h4','h5','h6','ul','ol','li','strong','em','code','pre','br','hr',
|
||||||
|
'table','thead','tbody','tr','th','td','img','a','blockquote'
|
||||||
|
],
|
||||||
|
FORBID_ATTR: [/^on/i],
|
||||||
|
FORBID_TAGS: ['script','iframe','object','embed']
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('sanitize 失败,使用原始HTML', e);
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 预处理markdown内容
|
* 预处理markdown内容
|
||||||
* @param {string} markdown - 原始markdown
|
* @param {string} markdown - 原始markdown
|
||||||
* @returns {string} 处理后的markdown
|
* @returns {string} 处理后的markdown
|
||||||
*/
|
*/
|
||||||
const preprocessMarkdown = (markdown) => {
|
const preprocessMarkdown = (markdown) => {
|
||||||
return markdown
|
// 宽容表格归一化 + 异常字符替换
|
||||||
|
const normalized = normalizeMarkdownTables(replaceAmbiguousChars(String(markdown ?? '')));
|
||||||
|
return normalized
|
||||||
// 处理块级数学公式($$...$$)
|
// 处理块级数学公式($$...$$)
|
||||||
.replace(/\$\$([\s\S]*?)\$\$/g, (match, formula) => {
|
.replace(/\$\$([\s\S]*?)\$\$/g, (match, formula) => {
|
||||||
try {
|
try {
|
||||||
|
|
@ -146,6 +174,117 @@ const preprocessMarkdown = (markdown) => {
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 粗略判断 HTML 表格
|
||||||
|
const looksLikeHTMLTable = (input) => {
|
||||||
|
const s = String(input ?? '').trim();
|
||||||
|
if (!s || s.indexOf('<') === -1) return false;
|
||||||
|
if (/<\/?(table|thead|tbody|tr|td|th)\b/i.test(s)) return true;
|
||||||
|
try {
|
||||||
|
const doc = new DOMParser().parseFromString(s, 'text/html');
|
||||||
|
return !!doc.body.querySelector('table');
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 替换全角符号/不可见空白为 ASCII
|
||||||
|
const replaceAmbiguousChars = (s) => {
|
||||||
|
return s
|
||||||
|
.replace(/[\uFF5C\u2223\uFFE8]/g, '|') // 竖线
|
||||||
|
.replace(/[\u2014\u2015\u2212\uFF0D\u2500\u2013]/g, '-') // 横线
|
||||||
|
.replace(/[\u3000\u00A0\u200B\uFEFF]/g, ' '); // 空白
|
||||||
|
};
|
||||||
|
|
||||||
|
// 宽容修复 Markdown 表格:插入分隔行/统一列数/移除缩进
|
||||||
|
export const normalizeMarkdownTables = (input) => {
|
||||||
|
const lines = String(input).split('\n');
|
||||||
|
const out = [];
|
||||||
|
let inFence = false;
|
||||||
|
const isTableLike = (l) => (l.replace(/\\\|/g, '').match(/\|/g) || []).length >= 2;
|
||||||
|
|
||||||
|
for (let i = 0; i < lines.length; i++) {
|
||||||
|
let line = lines[i];
|
||||||
|
if (/^\s*```/.test(line)) { inFence = !inFence; out.push(line); continue; }
|
||||||
|
if (inFence) { out.push(line); continue; }
|
||||||
|
|
||||||
|
if (isTableLike(line)) {
|
||||||
|
const header = line.replace(/^\t|^ {1,4}/, '').trim();
|
||||||
|
// 向前看整个表格块的结束位置 j
|
||||||
|
let j = i + 1;
|
||||||
|
while (j <= lines.length - 1 && isTableLike(lines[j])) j++;
|
||||||
|
const nextLine = i + 1 < lines.length ? lines[i + 1] : '';
|
||||||
|
const cellCount = header.split('|').filter(c => c.trim() !== '').length;
|
||||||
|
const hasSeparator = /^\s*\|?\s*[:\-\| ]+\|?\s*$/.test(nextLine);
|
||||||
|
|
||||||
|
// 输出表头与标准化分隔行
|
||||||
|
out.push(header);
|
||||||
|
const normSep = '|' + Array.from({ length: cellCount }).map(() => ' --- ').join('|') + '|';
|
||||||
|
out.push(normSep);
|
||||||
|
|
||||||
|
// 从 i+1 开始直到 j-1,逐行输出数据行。
|
||||||
|
// 遇到图片行,暂存到表格外缓冲,等整个表格结束后统一追加,避免把表格切成多段。
|
||||||
|
const outsideBuffer = [];
|
||||||
|
let lastRowCells = null; // 记录上一次输出的表格行单元格,用于处理续行
|
||||||
|
let lastRowOutIndex = -1;
|
||||||
|
for (let k = i + 1; k < j; k++) {
|
||||||
|
const rowLine = lines[k];
|
||||||
|
if (containsMarkdownImage(rowLine)) {
|
||||||
|
outsideBuffer.push(stripPipes(rowLine));
|
||||||
|
} else if (!hasSeparator && k === i + 1) {
|
||||||
|
// 原始没有分隔行的情况,第一行按数据行处理
|
||||||
|
const fixed = fixTableRow(rowLine, cellCount);
|
||||||
|
out.push(fixed);
|
||||||
|
lastRowCells = fixed.slice(1, -1).split('|').map(c => c.trim());
|
||||||
|
lastRowOutIndex = out.length - 1;
|
||||||
|
} else if (hasSeparator && k === i + 1) {
|
||||||
|
// 原分隔行跳过(我们已输出规范分隔行)
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
if (isTableLike(rowLine)) {
|
||||||
|
const fixed = fixTableRow(rowLine, cellCount);
|
||||||
|
out.push(fixed);
|
||||||
|
lastRowCells = fixed.slice(1, -1).split('|').map(c => c.trim());
|
||||||
|
lastRowOutIndex = out.length - 1;
|
||||||
|
} else if (rowLine.trim() !== '' && lastRowCells && lastRowOutIndex >= 0) {
|
||||||
|
// 续行:把没有管道的行视为上一行最后一个单元格的补充内容
|
||||||
|
const addon = stripPipes(rowLine).replace(/\s+/g, ' ').trim();
|
||||||
|
const lastIdx = lastRowCells.length - 1;
|
||||||
|
lastRowCells[lastIdx] = `${lastRowCells[lastIdx]} <br> ${addon}`.trim();
|
||||||
|
// 重建上一行并覆盖
|
||||||
|
const rebuilt = '|' + lastRowCells.map(c => ` ${c} `).join('|') + '|';
|
||||||
|
out[lastRowOutIndex] = rebuilt;
|
||||||
|
} else {
|
||||||
|
// 非法续行,作为表外段落
|
||||||
|
if (rowLine.trim()) outsideBuffer.push(stripPipes(rowLine));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 表格块结束后,先空一行,再把表内剥离的图片以表格外段落统一追加
|
||||||
|
out.push('');
|
||||||
|
if (outsideBuffer.length) {
|
||||||
|
out.push(outsideBuffer.join('\n\n'));
|
||||||
|
out.push('');
|
||||||
|
}
|
||||||
|
i = j - 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
out.push(line);
|
||||||
|
}
|
||||||
|
return out.join('\n');
|
||||||
|
};
|
||||||
|
|
||||||
|
const fixTableRow = (row, cellCount) => {
|
||||||
|
const cells = row.replace(/^\t|^ {1,4}/, '').split('|');
|
||||||
|
const filtered = cells.filter((c, idx) => !(idx === 0 && c.trim() === '') && !(idx === cells.length - 1 && c.trim() === ''));
|
||||||
|
while (filtered.length < cellCount) filtered.push(' ');
|
||||||
|
return '|' + filtered.slice(0, cellCount).map(c => ' ' + c.trim() + ' ').join('|') + '|';
|
||||||
|
};
|
||||||
|
|
||||||
|
const containsMarkdownImage = (line) => /!\[[^\]]*\]\([^\)]+\)/.test(line);
|
||||||
|
const stripPipes = (line) => line.replace(/^\s*\|/, '').replace(/\|\s*$/, '').replace(/\s*\|\s*/g, ' ').trim();
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 后处理HTML内容
|
* 后处理HTML内容
|
||||||
* @param {string} html - 渲染后的HTML
|
* @param {string} html - 渲染后的HTML
|
||||||
|
|
@ -158,10 +297,35 @@ const postprocessHTML = (html) => {
|
||||||
// 为代码块添加样式类
|
// 为代码块添加样式类
|
||||||
.replace(/<pre><code/g, '<pre class="markdown-code"><code');
|
.replace(/<pre><code/g, '<pre class="markdown-code"><code');
|
||||||
|
|
||||||
// 创建临时DOM元素来处理语法高亮
|
// 创建临时DOM元素来处理语法高亮与表格修复
|
||||||
const tempDiv = document.createElement('div');
|
const tempDiv = document.createElement('div');
|
||||||
tempDiv.innerHTML = processedHTML;
|
tempDiv.innerHTML = processedHTML;
|
||||||
|
|
||||||
|
// 表格结构修复与规范化:
|
||||||
|
// 1) 将表格中的独立图片移出到表格之后
|
||||||
|
// 2) 将只有一个单元格的“行”移出表格,避免出现单列行
|
||||||
|
// 3) 补齐 thead/tbody(若缺失由浏览器自动纠正)
|
||||||
|
try {
|
||||||
|
normalizeHTMLTablesInDocument(tempDiv);
|
||||||
|
} catch (err) {
|
||||||
|
console.warn('表格后处理失败,跳过修复:', err);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 对被从表格中移出的段落/图片做二次 Markdown 渲染(确保诸如 `- 列表`、`![图]()` 被正确转为 HTML)
|
||||||
|
try {
|
||||||
|
const afterBlocks = tempDiv.querySelectorAll('.markdown-after-table, .markdown-outside-row');
|
||||||
|
afterBlocks.forEach((el) => {
|
||||||
|
// 只在内容看起来像 Markdown 时处理
|
||||||
|
const raw = el.textContent || el.innerHTML || '';
|
||||||
|
if (/!\[|^\s*[-*+]\s+|^\s*\d+\.\s+|^\s*#{1,6}\s+/m.test(raw)) {
|
||||||
|
const rendered = marked.parse(raw);
|
||||||
|
el.innerHTML = rendered;
|
||||||
|
}
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('表格后段落二次渲染失败:', e);
|
||||||
|
}
|
||||||
|
|
||||||
// 为代码块添加语法高亮
|
// 为代码块添加语法高亮
|
||||||
const codeBlocks = tempDiv.querySelectorAll('pre code');
|
const codeBlocks = tempDiv.querySelectorAll('pre code');
|
||||||
codeBlocks.forEach(block => {
|
codeBlocks.forEach(block => {
|
||||||
|
|
@ -178,6 +342,94 @@ const postprocessHTML = (html) => {
|
||||||
return tempDiv.innerHTML;
|
return tempDiv.innerHTML;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// 把输入按 <table>…</table> 进行切分,保留表格原样,其它部分作为 Markdown 片段
|
||||||
|
const splitByHtmlTables = (input) => {
|
||||||
|
const text = String(input ?? '');
|
||||||
|
const result = [];
|
||||||
|
const regex = /<table[\s\S]*?<\/table>/gi;
|
||||||
|
let lastIndex = 0;
|
||||||
|
let match;
|
||||||
|
while ((match = regex.exec(text)) !== null) {
|
||||||
|
const start = match.index;
|
||||||
|
const end = regex.lastIndex;
|
||||||
|
if (start > lastIndex) {
|
||||||
|
result.push({ isTable: false, content: text.slice(lastIndex, start) });
|
||||||
|
}
|
||||||
|
result.push({ isTable: true, content: match[0] });
|
||||||
|
lastIndex = end;
|
||||||
|
}
|
||||||
|
if (lastIndex < text.length) {
|
||||||
|
result.push({ isTable: false, content: text.slice(lastIndex) });
|
||||||
|
}
|
||||||
|
if (result.length === 0) return [{ isTable: false, content: text }];
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
// 可复用:对传入 HTML 字符串做表格规范化
|
||||||
|
export const normalizeHTMLTables = (html) => {
|
||||||
|
try {
|
||||||
|
const container = document.createElement('div');
|
||||||
|
container.innerHTML = String(html ?? '');
|
||||||
|
normalizeHTMLTablesInDocument(container);
|
||||||
|
return container.innerHTML;
|
||||||
|
} catch {
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// 实际的 DOM 变换逻辑,既供 postprocess 调用,也供独立规范化使用
|
||||||
|
const normalizeHTMLTablesInDocument = (root) => {
|
||||||
|
const tables = Array.from(root.querySelectorAll('table'));
|
||||||
|
tables.forEach((table) => {
|
||||||
|
const moveAfter = (nodes) => {
|
||||||
|
if (!nodes || nodes.length === 0) return;
|
||||||
|
const after = document.createElement('div');
|
||||||
|
after.className = 'markdown-after-table';
|
||||||
|
nodes.forEach((n) => after.appendChild(n));
|
||||||
|
table.insertAdjacentElement('afterend', after);
|
||||||
|
};
|
||||||
|
|
||||||
|
// 将表格内图片整体移出,保持图片与表格分离
|
||||||
|
const imgs = Array.from(table.querySelectorAll('img'));
|
||||||
|
if (imgs.length) {
|
||||||
|
moveAfter(imgs.map((img) => img.parentElement && img.parentElement !== table ? (img.parentElement.removeChild(img), img) : img));
|
||||||
|
}
|
||||||
|
|
||||||
|
const rows = Array.from(table.querySelectorAll('tr'));
|
||||||
|
const expectedCols = rows.reduce((max, tr) => Math.max(max, tr.querySelectorAll('th,td').length), 0);
|
||||||
|
|
||||||
|
rows.forEach((tr) => {
|
||||||
|
const cells = tr.querySelectorAll('th,td');
|
||||||
|
if (cells.length <= 1) {
|
||||||
|
const wrapper = document.createElement('div');
|
||||||
|
wrapper.className = 'markdown-outside-row';
|
||||||
|
while (tr.firstChild) wrapper.appendChild(tr.firstChild);
|
||||||
|
tr.remove();
|
||||||
|
table.insertAdjacentElement('afterend', wrapper);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const text = tr.textContent ? tr.textContent.trim() : '';
|
||||||
|
if (expectedCols >= 2 && cells.length === 1 && text.length > 80) {
|
||||||
|
const wrapper = document.createElement('div');
|
||||||
|
wrapper.className = 'markdown-outside-row';
|
||||||
|
while (tr.firstChild) wrapper.appendChild(tr.firstChild);
|
||||||
|
tr.remove();
|
||||||
|
table.insertAdjacentElement('afterend', wrapper);
|
||||||
|
}
|
||||||
|
// 仅包含图片或仅空白的行,移除以消除表格中的空行/图片行
|
||||||
|
const onlyImages = Array.from(tr.querySelectorAll('td,th')).every((c) => c.children.length === 1 && c.querySelector('img'));
|
||||||
|
const isEmptyRow = text === '' && Array.from(tr.querySelectorAll('td,th')).every((c) => (c.textContent || '').trim() === '');
|
||||||
|
if (onlyImages || isEmptyRow) {
|
||||||
|
const after = document.createElement('div');
|
||||||
|
after.className = onlyImages ? 'markdown-after-table images-row' : 'markdown-after-table empty-row';
|
||||||
|
while (tr.firstChild) after.appendChild(tr.firstChild);
|
||||||
|
tr.remove();
|
||||||
|
table.insertAdjacentElement('afterend', after);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 为Mind Elixir节点设置markdown内容
|
* 为Mind Elixir节点设置markdown内容
|
||||||
* @param {HTMLElement} nodeElement - 节点DOM元素
|
* @param {HTMLElement} nodeElement - 节点DOM元素
|
||||||
|
|
@ -659,6 +911,25 @@ export const updateNodeContent = (nodeElement, newMarkdownContent) => {
|
||||||
renderNodeWithVditor(nodeElement, newMarkdownContent);
|
renderNodeWithVditor(nodeElement, newMarkdownContent);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 统一更新入口:从 markdown 生成 html 并触发 rerender
|
||||||
|
* @param {object} node - 节点对象(带 topic/markdown)
|
||||||
|
* @param {string} markdown - 新 markdown
|
||||||
|
* @param {any} mindElixirInstance - 可选实例,用于刷新
|
||||||
|
*/
|
||||||
|
export const updateNodeModelAndRefresh = (node, markdown, mindElixirInstance) => {
|
||||||
|
if (!node) return;
|
||||||
|
node.markdown = markdown || '';
|
||||||
|
node.topic = renderMarkdownToHTML(node.markdown);
|
||||||
|
try {
|
||||||
|
if (mindElixirInstance && typeof mindElixirInstance.render === 'function') {
|
||||||
|
mindElixirInstance.render();
|
||||||
|
}
|
||||||
|
} catch (e) {
|
||||||
|
console.warn('刷新思维导图失败:', e);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 同步渲染(兼容旧代码)
|
* 同步渲染(兼容旧代码)
|
||||||
* @param {string} content - 节点内容
|
* @param {string} content - 节点内容
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue