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