@bhsd/codemirror-css-color-picker 6.3.1 → 7.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,602 +1,405 @@
1
- import { EditorView, ViewPlugin, Decoration, WidgetType } from '@codemirror/view';
2
- import { NodeProp } from '@lezer/common';
3
- import { syntaxTree, language } from '@codemirror/language';
1
+ import { EditorView, WidgetType, ViewPlugin, Decoration } from "@codemirror/view";
2
+ import { syntaxTree } from "@codemirror/language";
3
+ import namedColors2 from "color-name";
4
+ import { intToHex } from "@bhsd/common";
4
5
 
5
- const namedColors = /*@__PURE__*/new Map([
6
- ['aliceblue', '#f0f8ff'],
7
- ['antiquewhite', '#faebd7'],
8
- ['aqua', '#00ffff'],
9
- ['aquamarine', '#7fffd4'],
10
- ['azure', '#f0ffff'],
11
- ['beige', '#f5f5dc'],
12
- ['bisque', '#ffe4c4'],
13
- ['black', '#000000'],
14
- ['blanchedalmond', '#ffebcd'],
15
- ['blue', '#0000ff'],
16
- ['blueviolet', '#8a2be2'],
17
- ['brown', '#a52a2a'],
18
- ['burlywood', '#deb887'],
19
- ['cadetblue', '#5f9ea0'],
20
- ['chartreuse', '#7fff00'],
21
- ['chocolate', '#d2691e'],
22
- ['coral', '#ff7f50'],
23
- ['cornflowerblue', '#6495ed'],
24
- ['cornsilk', '#fff8dc'],
25
- ['crimson', '#dc143c'],
26
- ['cyan', '#00ffff'],
27
- ['darkblue', '#00008b'],
28
- ['darkcyan', '#008b8b'],
29
- ['darkgoldenrod', '#b8860b'],
30
- ['darkgray', '#a9a9a9'],
31
- ['darkgreen', '#006400'],
32
- ['darkgrey', '#a9a9a9'],
33
- ['darkkhaki', '#bdb76b'],
34
- ['darkmagenta', '#8b008b'],
35
- ['darkolivegreen', '#556b2f'],
36
- ['darkorange', '#ff8c00'],
37
- ['darkorchid', '#9932cc'],
38
- ['darkred', '#8b0000'],
39
- ['darksalmon', '#e9967a'],
40
- ['darkseagreen', '#8fbc8f'],
41
- ['darkslateblue', '#483d8b'],
42
- ['darkslategray', '#2f4f4f'],
43
- ['darkslategrey', '#2f4f4f'],
44
- ['darkturquoise', '#00ced1'],
45
- ['darkviolet', '#9400d3'],
46
- ['deeppink', '#ff1493'],
47
- ['deepskyblue', '#00bfff'],
48
- ['dimgray', '#696969'],
49
- ['dimgrey', '#696969'],
50
- ['dodgerblue', '#1e90ff'],
51
- ['firebrick', '#b22222'],
52
- ['floralwhite', '#fffaf0'],
53
- ['forestgreen', '#228b22'],
54
- ['fuchsia', '#ff00ff'],
55
- ['gainsboro', '#dcdcdc'],
56
- ['ghostwhite', '#f8f8ff'],
57
- ['goldenrod', '#daa520'],
58
- ['gold', '#ffd700'],
59
- ['gray', '#808080'],
60
- ['green', '#008000'],
61
- ['greenyellow', '#adff2f'],
62
- ['grey', '#808080'],
63
- ['honeydew', '#f0fff0'],
64
- ['hotpink', '#ff69b4'],
65
- ['indianred', '#cd5c5c'],
66
- ['indigo', '#4b0082'],
67
- ['ivory', '#fffff0'],
68
- ['khaki', '#f0e68c'],
69
- ['lavenderblush', '#fff0f5'],
70
- ['lavender', '#e6e6fa'],
71
- ['lawngreen', '#7cfc00'],
72
- ['lemonchiffon', '#fffacd'],
73
- ['lightblue', '#add8e6'],
74
- ['lightcoral', '#f08080'],
75
- ['lightcyan', '#e0ffff'],
76
- ['lightgoldenrodyellow', '#fafad2'],
77
- ['lightgray', '#d3d3d3'],
78
- ['lightgreen', '#90ee90'],
79
- ['lightgrey', '#d3d3d3'],
80
- ['lightpink', '#ffb6c1'],
81
- ['lightsalmon', '#ffa07a'],
82
- ['lightseagreen', '#20b2aa'],
83
- ['lightskyblue', '#87cefa'],
84
- ['lightslategray', '#778899'],
85
- ['lightslategrey', '#778899'],
86
- ['lightsteelblue', '#b0c4de'],
87
- ['lightyellow', '#ffffe0'],
88
- ['lime', '#00ff00'],
89
- ['limegreen', '#32cd32'],
90
- ['linen', '#faf0e6'],
91
- ['magenta', '#ff00ff'],
92
- ['maroon', '#800000'],
93
- ['mediumaquamarine', '#66cdaa'],
94
- ['mediumblue', '#0000cd'],
95
- ['mediumorchid', '#ba55d3'],
96
- ['mediumpurple', '#9370db'],
97
- ['mediumseagreen', '#3cb371'],
98
- ['mediumslateblue', '#7b68ee'],
99
- ['mediumspringgreen', '#00fa9a'],
100
- ['mediumturquoise', '#48d1cc'],
101
- ['mediumvioletred', '#c71585'],
102
- ['midnightblue', '#191970'],
103
- ['mintcream', '#f5fffa'],
104
- ['mistyrose', '#ffe4e1'],
105
- ['moccasin', '#ffe4b5'],
106
- ['navajowhite', '#ffdead'],
107
- ['navy', '#000080'],
108
- ['oldlace', '#fdf5e6'],
109
- ['olive', '#808000'],
110
- ['olivedrab', '#6b8e23'],
111
- ['orange', '#ffa500'],
112
- ['orangered', '#ff4500'],
113
- ['orchid', '#da70d6'],
114
- ['palegoldenrod', '#eee8aa'],
115
- ['palegreen', '#98fb98'],
116
- ['paleturquoise', '#afeeee'],
117
- ['palevioletred', '#db7093'],
118
- ['papayawhip', '#ffefd5'],
119
- ['peachpuff', '#ffdab9'],
120
- ['peru', '#cd853f'],
121
- ['pink', '#ffc0cb'],
122
- ['plum', '#dda0dd'],
123
- ['powderblue', '#b0e0e6'],
124
- ['purple', '#800080'],
125
- ['rebeccapurple', '#663399'],
126
- ['red', '#ff0000'],
127
- ['rosybrown', '#bc8f8f'],
128
- ['royalblue', '#4169e1'],
129
- ['saddlebrown', '#8b4513'],
130
- ['salmon', '#fa8072'],
131
- ['sandybrown', '#f4a460'],
132
- ['seagreen', '#2e8b57'],
133
- ['seashell', '#fff5ee'],
134
- ['sienna', '#a0522d'],
135
- ['silver', '#c0c0c0'],
136
- ['skyblue', '#87ceeb'],
137
- ['slateblue', '#6a5acd'],
138
- ['slategray', '#708090'],
139
- ['slategrey', '#708090'],
140
- ['snow', '#fffafa'],
141
- ['springgreen', '#00ff7f'],
142
- ['steelblue', '#4682b4'],
143
- ['tan', '#d2b48c'],
144
- ['teal', '#008080'],
145
- ['thistle', '#d8bfd8'],
146
- ['tomato', '#ff6347'],
147
- ['turquoise', '#40e0d0'],
148
- ['violet', '#ee82ee'],
149
- ['wheat', '#f5deb3'],
150
- ['white', '#ffffff'],
151
- ['whitesmoke', '#f5f5f5'],
152
- ['yellow', '#ffff00'],
153
- ['yellowgreen', '#9acd32'],
154
- ]);
6
+ import { NodeProp } from "@lezer/common";
155
7
 
