Skip to content

Commit

Permalink
Merge pull request #111 from jeronimoek/add-custom-formats-presentation
Browse files Browse the repository at this point in the history
Add custom formats presentation
  • Loading branch information
jeronimoek authored Jul 21, 2024
2 parents 1352804 + 5d2717a commit 0616c56
Show file tree
Hide file tree
Showing 9 changed files with 285 additions and 41 deletions.
35 changes: 18 additions & 17 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

22 changes: 19 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@
"clean": "rimraf dist",
"pretest": "npm run test-compile",
"test": "node ./out/test/runTest.js",
"test-compile": "npm run clean-test && tsc -p tsconfig.json",
"test-compile": "npm run clean-test && tsc -p ./tsconfig.json",
"clean-test": "rimraf out",
"checks": "npm run lint && npm run test",
"pre-push": "bash scripts/no-push-main.sh && npm run checks",
Expand Down Expand Up @@ -77,10 +77,10 @@
"pre-push": "0.1.4",
"rimraf": "4.1.2",
"sinon": "15.0.1",
"typescript": "4.9.4"
"typescript": "5.5.3"
},
"dependencies": {
"color-translate": "^0.5.0"
"color-translate": "1.1.1"
},
"contributes": {
"commands": [
Expand Down Expand Up @@ -360,6 +360,22 @@
"yaml"
]
}
},
"color-picker-universal.customRegexes": {
"default": {},
"description": "Set custom regexes",
"type": "object",
"examples": [
{
"a98": [
"my-a98-alpha-format\\((\\d+(?:\\.\\d+)?) \\$ (\\d+(?:\\.\\d+)?) \\$ (\\d+(?:\\.\\d+)?)(?: \\$ (\\d+(?:\\.\\d+)?))?\\)",
"other-a98-format\\((\\d+(?:\\.\\d+)?) \\$ (\\d+(?:\\.\\d+)?) \\$ (\\d+(?:\\.\\d+)?)\\)"
],
"hsl": [
"the-hsl-format\\((\\d+(?:\\.\\d+)?) \\$ (\\d+(?:\\.\\d+)?) \\$ (\\d+(?:\\.\\d+)?)\\)"
]
}
]
}
}
}
Expand Down
67 changes: 60 additions & 7 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import * as vscode from "vscode";
import { colorFormatsTo } from "./shared/constants";
import { getMatches } from "./getMatches";
import { getCustomMatches, getMatches } from "./getMatches";
import {
findCustomFormat,
getFormatRegex,
getSetting,
isSettingEnabled,
isValidDocument,
Expand All @@ -10,7 +12,7 @@ import {
import { ColorFormatTo, CommandType } from "./utils/enums";
import { translateColors } from "./commands/translateColors";
import { ColorTranslatorExtended } from "./colorTranslatorExtended";

import { replaceRange } from "./utils/utils";
class Picker implements vscode.Disposable {
constructor() {
this.register();
Expand Down Expand Up @@ -74,15 +76,26 @@ class Picker implements vscode.Disposable {

vscode.commands.registerCommand(command, commandHandler);
vscode.languages.registerColorProvider("*", {
provideDocumentColors(document: vscode.TextDocument) {
async provideDocumentColors(document: vscode.TextDocument) {
if (!isValidDocument(document)) return;

const text = document.getText();
return getMatches(text);

return [...(await getMatches(text)), ...getCustomMatches(text)];
},
provideColorPresentations(colorRaw, { range, document }) {
if (!isValidDocument(document)) return;

const text = document.getText(range);

// Check if custom format
let isCustomFormat = false;
try {
new ColorTranslatorExtended(text);
} catch (_e) {
isCustomFormat = true;
}

const formatsToSetting = getSetting<string[]>("formatsTo");
const formatsTo = formatsToSetting?.length ? formatsToSetting : ["*"];

Expand Down Expand Up @@ -120,10 +133,50 @@ class Picker implements vscode.Disposable {
);
}

return representations.map(
(representation) =>
new vscode.ColorPresentation(representation.toString())
const finalRepresentations: vscode.ColorPresentation[] = [];

// Add custom format representation
// TODO: ugly asf
if (isCustomFormat) {
const customFormat = findCustomFormat(text);
if (customFormat) {
const { format, regexMatch } = customFormat;
const formatColor = color[format].toString();
const formatRegex = getFormatRegex(format);
const globalFormatRegex = new RegExp(formatRegex.source, "gi");
const [formatMatch] = [...formatColor.matchAll(globalFormatRegex)];
let updatedText = text;
const indices = regexMatch.indices?.slice(1).filter((v) => v) || [];
indices.reverse();
const formatValues = formatMatch
.slice(2, indices.length + 3)
.filter((v) => v);

indices.forEach(([start, end], i) => {
if (i === indices.length) return;
const diff = indices.length - formatValues.length;
let value = formatValues[formatValues.length - i - 1 + diff];
if (i === 0 && diff === 1) {
value = "1";
}
if (value) {
updatedText = replaceRange(updatedText, start, end, value);
}
});

finalRepresentations.push(
new vscode.ColorPresentation(updatedText)
);
}
}

finalRepresentations.push(
...representations.map(
(representation) => new vscode.ColorPresentation(representation)
)
);

return finalRepresentations;
},
});
}
Expand Down
79 changes: 79 additions & 0 deletions src/getMatches.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import {
customMatchColors,
ensureActiveEditorIsSet,
getSetting,
matchColors,
parseColorString,
} from "./utils/helpers";
import * as vscode from "vscode";
import { Document } from "./models/Document";
import { ColorFormatFrom, ColorFormatTo } from "./utils/enums";
import { Color } from "color-translate";

function findVars(
symbols: vscode.DocumentSymbol[] = []
Expand Down Expand Up @@ -103,3 +106,79 @@ export async function getMatches(
}
return result;
}

function parseAlpha(alpha: string) {
return alpha === "" ? "1" : alpha;
}

export function getCustomMatches(text: string) {
const result: vscode.ColorInformation[] = [];

const matches = customMatchColors(text);

for (const format in matches) {
const matchesValues = matches[format as ColorFormatTo];
for (const matchValues of matchesValues) {
const { index } = matchValues;
const [match = "", v1 = "", v2 = "", v3 = "", v4 = "", v5 = ""] =
matchValues;
let color: string | Color;

switch (format as ColorFormatFrom) {
case ColorFormatFrom.CMYK:
color = { c: v1, m: v2, y: v3, k: v4, alpha: parseAlpha(v5) };
break;
case ColorFormatFrom.HEX:
color = `#${v1}${v2}${v3}${v4}`;
break;
case ColorFormatFrom.HEX_0X:
color = `0x${v1}${v2}${v3}${v4}`;
break;
case ColorFormatFrom.HSL:
case ColorFormatFrom.HSLA:
color = { h: v1, s: v2, l: v3, alpha: parseAlpha(v4) };
break;
case ColorFormatFrom.HWB:
color = { h: v1, w: v2, b: v3, alpha: parseAlpha(v4) };
break;
case ColorFormatFrom.LAB:
color = { l: v1, a: v2, b: v3, alpha: parseAlpha(v4) };
break;
case ColorFormatFrom.LCH:
color = { l: v1, c: v2, h: v3, alpha: parseAlpha(v4) };
break;
case ColorFormatFrom.NAMED:
color = v1;
break;
case ColorFormatFrom.OKLAB:
color = { l: v1, a: v2, b: v3, ok: true, alpha: parseAlpha(v4) };
break;
case ColorFormatFrom.OKLCH:
color = { l: v1, c: v2, h: v3, ok: true, alpha: parseAlpha(v4) };
break;
case ColorFormatFrom.A98:
color = { r: v1, g: v2, b: v3, a98: true, alpha: parseAlpha(v4) };
break;
case ColorFormatFrom.RGB:
case ColorFormatFrom.RGBA:
default:
color = { r: v1, g: v2, b: v3, alpha: parseAlpha(v4) };
break;
}

const vscodeColor = parseColorString(color);

const currentTextDocument = new Document(text);

const range = new vscode.Range(
currentTextDocument.positionAt(index),
currentTextDocument.positionAt(index + match.length)
);

if (vscodeColor) {
result.push(new vscode.ColorInformation(range, vscodeColor));
}
}
}
return result;
}
4 changes: 4 additions & 0 deletions src/shared/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ export const NamedColors = {
yellowgreen: "#9ACD32",
};

export const namedColorsRegex = new RegExp(
`${Object.keys(NamedColors).join("|")}`
);

export const namedColorsLAB = {
aliceblue: [97.12, -1.77, -4.36],
antiquewhite: [93.86, 2.86, 11.64],
Expand Down
2 changes: 2 additions & 0 deletions src/utils/enums.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export enum ColorFormatTo {
LCH = "lch",
OKLAB = "oklab",
OKLCH = "oklch",
A98 = "a98",
}

export enum ColorFormatFrom {
Expand All @@ -31,6 +32,7 @@ export enum ColorFormatFrom {
LCH = "lch",
OKLAB = "oklab",
OKLCH = "oklch",
A98 = "a98",
}

export enum CommandType {
Expand Down
Loading

0 comments on commit 0616c56

Please sign in to comment.