Monaco 使用 ColorProvider

Manco 中可以使用调色板对色值进行修改,首先看一下调色版效果。

在这里插入图片描述
调色板是 Monaco-Editor 中一个特别的组件,通过两个方法实现呼出调色板,provideColorPresentations 显示调色窗口,provideDocumentColors 监听页面的变更,如果是色值(根据正则去判断)就在字符串前添加颜色块。
在这里插入图片描述

实现代码如下


export function colorProvider(editor, monaco){
    return monaco.languages.registerColorProvider('javascript',{
        provideDocumentColors: function (model, token) {
          const colors = [];
          const lines = model.getLinesContent();

          for (let lineNumber = 1; lineNumber <= lines.length; lineNumber++) {
            const lineContent = lines[lineNumber - 1];
            const regex = /(#[0-9A-Fa-f]{6}|#[0-9A-Fa-f]{3})/g;
            let match;
            while ((match = regex.exec(lineContent)) !== null) {
              const startIndex = match.index;
              const endIndex = startIndex + match[0].length;
              colors.push({
                range: new monaco.Range(lineNumber, startIndex + 1, lineNumber, endIndex + 1),
                color: {
                  red: parseInt(match[1].substr(1, 2), 16) / 255,
                  green: parseInt(match[1].substr(3, 2), 16) / 255,
                  blue: parseInt(match[1].substr(5, 2), 16) / 255,
                  alpha: 1
                }
              });
            }
          }
          return colors;
        },
        provideColorPresentations: function (model, colorInfo, token) {
          const { red, green, blue } = colorInfo.color;
          const hex = `#${Math.round(red * 255).toString(16).padStart(2, '0')}${Math.round(green * 255).toString(16).padStart(2, '0')}${Math.round(blue * 255).toString(16).padStart(2, '0')}`;
          return [{ label: hex }];
        }
      })
}

相关推荐

  1. 使用 Monaco Editor 开发 SQL 编辑器

    2024-07-12 21:00:03       28 阅读
  2. vue3.0-monaco组件封装

    2024-07-12 21:00:03       35 阅读
  3. monaco-editor设置语言、值等

    2024-07-12 21:00:03       31 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-12 21:00:03       66 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-12 21:00:03       70 阅读
  3. 在Django里面运行非项目文件

    2024-07-12 21:00:03       57 阅读
  4. Python语言-面向对象

    2024-07-12 21:00:03       68 阅读

热门阅读

  1. 力扣 225题 用队列实现栈 记录

    2024-07-12 21:00:03       21 阅读
  2. python爬虫js逆向入门

    2024-07-12 21:00:03       26 阅读
  3. vue3+ts 引入 json-editor-vue3 报错

    2024-07-12 21:00:03       19 阅读
  4. jar服务注册为windows的服务

    2024-07-12 21:00:03       14 阅读
  5. C++:创建线程

    2024-07-12 21:00:03       27 阅读
  6. python 知识点累积

    2024-07-12 21:00:03       22 阅读
  7. C语言——循环结构:while、do...while、for

    2024-07-12 21:00:03       22 阅读
  8. 简单有效防止CDN被盗刷流量

    2024-07-12 21:00:03       18 阅读
  9. Linux 命令个人学习笔记

    2024-07-12 21:00:03       19 阅读
  10. SpringBoot实现Read Through模式

    2024-07-12 21:00:03       20 阅读