156
- var __rest = (undefined && undefined.__rest) || function (s, e) {
157
- var t = {};
158
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
159
- t[p] = s[p];
160
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
161
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
162
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
163
- t[p[i]] = s[p[i]];
164
- }
165
- return t;
8
+ var names = {};
9
+ var color_parse_default = parse;
10
+ var baseHues = {
11
+ red: 0,
12
+ orange: 60,
13
+ yellow: 120,
14
+ green: 180,
15
+ blue: 240,
16
+ purple: 300
166
17
  };
167
- const pickerState = /*@__PURE__*/new WeakMap();
168
- var ColorType = /*@__PURE__*/(function (ColorType) {
169
- ColorType["rgb"] = "RGB";
170
- ColorType["hex"] = "HEX";
171
- ColorType["named"] = "NAMED";
172
- ColorType["hsl"] = "HSL";
173
- return ColorType})(ColorType || (ColorType = {}));
174
- const rgbCallExpRegex = /rgba?\(\s*(\d{1,3}%?)\s*[,\s]\s*(\d{1,3}%?)\s*[,\s]\s*(\d{1,3}%?)\s*([,/]\s*0?\.?\d+%?)?\s*\)/;
175
- const hslCallExpRegex = /hsla?\(\s*(\d{1,3})(?:deg)?\s*[,\s]\s*(\d{1,3})%?\s*[,\s]\s*(\d{1,3})%?\s*([,/]\s*0?\.?\d+%?)?\s*\)/;
176
- const hexRegex = /(^|\b)(#[0-9a-f]{3,9})(\b|$)/i;
177
- function discoverColorsInCSS(syntaxTree, from, to, typeName, doc, language) {
178
- var _a;
179
- switch (typeName) {
180
- case 'AttributeValue': {
181
- const innerTree = syntaxTree.resolveInner(from, 0).tree;
182
- if (!innerTree) {
183
- return null;
184
- }
185
- const overlayTree = (_a = innerTree.prop(NodeProp.mounted)) === null || _a === void 0 ? void 0 : _a.tree;
186
- if ((overlayTree === null || overlayTree === void 0 ? void 0 : overlayTree.type.name) !== 'Styles') {
187
- return null;
188
- }
189
- const ret = [];
190
- overlayTree.iterate({
191
- from: 0,
192
- to: overlayTree.length,
193
- enter: ({ type, from: overlayFrom, to: overlayTo }) => {
194
- const maybeWidgetOptions = discoverColorsInCSS(syntaxTree,
195
- // We add one because the tree doesn't include the
196
- // quotation mark from the style tag
197
- from + 1 + overlayFrom, from + 1 + overlayTo, type.name, doc);
198
- if (maybeWidgetOptions) {
199
- if (Array.isArray(maybeWidgetOptions)) {
200
- throw new Error('Unexpected nested overlays');
201
- }
202
- ret.push(maybeWidgetOptions);
203
- }
204
- },
205
- });
206
- return ret;
207
- }
208
- case 'CallExpression': {
209
- const callExp = doc.sliceString(from, to);
210
- const result = parseCallExpression(callExp);
211
- if (!result) {
212
- return null;
213
- }
214
- return Object.assign(Object.assign({}, result), { from,
215
- to });
216
- }
217
- case 'ColorLiteral': {
218
- const result = parseColorLiteral(doc.sliceString(from, to));
219
- if (!result) {
220
- return null;
221
- }
222
- return Object.assign(Object.assign({}, result), { from,
223
- to });
224
- }
225
- case 'ValueName': {
226
- const colorName = doc.sliceString(from, to);
227
- const result = parseNamedColor(colorName);
228
- if (!result) {
229
- return null;
230
- }
231
- return Object.assign(Object.assign({}, result), { from,
232
- to });
233
- }
234
- default:
235
- return null;
18
+ function parse(cstr) {
19
+ var _a, _b;
20
+ var m, parts = [], alpha = 1, space;
21
+ if (typeof cstr === "number") {
22
+ return { space: "rgb", values: [cstr >>> 16, (cstr & 65280) >>> 8, cstr & 255], alpha: 1 };
23
+ }
24
+ if (typeof cstr === "number") return { space: "rgb", values: [cstr >>> 16, (cstr & 65280) >>> 8, cstr & 255], alpha: 1 };
25
+ cstr = String(cstr).toLowerCase();
26
+ if (names[cstr]) {
27
+ parts = names[cstr].slice();
28
+ space = "rgb";
29
+ } else if (cstr === "transparent") {
30
+ alpha = 0;
31
+ space = "rgb";
32
+ parts = [0, 0, 0];
33
+ } else if (cstr[0] === "#") {
34
+ var base = cstr.slice(1);
35
+ var size = base.length;
36
+ var isShort = size <= 4;
37
+ alpha = 1;
38
+ if (isShort) {
39
+ parts = [
40
+ parseInt(base[0] + base[0], 16),
41
+ parseInt(base[1] + base[1], 16),
42
+ parseInt(base[2] + base[2], 16)
43
+ ];
44
+ if (size === 4) {
45
+ alpha = parseInt(base[3] + base[3], 16) / 255;
46
+ }
47
+ } else {
48
+ parts = [
49
+ parseInt(base[0] + base[1], 16),
50
+ parseInt(base[2] + base[3], 16),
51
+ parseInt(base[4] + base[5], 16)
52
+ ];
53
+ if (size === 8) {
54
+ alpha = parseInt(base[6] + base[7], 16) / 255;
55
+ }
236
56
  }
57
+ if (!parts[0]) parts[0] = 0;
58
+ if (!parts[1]) parts[1] = 0;
59
+ if (!parts[2]) parts[2] = 0;
60
+ space = "rgb";
61
+ } else if (m = /^((?:rgba?|hs[lvb]a?|hwba?|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms|oklch|oklab|color))\s*\(([^\)]*)\)/.exec(cstr)) {
62
+ var name = m[1];
63
+ space = name.replace(/a$/, "");
64
+ var dims = space === "cmyk" ? 4 : space === "gray" ? 1 : 3;
65
+ parts = m[2].trim().split(/\s*[,\/]\s*|\s+/);
66
+ if (space === "color") space = parts.shift();
67
+ parts = parts.map(function(x, i) {
68
+ if (x[x.length - 1] === "%") {
69
+ x = parseFloat(x) / 100;
70
+ if (i === 3) return x;
71
+ if (space === "rgb") return x * 255;
72
+ if (space[0] === "h") return x * 100;
73
+ if (space[0] === "l" && !i) return x * 100;
74
+ if (space === "lab") return x * 125;
75
+ if (space === "lch") return i < 2 ? x * 150 : x * 360;
76
+ if (space[0] === "o" && !i) return x;
77
+ if (space === "oklab") return x * 0.4;
78
+ if (space === "oklch") return i < 2 ? x * 0.4 : x * 360;
79
+ return x;
80
+ }
81
+ if (space[i] === "h" || i === 2 && space[space.length - 1] === "h") {
82
+ if (baseHues[x] !== void 0) return baseHues[x];
83
+ if (x.endsWith("deg")) return parseFloat(x);
84
+ if (x.endsWith("turn")) return parseFloat(x) * 360;
85
+ if (x.endsWith("grad")) return parseFloat(x) * 360 / 400;
86
+ if (x.endsWith("rad")) return parseFloat(x) * 180 / Math.PI;
87
+ }
88
+ if (x === "none") return 0;
89
+ return parseFloat(x);
90
+ });
91
+ alpha = parts.length > dims ? parts.pop() : 1;
92
+ } else if (/[0-9](?:\s|\/|,)/.test(cstr)) {
93
+ parts = cstr.match(/([0-9]+)/g).map(function(value) {
94
+ return parseFloat(value);
95
+ });
96
+ space = ((_b = (_a = cstr.match(/([a-z])/ig)) == null ? void 0 : _a.join("")) == null ? void 0 : _b.toLowerCase()) || "rgb";
97
+ }
98
+ return {
99
+ space,
100
+ values: parts,
101
+ alpha
102
+ };
237
103
  }
238
- function parseCallExpression(callExp) {
239
- const fn = callExp.slice(0, 3);
240
- switch (fn) {
241
- case 'rgb': {
242
- const match = rgbCallExpRegex.exec(callExp);
243
- if (!match) {
244
- return null;
245
- }
246
- const [_, r, g, b, a] = match;
247
- const color = rgbToHex(r, g, b);
248
- return {
249
- colorType: ColorType.rgb,
250
- color,
251
- alpha: (a === null || a === void 0 ? void 0 : a.replace(/^\//, ',')) || '',
252
- };
253
- }
254
- case 'hsl': {
255
- const match = hslCallExpRegex.exec(callExp);
256
- if (!match) {
257
- return null;
258
- }
259
- const [_, h, s, l, a] = match;
260
- const color = hslToHex(h, s, l);
261
- return {
262
- colorType: ColorType.hsl,
263
- color,
264
- alpha: (a === null || a === void 0 ? void 0 : a.replace(/^\//, ',')) || '',
265
- };
266
- }
267
- default:
268
- return null;
269
- }
270
- }
271
- function parseColorLiteral(colorLiteral) {
272
- const match = hexRegex.exec(colorLiteral);
273
- if (!match) {
274
- return null;
275
- }
276
- const [color, alpha] = toFullHex(colorLiteral);
277
- return {
278
- colorType: ColorType.hex,
279
- color,
280
- alpha,
281
- };
282
- }
283
- function parseNamedColor(colorName) {
284
- const color = namedColors.get(colorName);
285
- if (!color) {
286
- return null;
287
- }
288
- return {
289
- colorType: ColorType.named,
290
- color,
291
- alpha: '',
292
- };
104
+
105
+ import rgb from "color-space/rgb.js";
106
+ import hsl from "color-space/hsl.js";
107
+ function rgba(color) {
108
+ if (Array.isArray(color) && color.raw) color = String.raw(...arguments);
109
+ if (color instanceof Number) color = +color;
110
+ var values, i, l;
111
+ var parsed = color_parse_default(color);
112
+ if (!parsed.space) return [];
113
+ const min = parsed.space[0] === "h" ? hsl.min : rgb.min;
114
+ const max = parsed.space[0] === "h" ? hsl.max : rgb.max;
115
+ values = Array(3);
116
+ values[0] = Math.min(Math.max(parsed.values[0], min[0]), max[0]);
117
+ values[1] = Math.min(Math.max(parsed.values[1], min[1]), max[1]);
118
+ values[2] = Math.min(Math.max(parsed.values[2], min[2]), max[2]);
119
+ if (parsed.space[0] === "h") {
120
+ values = hsl.rgb(values);
121
+ }
122
+ values.push(Math.min(Math.max(parsed.alpha, 0), 1));
123
+ return values;
293
124
  }
294
- function colorPickersDecorations(view, discoverColors) {
295
- const widgets = [];
296
- const st = syntaxTree(view.state);
297
- for (const range of view.visibleRanges) {
298
- st.iterate({
299
- from: range.from,
300
- to: range.to,
301
- enter: ({ type, from, to }) => {
302
- var _a;
303
- const maybeWidgetOptions = discoverColors(st, from, to, type.name, view.state.doc, (_a = view.state.facet(language)) === null || _a === void 0 ? void 0 : _a.name);
304
- if (!maybeWidgetOptions) {
305
- return;
306
- }
307
- if (!Array.isArray(maybeWidgetOptions)) {
308
- widgets.push(Decoration.widget({
309
- widget: new ColorPickerWidget(maybeWidgetOptions),
310
- side: 1,
311
- }).range(maybeWidgetOptions.from));
312
- return;
313
- }
314
- for (const wo of maybeWidgetOptions) {
315
- widgets.push(Decoration.widget({
316
- widget: new ColorPickerWidget(wo),
317
- side: 1,
318
- }).range(wo.from));
319
- }
125
+
126
+ import namedColors from "color-name";
127
+ var rgbCallExpRegex = /^rgba?\(\s*\d+%?(?:\s|\s*,)\s*\d+%?(?:\s|\s*,)\s*\d+%?\s*(?:[,/]\s*0?\.?\d+%?\s*)?\)$/iu;
128
+ var hslCallExpRegex = /^hsla?\(\s*\d+(?:deg|g?rad|turn)?(?:\s|\s*,)\s*\d+%?(?:\s|\s*,)\s*\d+%?\s*(?:[,/]\s*0?\.?\d+%?\s*)?\)$/iu;
129
+ var hexRegex = /^#(?:[\da-f]{3,4}|(?:[\da-f]{2}){3,4})$/iu;
130
+ var discoverColorsInCSS = (tree, { from, to, name: typeName }, doc) => {
131
+ var _a, _b;
132
+ let parse2;
133
+ switch (typeName) {
134
+ case "UnquotedAttributeValue":
135
+ case "AttributeValue": {
136
+ const overlayTree = (_b = (_a = tree.resolveInner(from, 0).tree) == null ? void 0 : _a.prop(NodeProp.mounted)) == null ? void 0 : _b.tree;
137
+ if ((overlayTree == null ? void 0 : overlayTree.type.name) !== "Styles") {
138
+ return false;
139
+ }
140
+ const ret = [], offset = from + (typeName === "AttributeValue" ? 1 : 0);
141
+ overlayTree.iterate({
142
+ from: 0,
143
+ to: overlayTree.length,
144
+ enter({ name, from: overlayFrom, to: overlayTo }) {
145
+ const widgetOptions = discoverColorsInCSS(
146
+ tree,
147
+ {
148
+ from: offset + overlayFrom,
149
+ to: offset + overlayTo,
150
+ name
320
151
  },
321
- });
322
- }
323
- return Decoration.set(widgets);
324
- }
325
- function toFullHex(color) {
326
- if (color.length === 4) {
327
- // 3-char hex
328
- return [
329
- `#${color[1].repeat(2)}${color[2].repeat(2)}${color[3].repeat(2)}`,
330
- '',
331
- ];
332
- }
333
- if (color.length === 5) {
334
- // 4-char hex (alpha)
335
- return [
336
- `#${color[1].repeat(2)}${color[2].repeat(2)}${color[3].repeat(2)}`,
337
- color[4].repeat(2),
338
- ];
339
- }
340
- if (color.length === 9) {
341
- // 8-char hex (alpha)
342
- return [`#${color.slice(1, -2)}`, color.slice(-2)];
343
- }
344
- return [color, ''];
345
- }
346
- function rgbComponentToHex(component) {
347
- let numericValue;
348
- if (component.endsWith('%')) {
349
- // 0-100%
350
- const percent = Number(component.slice(0, -1));
351
- numericValue = Math.round((percent / 100) * 255.0);
352
- }
353
- else {
354
- numericValue = Number(component); // assume 0-255
355
- }
356
- return decimalToHex(numericValue);
357
- }
358
- function decimalToHex(decimal) {
359
- const hex = decimal.toString(16);
360
- return hex.length === 1 ? '0' + hex : hex;
361
- }
362
- function hexToRGBComponents(hex) {
363
- const r = hex.slice(1, 3);
364
- const g = hex.slice(3, 5);
365
- const b = hex.slice(5, 7);
366
- return [parseInt(r, 16), parseInt(g, 16), parseInt(b, 16)];
367
- }
368
- function rgbToHex(r, g, b) {
369
- return `#${rgbComponentToHex(r)}${rgbComponentToHex(g)}${rgbComponentToHex(b)}`;
370
- }
371
- function hslToHex(h, s, l) {
372
- const sFloat = Number(s) / 100;
373
- const lFloat = Number(l) / 100;
374
- const [r, g, b] = hslToRGB(Number(h), sFloat, lFloat);
375
- return `#${decimalToHex(r)}${decimalToHex(g)}${decimalToHex(b)}`;
376
- }
377
- function hslToRGB(hue, saturation, luminance) {
378
- // If there is no Saturation it means that it’s a shade of grey.
379
- // So in that case we just need to convert the Luminance and set R,G and B to that level.
380
- if (saturation === 0) {
381
- const value = Math.round(luminance * 255);
382
- return [value, value, value];
383
- }
384
- let temp1;
385
- // If Luminance is smaller then 0.5 (50%) then temporary_1 = Luminance x (1.0+Saturation)
386
- if (luminance < 0.5) {
387
- temp1 = luminance * (1.0 + saturation);
388
- }
389
- else {
390
- // If Luminance is equal or larger then 0.5 (50%) then temporary_1 = Luminance + Saturation – Luminance x Saturation
391
- temp1 = luminance + saturation - luminance * saturation;
392
- }
393
- // temporary_2 = 2 x Luminance – temporary _1
394
- const temp2 = 2 * luminance - temp1;
395
- // The next step is to convert the 360 degrees in a circle to 1 by dividing the angle by 360.
396
- hue = hue / 360.0;
397
- // And now we need another temporary variable for each color channel, temporary_R, temporary_G and temporary_B.
398
- // All values need to be between 0 and 1. In our case all the values are between 0 and 1
399
- const tempR = clamp(hue + 0.333);
400
- const tempG = hue;
401
- const tempB = clamp(hue - 0.333);
402
- const red = hueToRGB(temp1, temp2, tempR);
403
- const green = hueToRGB(temp1, temp2, tempG);
404
- const blue = hueToRGB(temp1, temp2, tempB);
405
- return [
406
- Math.round(red * 255),
407
- Math.round(green * 255),
408
- Math.round(blue * 255),
409
- ];
410
- }
411
- // If you get a negative value you need to add 1 to it.
412
- // If you get a value above 1 you need to subtract 1 from it.
413
- function clamp(num) {
414
- if (num < 0) {
415
- return num + 1;
416
- }
417
- if (num > 1) {
418
- return num - 1;
419
- }
420
- return num;
421
- }
422
- /**
423
- * Now we need to do up to 3 tests to select the correct formula for each color channel. Let’s start with Red.
424
- *
425
- * test 1 – If 6 x temporary_R is smaller then 1, Red = temporary_2 + (temporary_1 – temporary_2) x 6 x temporary_R
426
- * In the case the first test is larger then 1 check the following
427
- *
428
- * test 2 – If 2 x temporary_R is smaller then 1, Red = temporary_1
429
- * In the case the second test also is larger then 1 do the following
430
- *
431
- * test 3 – If 3 x temporary_R is smaller then 2, Red = temporary_2 + (temporary_1 – temporary_2) x (0.666 – temporary_R) x 6
432
- * In the case the third test also is larger then 2 you do the following
433
- *
434
- * Red = temporary_2
435
- */
436
- function hueToRGB(temp1, temp2, tempHue) {
437
- if (6 * tempHue < 1) {
438
- return temp2 + (temp1 - temp2) * 6 * tempHue;
439
- }
440
- if (2 * tempHue < 1) {
441
- return temp1;
442
- }
443
- if (3 * tempHue < 2) {
444
- return temp2 + (temp1 - temp2) * (0.666 - tempHue) * 6;
445
- }
446
- return temp2;
447
- }
448
- // https://www.niwa.nu/2013/05/math-behind-colorspace-conversions-rgb-hsl/
449
- function rgbToHSL(r, g, b) {
450
- const redPercent = r / 255;
451
- const greenPercent = g / 255;
452
- const bluePercent = b / 255;
453
- const min = Math.min(redPercent, greenPercent, bluePercent);
454
- const max = Math.max(redPercent, greenPercent, bluePercent);
455
- const luminance = (max + min) / 2;
456
- // If the min and max value are the same, it means that there is no saturation. ...
457
- // If there is no Saturation, we don’t need to calculate the Hue. So we set it to 0 degrees.
458
- if (max === min) {
459
- return [0, 0, luminance];
460
- }
461
- let saturation;
462
- // If Luminance is less or equal to 0.5, then Saturation = (max-min)/(max+min)
463
- if (luminance <= 0.5) {
464
- saturation = (max - min) / (max + min);
465
- }
466
- else {
467
- // If Luminance is bigger then 0.5. then Saturation = ( max-min)/(2.0-max-min)
468
- saturation = (max - min) / (2.0 - max - min);
469
- }
470
- let hue;
471
- // If Red is max, then Hue = (G-B)/(max-min)
472
- if (max === redPercent) {
473
- hue = (greenPercent - bluePercent) / (max - min);
474
- }
475
- else if (greenPercent === max) {
476
- // If Green is max, then Hue = 2.0 + (B-R)/(max-min)
477
- hue = 2.0 + (bluePercent - redPercent) / (max - min);
478
- }
479
- else {
480
- // If Blue is max, then Hue = 4.0 + (R-G)/(max-min)
481
- hue = 4.0 + (redPercent - greenPercent) / (max - min);
482
- }
483
- hue = Math.round(hue * 60); // convert to degrees
484
- // make hue positive angle/degrees
485
- while (hue < 0) {
486
- hue += 360;
487
- }
488
- return [hue, saturation, luminance];
489
- }
490
- const wrapperClassName = 'cm-css-color-picker-wrapper';
491
- class ColorPickerWidget extends WidgetType {
492
- constructor(_a) {
493
- var { color } = _a, state = __rest(_a, ["color"]);
494
- super();
495
- this.state = state;
496
- this.color = color;
152
+ doc
153
+ );
154
+ if (widgetOptions) {
155
+ if (Array.isArray(widgetOptions)) {
156
+ throw new Error("Unexpected nested overlays");
157
+ }
158
+ ret.push(widgetOptions);
159
+ }
160
+ }
161
+ });
162
+ return ret;
497
163
  }
498
- eq(other) {
499
- return (other.state.colorType === this.state.colorType &&
500
- other.color === this.color &&
501
- other.state.from === this.state.from &&
502
- other.state.to === this.state.to &&
503
- other.state.alpha === this.state.alpha);
164
+ case "CallExpression":
165
+ parse2 = parseCallExpression;
166
+ break;
167
+ case "ColorLiteral":
168
+ parse2 = parseColorLiteral;
169
+ break;
170
+ case "ValueName":
171
+ parse2 = parseNamedColor;
172
+ break;
173
+ default:
174
+ return void 0;
175
+ }
176
+ const result = parse2(doc.sliceString(from, to));
177
+ return result && Object.assign({ from, to }, result);
178
+ };
179
+ var parseCallExpression = (callExp) => {
180
+ const fn = callExp.split("(", 1)[0].toLowerCase();
181
+ switch (fn) {
182
+ case "rgba":
183
+ case "rgb":
184
+ if (!rgbCallExpRegex.test(callExp)) {
185
+ return void 0;
186
+ }
187
+ break;
188
+ case "hsla":
189
+ case "hsl":
190
+ if (!hslCallExpRegex.test(callExp)) {
191
+ return void 0;
192
+ }
193
+ break;
194
+ default:
195
+ return void 0;
196
+ }
197
+ const [r, g, b, alpha] = rgba(callExp);
198
+ return alpha !== void 0 && {
199
+ colorType: fn,
200
+ color: [r, g, b].map(Math.round),
201
+ alpha,
202
+ legacy: callExp.includes(","),
203
+ spaced: /\s/u.test(callExp)
204
+ };
205
+ };
206
+ var parseColorLiteral = (colorLiteral) => {
207
+ if (!hexRegex.test(colorLiteral)) {
208
+ return false;
209
+ }
210
+ const [r, g, b, alpha] = rgba(colorLiteral), { length } = colorLiteral;
211
+ return alpha !== void 0 && {
212
+ colorType: "hex",
213
+ color: [r, g, b],
214
+ alpha,
215
+ legacy: length === 4 || length === 7,
216
+ spaced: false
217
+ };
218
+ };
219
+ var parseNamedColor = (colorName) => {
220
+ const lcName = colorName.toLowerCase();
221
+ if (!Object.prototype.hasOwnProperty.call(namedColors, lcName)) {
222
+ return false;
223
+ }
224
+ const color = namedColors[lcName];
225
+ return {
226
+ colorType: "named",
227
+ color,
228
+ alpha: 1,
229
+ legacy: true,
230
+ spaced: false
231
+ };
232
+ };
233
+
234
+ import rgb2 from "color-space/rgb.js";
235
+ import "color-space/hsl.js";
236
+ import { numToHex } from "@bhsd/common";
237
+ var getDelimiter = (legacy, spaced) => legacy ? `,${spaced ? " " : ""}` : " ";
238
+ var alphaToString = (alpha, legacy, spaced) => alpha === 1 ? "" : (legacy ? `,${spaced ? " " : ""}` : " / ") + String(alpha === 0 ? alpha : Number(alpha.toFixed(2)));
239
+ var colorToString = ({ color, alpha, colorType, legacy, spaced }, value, colors) => {
240
+ var _a;
241
+ const currentColor = rgba(value).slice(0, 3);
242
+ if (currentColor.every((c, i) => c === Math.round(color[i]))) {
243
+ return false;
244
+ }
245
+ const delimiter = getDelimiter(legacy, spaced);
246
+ switch (colorType) {
247
+ case "rgba":
248
+ case "rgb":
249
+ return `${colorType}(${currentColor.join(delimiter)}${alphaToString(alpha, legacy, spaced)})`;
250
+ case "hsla":
251
+ case "hsl": {
252
+ const [h, s, l] = rgb2.hsl(currentColor.slice(0, 3));
253
+ return `${colorType}(${[Math.round(h), `${Math.round(s)}%`, `${Math.round(l)}%`].join(delimiter)}${alphaToString(alpha, legacy, spaced)})`;
504
254
  }
505
- toDOM() {
506
- const picker = document.createElement('input');
507
- pickerState.set(picker, this.state);
508
- picker.type = 'color';
509
- picker.value = this.color;
510
- const wrapper = document.createElement('span');
511
- wrapper.appendChild(picker);
512
- wrapper.className = wrapperClassName;
513
- return wrapper;
255
+ case "named":
256
+ if (colors && alpha === 1) {
257
+ const colorName = (_a = Object.entries(colors).find(([, colorValues]) => colorValues.every((c, i) => c === currentColor[i]))) == null ? void 0 : _a[0];
258
+ if (colorName) {
259
+ return colorName;
260
+ }
261
+ }
262
+ // fall through
263
+ default:
264
+ return value + (alpha === 1 ? "" : numToHex(alpha));
265
+ }
266
+ };
267
+
268
+ var wrapperClassName = "cm-css-color-picker-wrapper";
269
+ var pickerState = /* @__PURE__ */ new WeakMap();
270
+ var ColorPickerWidget = class extends WidgetType {
271
+ /** @class */
272
+ constructor(state, readOnly) {
273
+ super();
274
+ this.state = state;
275
+ this.readonly = readOnly;
276
+ }
277
+ /** @override */
278
+ eq(other) {
279
+ return other.readonly === this.readonly && other.state.from === this.state.from && other.state.to === this.state.to && other.state.colorType === this.state.colorType && other.state.color === this.state.color && other.state.alpha === this.state.alpha && other.state.legacy === this.state.legacy && other.state.spaced === this.state.spaced;
280
+ }
281
+ /** @override */
282
+ toDOM() {
283
+ const picker = document.createElement("input");
284
+ picker.type = "color";
285
+ picker.value = `#${this.state.color.map((c) => intToHex(c)).join("")}`;
286
+ if (this.readonly) {
287
+ picker.disabled = true;
514
288
  }
515
- ignoreEvent() {
516
- return false;
289
+ pickerState.set(picker, this.state);
290
+ const wrapper = document.createElement("span");
291
+ wrapper.className = wrapperClassName;
292
+ wrapper.append(picker);
293
+ return wrapper;
294
+ }
295
+ /** @override */
296
+ ignoreEvent(e) {
297
+ return e.type !== "change";
298
+ }
299
+ };
300
+ var colorPickersDecorations = (view, discoverColors) => {
301
+ const widgets = [], { state, visibleRanges } = view, tree = syntaxTree(state);
302
+ for (const { from, to } of visibleRanges) {
303
+ tree.iterate({
304
+ from,
305
+ to,
306
+ enter(node) {
307
+ const widgetOptions = discoverColors(tree, node, state.doc);
308
+ if (!widgetOptions) {
309
+ return widgetOptions;
310
+ }
311
+ for (const wo of Array.isArray(widgetOptions) ? widgetOptions : [widgetOptions]) {
312
+ widgets.push(
313
+ Decoration.widget({
314
+ widget: new ColorPickerWidget(wo, state.readOnly),
315
+ side: 1
316
+ }).range(wo.from)
317
+ );
318
+ }
319
+ return void 0;
320
+ }
321
+ });
322
+ }
323
+ return Decoration.set(widgets);
324
+ };
325
+ var colorPickerTheme = EditorView.baseTheme({
326
+ [`.${wrapperClassName}`]: {
327
+ display: "inline-block",
328
+ marginLeft: "0.6ch",
329
+ marginRight: "0.6ch",
330
+ height: "1em",
331
+ width: "1em",
332
+ transform: "translateY(1px)",
333
+ '& input[type="color"]': {
334
+ height: "100%",
335
+ width: "100%",
336
+ padding: 0,
337
+ border: "none",
338
+ outline: "1px solid #eee",
339
+ "&:enabled": {
340
+ cursor: "pointer"
341
+ },
342
+ "&::-webkit-color-swatch-wrapper": {
343
+ padding: 0
344
+ },
345
+ "&::-webkit-color-swatch": {
346
+ border: "none"
347
+ },
348
+ "&::-moz-color-swatch": {
349
+ border: "none"
350
+ }
517
351
  }
518
- }
519
- const colorPickerTheme = /*@__PURE__*/EditorView.baseTheme({
520
- [`.${wrapperClassName}`]: {
521
- display: 'inline-block',
522
- marginLeft: '0.6ch',
523
- marginRight: '0.6ch',
524
- height: '1em',
525
- width: '1em',
526
- transform: 'translateY(1px)',
527
- },
528
- [`.${wrapperClassName} input[type="color"]`]: {
529
- cursor: 'pointer',
530
- height: '100%',
531
- width: '100%',
532
- padding: 0,
533
- border: 'none',
534
- outline: '1px solid #eee',
535
- '&::-webkit-color-swatch-wrapper': {
536
- padding: 0,
537
- },
538
- '&::-webkit-color-swatch': {
539
- border: 'none',
540
- },
541
- '&::-moz-color-swatch': {
542
- border: 'none',
543
- },
544
- },
352
+ }
545
353
  });
546
- const makeColorPicker = (options) => ViewPlugin.fromClass(class ColorPickerViewPlugin {
547
- constructor(view) {
548
- this.decorations = colorPickersDecorations(view, options.discoverColors);
549
- }
550
- update(update) {
551
- if (update.docChanged || update.viewportChanged) {
552
- this.decorations = colorPickersDecorations(update.view, options.discoverColors);
354
+ var makeColorPicker = (discoverColors, colors) => [
355
+ ViewPlugin.fromClass(
356
+ class ColorPickerViewPlugin {
357
+ /** @class */
358
+ constructor(view) {
359
+ this.readOnly = view.state.readOnly;
360
+ this.decorations = colorPickersDecorations(view, discoverColors);
361
+ }
362
+ /** @implements */
363
+ update({ docChanged, viewportChanged, view }) {
364
+ const { readOnly } = view.state;
365
+ if (docChanged || viewportChanged || readOnly !== this.readOnly) {
366
+ this.readOnly = readOnly;
367
+ this.decorations = colorPickersDecorations(view, discoverColors);
553
368
  }
554
- }
555
- }, {
556
- decorations: (v) => v.decorations,
557
- eventHandlers: {
558
- change: (e, view) => {
559
- const target = e.target;
560
- if (target.nodeName !== 'INPUT' ||
561
- !target.parentElement ||
562
- !target.parentElement.classList.contains(wrapperClassName)) {
563
- return false;
564
- }
565
- const data = pickerState.get(target);
566
- let converted = target.value + data.alpha;
567
- if (data.colorType === ColorType.rgb) {
568
- converted = `rgb(${hexToRGBComponents(target.value).join(', ')}${data.alpha})`;
569
- }
570
- else if (data.colorType === ColorType.named && options.namedColors) {
571
- // If the hex is an exact match for another named color, prefer retaining name
572
- for (const [key, value] of options.namedColors.entries()) {
573
- if (value === target.value) {
574
- converted = key;
575
- }
576
- }
577
- }
578
- else if (data.colorType === ColorType.hsl) {
579
- const [r, g, b] = hexToRGBComponents(target.value);
580
- const [h, s, l] = rgbToHSL(r, g, b);
581
- converted = `hsl(${h}, ${Math.round(s * 100)}%, ${Math.round(l * 100)}%${data.alpha})`;
582
- }
369
+ }
370
+ },
371
+ {
372
+ decorations(v) {
373
+ return v.decorations;
374
+ },
375
+ eventHandlers: {
376
+ change(e, view) {
377
+ var _a;
378
+ const target = e.target;
379
+ if (target.nodeName !== "INPUT" || target.type !== "color" || !((_a = target.parentElement) == null ? void 0 : _a.classList.contains(wrapperClassName))) {
380
+ return false;
381
+ }
382
+ const state = pickerState.get(target), insert = colorToString(state, target.value, colors);
383
+ if (insert) {
384
+ const { from, to } = state;
583
385
  view.dispatch({
584
- changes: {
585
- from: data.from,
586
- to: data.to,
587
- insert: converted,
588
- },
386
+ changes: { from, to, insert }
589
387
  });
590
- return true;
591
- },
592
- },
593
- });
594
- const colorPicker = [
595
- /*@__PURE__*/makeColorPicker({
596
- discoverColors: discoverColorsInCSS,
597
- namedColors,
598
- }),
599
- colorPickerTheme,
388
+ }
389
+ return true;
390
+ }
391
+ }
392
+ }
393
+ ),
394
+ colorPickerTheme
600
395
  ];
601
-
602
- export { ColorType, colorPicker, colorPickerTheme, makeColorPicker, parseCallExpression, parseColorLiteral, parseNamedColor, wrapperClassName };
396
+ var colorPicker = /* @__PURE__ */ makeColorPicker(discoverColorsInCSS, namedColors2);
397
+ export {
398
+ colorPicker,
399
+ makeColorPicker,
400
+ namedColors2 as namedColors,
401
+ parseCallExpression,
402
+ parseColorLiteral,
403
+ parseNamedColor,
404
+ wrapperClassName
405
+ };