[js] 限制数据库换行文本最大行数

效果是将开启了换行的字段文本限制为仅显示前 3 行(这个数值可以改),如果文本超出 3 行,鼠标悬浮在单元格上时可以在悬浮提示中看到完整的文本

image.png

// 限制数据库换行文本最大行数 JS片段 - author: JeffreyChen

(function() {
  var animationFrameRequestId = null; // 用于存储 requestAnimationFrame 的 ID
  const rowsSelector = '.av__row:not(.av__row--header) ';

  // 获取当前单元格的函数
  function getCurrentCells() {
    return Array.from(document.querySelectorAll(rowsSelector + '.av__cell[data-wrap="true"]'));
  }

  // 计算单元格内所有文本元素的总高度的函数
  function calculateTotalHeight(cell) {
    const textElements = Array.from(cell.querySelectorAll('.av__celltext'));
    const tempSpan = document.createElement('span');
    tempSpan.style.visibility = 'hidden';
    tempSpan.style.display = 'block';

    // 根据 data-dtype 属性设置 whiteSpace 样式
    if (cell.dataset.dtype === 'relation' || cell.dataset.dtype === 'rollup') {
      tempSpan.style.whiteSpace = 'normal'; // 对于 relation 和 rollup
    } else {
      tempSpan.style.whiteSpace = 'pre-wrap'; // 其他情况使用 pre-wrap
    }

    cell.appendChild(tempSpan); // 将其附加到单元格以便准确测量

    // 将所有文本内容与分隔符 ", " 组合
    const combinedText = textElements.map(textElement => textElement.textContent.trim()).join(', ');

    tempSpan.textContent = combinedText; // 设置组合文本以进行高度计算
    const totalHeight = tempSpan.scrollHeight; // 获取总高度

    // 清理临时 span
    cell.removeChild(tempSpan);
    return totalHeight;
  }

  function updateAriaLabels(cells) {
    if (animationFrameRequestId !== null) {
      cancelAnimationFrame(animationFrameRequestId);
    }
    animationFrameRequestId = requestAnimationFrame(function() {
      cells.forEach(cell => {
        const currentLabel = cell.getAttribute('aria-label');
        const totalHeight = calculateTotalHeight(cell);
        const isTruncated = totalHeight > cell.clientHeight;

        // 将所有文本组合成一个字符串以用于 aria-label
        const textElements = cell.querySelectorAll('.av__celltext');
        let combinedText;

        // 特殊处理 .av__cell[data-dtype="relation"] 和 .av__cell[data-dtype="rollup"] 元素
        if (cell.dataset.dtype === 'relation' || cell.dataset.dtype === 'rollup') {
          combinedText = Array.from(textElements).map(textElement => {
            // 获取文本并替换换行符
            const cleanedText = textElement.textContent.replace(/\n+/g, ' ').trim();
            return cleanedText;
          }).join(',\n');
        } else {
          combinedText = Array.from(textElements).map(textElement => textElement.textContent.trim()).join(', ');
        }

        // 根据组合文本长度更新 aria-label
        if (isTruncated && !currentLabel) {
          cell.setAttribute('aria-label', combinedText);
        } else if (!isTruncated && currentLabel) {
          cell.removeAttribute('aria-label');
        }
      });
      animationFrameRequestId = null;
    });
  }

  function deferredUpdateAriaLabels() {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      const cells = getCurrentCells();
      updateAriaLabels(cells);
    }, 500); // 500 毫秒延时。
  }

  // 判断脚本是否开启 https://ld246.com/article/1726930314271
  // 通过唯一标志符判断是否启用此脚本,注释中的uuid不要删除,也可以改成其他全局唯一字符串
  // 也可以通过/api/snippet/getSnippet来判断脚本开启状态,这里采用判断脚本是否存在的方式
  // 调用方式 isEnabled()
  let scriptId = '';
  function isEnabled(keyword = '限制数据库换行文本最大行数-b6fb408a-d400-4874-b357-06fcdce67ca6') {
    if(!siyuan.config.snippet.enabledJS) return false;
    const script = scriptId ? document.getElementById(scriptId) : null;
    if(script) return true;
    const scripts = document.head.querySelectorAll("script[id^=snippetJS]");
    for (var i = 0; i < scripts.length; i++) {
        // 限制数据库换行文本最大行数-b6fb408a-d400-4874-b357-06fcdce67ca6
        if (scripts[i].textContent.indexOf('// ' + keyword) !== -1) {
          scriptId = scripts[i].id;
          return true;
        }
    }
    return false;
  }

  var timeoutId = null;

  // 定期检查 .layout__center 是否存在于 DOM 中
  function checkForLayoutCenter() {
    const targetNode = document.querySelector('.layout__center');
    if (targetNode) {
        startObserving(targetNode);
    } else {
        // 如果未找到,则每 200 毫秒重试
        setTimeout(checkForLayoutCenter, 200);
    }
  }

  function startObserving(targetNode) {
    // 创建一个新的 MutationObserver 实例,观察 .layout__center 元素
    const observer = new MutationObserver((mutations) => {
        if(!isEnabled()) { // 判断脚本是否开启
            if(observer) observer.disconnect();
            if(timeoutId) clearTimeout(timeoutId);
            if(animationFrameRequestId) cancelAnimationFrame(animationFrameRequestId);
            return;
          }    
        for (let mutation of mutations) {
        if (mutation.type === 'attributes') {
          const target = mutation.target;
          // 数据库渲染检查
          if (target.classList.contains('av') && target.getAttribute('data-render') === 'true') {
            deferredUpdateAriaLabels();
          // 列头调整或切换页签检查
          } else if (target.classList.contains('av__cell--header') && target.getAttribute('data-wrap') === 'true' || target.classList.contains('item--focus')) {
            deferredUpdateAriaLabels();
          }
        }
      }
    });

    // 配置并开始观察
    const config = { attributes: true, childList: false, subtree: true };
    observer.observe(targetNode, config);

    // 脚本启用后立即对当前 DOM 进行一次操作
    const cells = getCurrentCells();
    updateAriaLabels(cells);
  }

  checkForLayoutCenter(); // 开始检查 .layout__center 是否存在

  // 创建并添加 CSS 代码
  const style = document.createElement('style');
  style.textContent = `
  /* 限制数据库换行文本最大行数 CSS片段 */
  .av__row:not(.av__row--header) .av__cell[data-wrap="true"]:not([data-dtype="relation"]):not([data-dtype="rollup"]):not([data-dtype="mAsset"]) {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 最多3行 */
    overflow: hidden;
  }
  .av__celltext--ref {
    border-bottom: 0px;
    text-decoration: underline; /* 下划线 */
    text-decoration-color: rgb(0 202 255 / 85%); /* 浅蓝色 */
    text-decoration-thickness: 2px;
  }
  /* 针对关联字段、汇总字段 */
  .av__row:not(.av__row--header) .av__cell[data-wrap="true"][data-dtype="relation"],
  .av__row:not(.av__row--header) .av__cell[data-wrap="true"][data-dtype="rollup"] {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 最多3行 */
    overflow: hidden;
    white-space: normal;
  }
  /* 资源字段变为滚动容器 */
  .av__row:not(.av__row--header) .av__cell[data-wrap="true"][data-dtype="mAsset"] {
    display: -webkit-box;
    -webkit-box-orient: vertical;
    -webkit-line-clamp: 3; /* 最多3行 */
    text-overflow: clip; /* 用于去掉多余的 "..." ,但不起效,要等 CSS4 再看有没有合适的 CSS 属性*/
    overflow: auto;
    overflow-x: hidden;
  }
  `;
  document.head.appendChild(style);
})();
  • 思源笔记

    思源笔记是一款隐私优先的个人知识管理系统,支持完全离线使用,同时也支持端到端加密同步。

    融合块、大纲和双向链接,重构你的思维。

    21193 引用 • 83520 回帖 • 1 关注
  • 代码片段

    代码片段是一段 CSS 或 JS 的代码,这些代码会在思源笔记加载时自动执行,用于改善笔记的样式或功能。

    用户在分享内容时请在帖子标题前添加 [css][js] 作为标签

    12 引用 • 62 回帖 • 3 关注

