[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);
})();
  • 思源笔记

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

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

    21202 引用 • 83546 回帖
  • 代码片段

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

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

    13 引用 • 63 回帖 • 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

推荐标签 标签

  • 工具

    子曰:“工欲善其事,必先利其器。”

    285 引用 • 728 回帖
  • TensorFlow

    TensorFlow 是一个采用数据流图(data flow graphs),用于数值计算的开源软件库。节点(Nodes)在图中表示数学操作,图中的线(edges)则表示在节点间相互联系的多维数据数组,即张量(tensor)。

    20 引用 • 19 回帖
  • IBM

    IBM(国际商业机器公司)或万国商业机器公司,简称 IBM(International Business Machines Corporation),总公司在纽约州阿蒙克市。1911 年托马斯·沃森创立于美国,是全球最大的信息技术和业务解决方案公司,拥有全球雇员 30 多万人,业务遍及 160 多个国家和地区。

    17 引用 • 53 回帖 • 130 关注
  • 区块链

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

    91 引用 • 751 回帖 • 2 关注
  • FlowUs

    FlowUs.息流 个人及团队的新一代生产力工具。

    让复杂的信息管理更轻松、自由、充满创意。

    1 引用
  • 大疆创新

    深圳市大疆创新科技有限公司(DJI-Innovations,简称 DJI),成立于 2006 年,是全球领先的无人飞行器控制系统及无人机解决方案的研发和生产商,客户遍布全球 100 多个国家。通过持续的创新,大疆致力于为无人机工业、行业用户以及专业航拍应用提供性能最强、体验最佳的革命性智能飞控产品和解决方案。

    2 引用 • 14 回帖 • 3 关注
  • 黑曜石

    黑曜石是一款强大的知识库工具,支持本地 Markdown 文件编辑,支持双向链接和关系图。

    A second brain, for you, forever.

    11 引用 • 90 回帖 • 1 关注
  • GitBook

    GitBook 使您的团队可以轻松编写和维护高质量的文档。 分享知识,提高团队的工作效率,让用户满意。

    3 引用 • 8 回帖 • 1 关注
  • ZooKeeper

    ZooKeeper 是一个分布式的,开放源码的分布式应用程序协调服务,是 Google 的 Chubby 一个开源的实现,是 Hadoop 和 HBase 的重要组件。它是一个为分布式应用提供一致性服务的软件,提供的功能包括:配置维护、域名服务、分布式同步、组服务等。

    59 引用 • 29 回帖 • 9 关注
  • Typecho

    Typecho 是一款博客程序,它在 GPLv2 许可证下发行,基于 PHP 构建,可以运行在各种平台上,支持多种数据库(MySQL、PostgreSQL、SQLite)。

    12 引用 • 65 回帖 • 454 关注
  • PHP

    PHP(Hypertext Preprocessor)是一种开源脚本语言。语法吸收了 C 语言、 Java 和 Perl 的特点,主要适用于 Web 开发领域,据说是世界上最好的编程语言。

    179 引用 • 407 回帖 • 499 关注
  • Git

    Git 是 Linux Torvalds 为了帮助管理 Linux 内核开发而开发的一个开放源码的版本控制软件。

    207 引用 • 358 回帖
  • RYMCU

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

    4 引用 • 6 回帖 • 52 关注
  • 运维

    互联网运维工作,以服务为中心,以稳定、安全、高效为三个基本点,确保公司的互联网业务能够 7×24 小时为用户提供高质量的服务。

    148 引用 • 257 回帖
  • OnlyOffice
    4 引用 • 7 关注
  • MongoDB

    MongoDB(来自于英文单词“Humongous”,中文含义为“庞大”)是一个基于分布式文件存储的数据库,由 C++ 语言编写。旨在为应用提供可扩展的高性能数据存储解决方案。MongoDB 是一个介于关系数据库和非关系数据库之间的产品,是非关系数据库当中功能最丰富,最像关系数据库的。它支持的数据结构非常松散,是类似 JSON 的 BSON 格式,因此可以存储比较复杂的数据类型。

    90 引用 • 59 回帖 • 5 关注
  • IPFS

    IPFS(InterPlanetary File System,星际文件系统)是永久的、去中心化保存和共享文件的方法,这是一种内容可寻址、版本化、点对点超媒体的分布式协议。请浏览 IPFS 入门笔记了解更多细节。

    21 引用 • 245 回帖 • 246 关注
  • uTools

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

    5 引用 • 13 回帖 • 2 关注
  • 思源笔记

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

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

    21201 引用 • 83545 回帖
  • Vditor

    Vditor 是一款浏览器端的 Markdown 编辑器,支持所见即所得、即时渲染(类似 Typora)和分屏预览模式。它使用 TypeScript 实现,支持原生 JavaScript、Vue、React 和 Angular。

    344 引用 • 1778 回帖 • 1 关注
  • WordPress

    WordPress 是一个使用 PHP 语言开发的博客平台,用户可以在支持 PHP 和 MySQL 数据库的服务器上架设自己的博客。也可以把 WordPress 当作一个内容管理系统(CMS)来使用。WordPress 是一个免费的开源项目,在 GNU 通用公共许可证(GPLv2)下授权发布。

    66 引用 • 114 回帖 • 257 关注
  • HHKB

    HHKB 是富士通的 Happy Hacking 系列电容键盘。电容键盘即无接点静电电容式键盘(Capacitive Keyboard)。

    5 引用 • 74 回帖 • 454 关注
  • 一些有用的避坑指南。

    69 引用 • 93 回帖
  • Eclipse

    Eclipse 是一个开放源代码的、基于 Java 的可扩展开发平台。就其本身而言,它只是一个框架和一组服务,用于通过插件组件构建开发环境。

    75 引用 • 258 回帖 • 634 关注
  • 以太坊

    以太坊(Ethereum)并不是一个机构,而是一款能够在区块链上实现智能合约、开源的底层系统。以太坊是一个平台和一种编程语言 Solidity,使开发人员能够建立和发布下一代去中心化应用。 以太坊可以用来编程、分散、担保和交易任何事物:投票、域名、金融交易所、众筹、公司管理、合同和知识产权等等。

    34 引用 • 367 回帖 • 6 关注
  • V2EX

    V2EX 是创意工作者们的社区。这里目前汇聚了超过 400,000 名主要来自互联网行业、游戏行业和媒体行业的创意工作者。V2EX 希望能够成为创意工作者们的生活和事业的一部分。

    17 引用 • 236 回帖 • 343 关注
  • Vim

    Vim 是类 UNIX 系统文本编辑器 Vi 的加强版本,加入了更多特性来帮助编辑源代码。Vim 的部分增强功能包括文件比较(vimdiff)、语法高亮、全面的帮助系统、本地脚本(Vimscript)和便于选择的可视化模式。

    29 引用 • 66 回帖