reference/scripts/utils/tooltips.mjs

63 lines
2.0 KiB
JavaScript
Raw Normal View History

/**
* 配置 tooltips 注释
2022-10-29 00:24:39 +08:00
*
* ```markdown
* - [超链接有 tooltips 提示](#1xx-information) _Tooltips 展示内容_ <!--rehype:tooltips-->
* ```
2022-10-29 00:24:39 +08:00
*
* 上面示例 Tooltips 展示内容 放到 前一个 `<a>` dom 节点作为子节点
2022-10-29 00:24:39 +08:00
*
* - 注释配置的前一个节点 AA 的前一个节点 B
* - 如果 A B 其中一个不存在 `tooltips` 将失效
2022-10-29 00:24:39 +08:00
* - 设置 B 的类名称为 tooltips
*/
export function tooltips(node, index, parent) {
if (node.type === 'comment' && parent?.children.length > 2) {
const childs = parent?.children;
const result = [];
let recordPos = false; // 记录位置
let tooltipNode = null;
2022-10-29 00:24:39 +08:00
for (let i = childs.length; i > -1; i--) {
const node = childs[i];
// 记录 tooltip 的开始位置
if (node?.type === 'comment' && node?.value === 'rehype:tooltips') {
recordPos = true;
2022-10-29 00:24:39 +08:00
continue;
}
// 记录 tooltip 的 node
if (recordPos && !tooltipNode) {
if (node.type === 'comment' || (node.type === 'text' && !node?.value?.replace(/\s\n/g, ''))) {
recordPos = false;
}
if (recordPos && node.type === 'element') {
tooltipNode = node;
tooltipNode.properties['class'] = 'tooltiptext';
delete tooltipNode.position;
2022-10-29 00:24:39 +08:00
continue;
}
}
// 将 tooltip 节点,插入到下一个 element 节点的子节点中
if (tooltipNode) {
if (node.type === 'comment' || (node.type === 'text' && !node?.value?.replace(/\s\n/g, ''))) {
recordPos = false;
2022-10-29 00:24:39 +08:00
tooltipNode = null;
}
if (tooltipNode && node?.type === 'element') {
recordPos = false;
node.properties['class'] = 'tooltip';
node.children.push(tooltipNode);
2022-10-29 00:24:39 +08:00
tooltipNode = null;
}
}
if (!recordPos && node) {
2022-10-29 00:24:39 +08:00
result.push(node);
}
}
if (parent) {
parent.children = [...result.reverse()];
}
}
}
2022-10-29 00:24:39 +08:00
export function getPreviewNode() {}