相关帖子

欢迎来到这里!

我们正在构建一个小众社区,大家在这里相互信任,以平等 • 自由 • 奔放的价值观进行分享交流。最终,希望大家能够找到与自己志同道合的伙伴,共同成长。

注册 关于
请输入回帖内容 ...
  • 如果能改思源本身的话,只需要增加 3 行 JS 代码,用代码片段的话就得用几十行,性能还差 😭

    该回帖因已过时而被折叠
    1 操作
    JeffreyChen 在 2024-09-22 01:28:44 折叠了该回帖
  • 纯 CSS:

      .av__row:not(.av__row--header) .av__cell[data-wrap="true"]:not([data-block-id]) .av__celltext {
        display: -webkit-box;
        -webkit-box-orient: vertical;
        -webkit-line-clamp: 3; /* 最多3行 */
        overflow: hidden;
      }
    
    该回帖因已过时而被折叠
    1 操作
    JeffreyChen 在 2024-09-22 01:28:39 折叠了该回帖
  • 我自己用的版本:

    // 限制数据库换行文本最大行数 JS片段 - author: JeffreyChen
    
    var animationFrameRequestId = null; // 用于存储 requestAnimationFrame 的 ID
    function updateAriaLabels() { // 数据库渲染后所有 aria-label 属性都会丢失,所以直接全部添加即可
      // 如果已经有一个动画帧请求在等待,取消它
      if (animationFrameRequestId !== null) {
        cancelAnimationFrame(animationFrameRequestId);
      }
      animationFrameRequestId = requestAnimationFrame(function() {
        document.querySelectorAll('.av__row:not(.av__row--header) .av__cell[data-wrap="true"]').forEach(cell => {
          const textElement = cell.querySelector('.av__celltext'); // 查找包含文本的子元素
          // 检查父元素是否已有 aria-label 属性、是否是有效的 DOM 元素、文本是否被截断
          if (!cell.getAttribute('aria-label') && textElement && textElement.scrollHeight > textElement.clientHeight) {
            const text = textElement.textContent.trim();  // 提取文本
            cell.setAttribute('aria-label', text); // 为单元格添加 aria-label 属性
          }
        });
        // 重置 animationFrameRequestId,以便下次调用 updateAriaLabels 时可以检查
        animationFrameRequestId = null;
      });
    }
    function updateAriaLabels2() { // 调整列(宽)后 aria-label 仍然保留,需要逐个判断移除或者添加;调整列(宽)后切换到镜像数据库时也需要逐个判断移除或者添加
      // 如果已经有一个动画帧请求在等待,取消它
      if (animationFrameRequestId !== null) {
        cancelAnimationFrame(animationFrameRequestId);
      }
      animationFrameRequestId = requestAnimationFrame(function() {
        document.querySelectorAll('.av__row:not(.av__row--header) .av__cell[data-wrap="true"]').forEach(cell => {
          const textElement = cell.querySelector('.av__celltext'); // 查找包含文本的子元素
          // 检查父元素是否已有 aria-label 属性、是否是有效的 DOM 元素、文本是否被截断
          if (cell.getAttribute('aria-label') && textElement && !(textElement.scrollHeight > textElement.clientHeight)) {
            cell.removeAttribute('aria-label'); // 为无截断文本的单元格移除 aria-label 属性
          } else if (!cell.getAttribute('aria-label') && textElement && textElement.scrollHeight > textElement.clientHeight) {
            const text = textElement.textContent.trim();  // 提取文本
            cell.setAttribute('aria-label', text); // 为有截断文本单元格添加 aria-label 属性
          }
        });
        // 重置 animationFrameRequestId,以便下次调用 updateAriaLabels 时可以检查
        animationFrameRequestId = null;
      });
    }
    
    var timeoutId = null;
    // 创建一个新的 MutationObserver 实例,并提供一个回调函数
    const observer = new MutationObserver((mutations) => {
      mutations.forEach((mutation) => {
        if (mutation.type === 'attributes') {
          // 数据库渲染:检查被修改的节点是否是数据库 av 类型并且已经渲染完成
          if (mutation.target.classList.contains('av') && mutation.target.getAttribute('data-render') === 'true') {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function() {
              updateAriaLabels()
            }, 500); // 500 毫秒延时。用以避免短时间内重复执行
          // 调整列(宽):检查被修改的节点是否是数据库列头并且开启了换行;或者是否是切换页签
          } else if (mutation.target.classList.contains('av__cell--header') && mutation.target.getAttribute('data-wrap') === 'true' || mutation.target.classList.contains('item--focus')) {
            clearTimeout(timeoutId);
            timeoutId = setTimeout(function() {
              updateAriaLabels2()
            }, 500); // 500 毫秒延时。拖拽的过程中属性会高频变化,此时不继续运行
          }
        }
      });
    });
    // 配置MutationObserver以观察DOM树的变化
    const config = { attributes: true, childList: false, subtree: true };
    // 开始观察
    observer.observe(document.body, config);
    
    // 创建一个新的style元素
    var style = document.createElement('style');
    // 添加CSS代码
    style.textContent = `
    /* 限制数据库换行文本最大行数 CSS片段 */
    .av__row:not(.av__row--header) .av__cell[data-wrap="true"] .av__celltext {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3; /* 最多3行 */
      overflow: hidden;
    }
    .av__celltext--ref {
        border-bottom: 0px;
        text-decoration: underline; /* 下划线 */
        text-decoration-color: rgb(0 202 255 / 85%); /* 浅蓝色 */
        text-decoration-thickness: 2px;
    }
    `;
    // 将style元素添加到文档的head中
    document.head.appendChild(style);
    
    该回帖因已过时而被折叠
    1 操作
    JeffreyChen 在 2024-09-22 01:28:30 折叠了该回帖
