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 }];}})
}