JeffreyChen
思源是支持 Markdown 语法输入的块编辑器,而不是 Markdown 文件编辑器; 思源笔记同步教程:ld246.com/article/1692089679062

推荐标签 标签

  • 持续集成

    持续集成(Continuous Integration)是一种软件开发实践,即团队开发成员经常集成他们的工作,通过每个成员每天至少集成一次,也就意味着每天可能会发生多次集成。每次集成都通过自动化的构建(包括编译,发布,自动化测试)来验证,从而尽早地发现集成错误。

    15 引用 • 7 回帖
  • CSS

    CSS(Cascading Style Sheet)“层叠样式表”是用于控制网页样式并允许将样式信息与网页内容分离的一种标记性语言。

    194 引用 • 515 回帖
  • 单点登录

    单点登录(Single Sign On)是目前比较流行的企业业务整合的解决方案之一。SSO 的定义是在多个应用系统中,用户只需要登录一次就可以访问所有相互信任的应用系统。

    9 引用 • 25 回帖
  • Lute

    Lute 是一款结构化的 Markdown 引擎,支持 Go 和 JavaScript。

    25 引用 • 191 回帖 • 22 关注
  • Notion

    Notion - The all-in-one workspace for your notes, tasks, wikis, and databases.

    5 引用 • 26 回帖
  • 安全

    安全永远都不是一个小问题。

    200 引用 • 816 回帖 • 1 关注
  • HBase

    HBase 是一个分布式的、面向列的开源数据库,该技术来源于 Fay Chang 所撰写的 Google 论文 “Bigtable:一个结构化数据的分布式存储系统”。就像 Bigtable 利用了 Google 文件系统所提供的分布式数据存储一样,HBase 在 Hadoop 之上提供了类似于 Bigtable 的能力。

    17 引用 • 6 回帖 • 70 关注
  • 微服务

    微服务架构是一种架构模式,它提倡将单一应用划分成一组小的服务。服务之间互相协调,互相配合,为用户提供最终价值。每个服务运行在独立的进程中。服务于服务之间才用轻量级的通信机制互相沟通。每个服务都围绕着具体业务构建,能够被独立的部署。

    96 引用 • 155 回帖
  • 反馈

    Communication channel for makers and users.

    123 引用 • 910 回帖 • 228 关注
  • 导航

    各种网址链接、内容导航。

    38 引用 • 169 回帖
  • Shell

    Shell 脚本与 Windows/Dos 下的批处理相似,也就是用各类命令预先放入到一个文件中,方便一次性执行的一个程序文件,主要是方便管理员进行设置或者管理用的。但是它比 Windows 下的批处理更强大,比用其他编程程序编辑的程序效率更高,因为它使用了 Linux/Unix 下的命令。

    122 引用 • 73 回帖
  • RYMCU

    RYMCU 致力于打造一个即严谨又活泼、专业又不失有趣,为数百万人服务的开源嵌入式知识学习交流平台。

    4 引用 • 6 回帖 • 50 关注
  • Solidity

    Solidity 是一种智能合约高级语言,运行在 [以太坊] 虚拟机(EVM)之上。它的语法接近于 JavaScript,是一种面向对象的语言。

    3 引用 • 18 回帖 • 376 关注
  • OpenStack

    OpenStack 是一个云操作系统,通过数据中心可控制大型的计算、存储、网络等资源池。所有的管理通过前端界面管理员就可以完成,同样也可以通过 Web 接口让最终用户部署资源。

    10 引用
  • Log4j

    Log4j 是 Apache 开源的一款使用广泛的 Java 日志组件。

    20 引用 • 18 回帖 • 31 关注
  • Ngui

    Ngui 是一个 GUI 的排版显示引擎和跨平台的 GUI 应用程序开发框架,基于
    Node.js / OpenGL。目标是在此基础上开发 GUI 应用程序可拥有开发 WEB 应用般简单与速度同时兼顾 Native 应用程序的性能与体验。

    7 引用 • 9 回帖 • 378 关注
  • SQLite

    SQLite 是一个进程内的库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是全世界使用最为广泛的数据库引擎。

    5 引用 • 7 回帖 • 1 关注
  • 区块链

    区块链是分布式数据存储、点对点传输、共识机制、加密算法等计算机技术的新型应用模式。所谓共识机制是区块链系统中实现不同节点之间建立信任、获取权益的数学算法 。

    91 引用 • 751 回帖
  • Latke

    Latke 是一款以 JSON 为主的 Java Web 框架。

    70 引用 • 533 回帖 • 760 关注
  • SVN

    SVN 是 Subversion 的简称,是一个开放源代码的版本控制系统,相较于 RCS、CVS,它采用了分支管理系统,它的设计目标就是取代 CVS。

    29 引用 • 98 回帖 • 694 关注
  • uTools

    uTools 是一个极简、插件化、跨平台的现代桌面软件。通过自由选配丰富的插件,打造你得心应手的工具集合。

    5 引用 • 13 回帖 • 1 关注
  • GAE

    Google App Engine(GAE)是 Google 管理的数据中心中用于 WEB 应用程序的开发和托管的平台。2008 年 4 月 发布第一个测试版本。目前支持 Python、Java 和 Go 开发部署。全球已有数十万的开发者在其上开发了众多的应用。

    14 引用 • 42 回帖 • 732 关注
  • SSL

    SSL(Secure Sockets Layer 安全套接层),及其继任者传输层安全(Transport Layer Security,TLS)是为网络通信提供安全及数据完整性的一种安全协议。TLS 与 SSL 在传输层对网络连接进行加密。

    70 引用 • 193 回帖 • 446 关注
  • Sillot

    Insights(注意当前设置 master 为默认分支)

    汐洛彖夲肜矩阵(Sillot T☳Converbenk Matrix),致力于服务智慧新彖乄,具有彖乄驱动、极致优雅、开发者友好的特点。其中汐洛绞架(Sillot-Gibbet)基于自思源笔记(siyuan-note),前身是思源笔记汐洛版(更早是思源笔记汐洛分支),是智慧新录乄终端(多端融合,移动端优先)。

    主仓库地址:Hi-Windom/Sillot

    文档地址:sillot.db.sc.cn

    注意事项:

    1. ⚠️ 汐洛仍在早期开发阶段,尚不稳定
    2. ⚠️ 汐洛并非面向普通用户设计,使用前请了解风险
    3. ⚠️ 汐洛绞架基于思源笔记,开发者尽最大努力与思源笔记保持兼容,但无法实现 100% 兼容
    29 引用 • 25 回帖 • 72 关注
  • 博客

    记录并分享人生的经历。

    272 引用 • 2386 回帖
  • Flume

    Flume 是一套分布式的、可靠的,可用于有效地收集、聚合和搬运大量日志数据的服务架构。

    9 引用 • 6 回帖 • 625 关注
  • Scala

    Scala 是一门多范式的编程语言,集成面向对象编程和函数式编程的各种特性。

    13 引用 • 11 回帖 • 117 关注