diff --git a/bun.lock b/bun.lock index a15a67350e..535376c94b 100644 --- a/bun.lock +++ b/bun.lock @@ -43,6 +43,7 @@ "@lezer/common": "^1.5.7", "@lezer/highlight": "^1.2.5", "@lezer/lr": "^1.4.10", + "@simonwep/pickr": "^1.10.3", "@ungap/custom-elements": "^1.3.0", "@xterm/addon-attach": "^0.12.0", "@xterm/addon-fit": "^0.11.0", @@ -78,7 +79,6 @@ "picomatch": "^4.0.7", "tough-cookie": "^6.0.2", "url-parse": "^1.5.10", - "vanilla-picker": "^2.12.3", "vscode-css-languageservice": "6.3.10", "vscode-html-languageservice": "5.6.2", "vscode-json-languageservice": "5.7.2", @@ -569,7 +569,7 @@ "@rspack/core": ["@rspack/core@2.2.8", "", { "dependencies": { "@rspack/binding": "2.2.8" }, "peerDependencies": { "@module-federation/runtime-tools": "^0.24.1 || ^2.0.0", "@swc/helpers": "^0.5.23" }, "optionalPeers": ["@module-federation/runtime-tools", "@swc/helpers"] }, "sha512-JugsVrnbMGNYzMH++7gR9enygpP/lAo9PbVRq3XmJg0ryIvCpST0XJjBcccaSjYaaPamsjrddihmgVLMFp+yXw=="], - "@sphinxxxx/color-conversion": ["@sphinxxxx/color-conversion@2.2.2", "", {}, "sha512-XExJS3cLqgrmNBIP3bBw6+1oQ1ksGjFh0+oClDKFYpCCqx/hlqwWO5KO/S63fzUo67SxI9dMrF0y5T/Ey7h8Zw=="], + "@simonwep/pickr": ["@simonwep/pickr@1.10.3", "", {}, "sha512-/vDqVAPU2mOOc5MXqia5MH+pwyfmSUyBKxSaj+YTZB78RmGfOtRXwD54fFmyHeUJ3Y4YWVGLJCy4zjxgDfylRA=="], "@standard-schema/spec": ["@standard-schema/spec@1.1.0", "", {}, "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w=="], @@ -1109,8 +1109,6 @@ "util-deprecate": ["util-deprecate@1.0.2", "", {}, "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw=="], - "vanilla-picker": ["vanilla-picker@2.12.3", "", { "dependencies": { "@sphinxxxx/color-conversion": "^2.2.2" } }, "sha512-qVkT1E7yMbUsB2mmJNFmaXMWE2hF8ffqzMMwe9zdAikd8u2VfnsVY2HQcOUi2F38bgbxzlJBEdS1UUhOXdF9GQ=="], - "verkit": ["verkit@0.3.2", "", {}, "sha512-zj/ob3UsvJGN0whEAKFp53REA5X66hvffVqoCtVQAakJKnKlH+/PcOfMoFwIG/o4rElqLv/ycAFlx8ZlXUorCg=="], "vite": ["vite@8.3.2", "", { "dependencies": { "lightningcss": "^1.33.0", "picomatch": "^4.0.7", "postcss": "^8.5.28", "rolldown": "~1.2.11", "tinyglobby": "^0.2.17" }, "optionalDependencies": { "fsevents": "~2.3.3" }, "peerDependencies": { "@types/node": "^20.19.0 || >=22.12.0", "@vitejs/devtools": "^0.7.1", "esbuild": "^0.27.0 || ^0.28.0", "jiti": ">=1.21.0", "less": "^4.0.0", "sass": "^1.70.0", "sass-embedded": "^1.70.0", "stylus": ">=0.54.8", "sugarss": "^5.0.0", "terser": "^5.16.0", "tsx": "^4.8.1", "yaml": "^2.4.2" }, "optionalPeers": ["@vitejs/devtools", "esbuild", "less", "sass-embedded", "stylus", "sugarss", "tsx", "yaml"], "bin": "bin/vite.js" }, "sha512-SQr1x6W5vVSbROg7vsyXIaxK9b0G7zsT68acdWWRmnBUsgDieLCRG+Rep9WdZgcposvv/GSnr4GUUBqB3vXq6w=="], diff --git a/package-lock.json b/package-lock.json index 0619a211cf..18f8c24e62 100644 --- a/package-lock.json +++ b/package-lock.json @@ -47,6 +47,7 @@ "@lezer/common": "^1.5.7", "@lezer/highlight": "^1.2.5", "@lezer/lr": "^1.4.10", + "@simonwep/pickr": "^1.10.3", "@ungap/custom-elements": "^1.3.0", "@xterm/addon-attach": "^0.12.0", "@xterm/addon-fit": "^0.11.0", @@ -82,7 +83,6 @@ "picomatch": "^4.0.7", "tough-cookie": "^6.0.2", "url-parse": "^1.5.10", - "vanilla-picker": "^2.12.3", "vscode-css-languageservice": "6.3.10", "vscode-html-languageservice": "5.6.2", "vscode-json-languageservice": "5.7.2", @@ -4394,11 +4394,11 @@ } } }, - "node_modules/@sphinxxxx/color-conversion": { - "version": "2.2.2", - "resolved": "https://registry.npmjs.org/@sphinxxxx/color-conversion/-/color-conversion-2.2.2.tgz", - "integrity": "sha512-XExJS3cLqgrmNBIP3bBw6+1oQ1ksGjFh0+oClDKFYpCCqx/hlqwWO5KO/S63fzUo67SxI9dMrF0y5T/Ey7h8Zw==", - "license": "ISC" + "node_modules/@simonwep/pickr": { + "version": "1.10.3", + "resolved": "https://registry.npmjs.org/@simonwep/pickr/-/pickr-1.10.3.tgz", + "integrity": "sha512-/vDqVAPU2mOOc5MXqia5MH+pwyfmSUyBKxSaj+YTZB78RmGfOtRXwD54fFmyHeUJ3Y4YWVGLJCy4zjxgDfylRA==", + "license": "MIT" }, "node_modules/@standard-schema/spec": { "version": "1.1.0", @@ -8032,15 +8032,6 @@ "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", "license": "MIT" }, - "node_modules/vanilla-picker": { - "version": "2.12.3", - "resolved": "https://registry.npmjs.org/vanilla-picker/-/vanilla-picker-2.12.3.tgz", - "integrity": "sha512-qVkT1E7yMbUsB2mmJNFmaXMWE2hF8ffqzMMwe9zdAikd8u2VfnsVY2HQcOUi2F38bgbxzlJBEdS1UUhOXdF9GQ==", - "license": "ISC", - "dependencies": { - "@sphinxxxx/color-conversion": "^2.2.2" - } - }, "node_modules/verkit": { "version": "0.3.2", "resolved": "https://registry.npmjs.org/verkit/-/verkit-0.3.2.tgz", diff --git a/package.json b/package.json index 29c2381fda..487c0ca289 100644 --- a/package.json +++ b/package.json @@ -113,6 +113,7 @@ "@lezer/common": "^1.5.7", "@lezer/highlight": "^1.2.5", "@lezer/lr": "^1.4.10", + "@simonwep/pickr": "^1.10.3", "@ungap/custom-elements": "^1.3.0", "@xterm/addon-attach": "^0.12.0", "@xterm/addon-fit": "^0.11.0", @@ -148,7 +149,6 @@ "picomatch": "^4.0.7", "tough-cookie": "^6.0.2", "url-parse": "^1.5.10", - "vanilla-picker": "^2.12.3", "vscode-css-languageservice": "6.3.10", "vscode-html-languageservice": "5.6.2", "vscode-json-languageservice": "5.7.2", diff --git a/rspack.config.js b/rspack.config.js index f06ba78561..cdd0591393 100644 --- a/rspack.config.js +++ b/rspack.config.js @@ -179,7 +179,7 @@ module.exports = (env, options) => { ignoreWarnings: [ { module: /typescript[\\/]lib[\\/]typescript\.js$/, - message: /Critical dependency/, + message: /Critical dependency|Dynamic module path/, }, ], module: { diff --git a/src/dialogs/color.js b/src/dialogs/color.js index 21b8343a12..52a982d89c 100644 --- a/src/dialogs/color.js +++ b/src/dialogs/color.js @@ -1,200 +1,198 @@ +import "@simonwep/pickr/dist/themes/nano.min.css"; +import "./color.scss"; +import Pickr from "@simonwep/pickr"; import actionStack from "lib/actionStack"; import restoreTheme from "lib/restoreTheme"; -import Picker from "vanilla-picker"; +import colorSwatches from "./colorSwatches"; +import formatColor from "./formatColor"; -let lastPicked = localStorage.__picker_last_picked || "#fff"; +const FORMATS = ["HEX", "RGB", "HSL"]; /** * Choose color - * @param {string} defaultColor Default color + * @param {string} [defaultColor] Default color * @param {Function} [onhide] Callback function * @returns {Promise} */ function color(defaultColor, onhide) { - defaultColor = defaultColor || lastPicked; - let type = checkColorType(defaultColor) || "hex"; return new Promise((resolve, reject) => { - const colorModes = ["hsl", "hex", "rgb"]; - let mode = colorModes.indexOf(type); - let color = null; - - const parent = tag("div", { - className: "message color-picker", + const $previousFocus = getFocusedElement(); + let isHidden = false; + const swatches = colorSwatches({ + getColor: getHexColor, + onSelect: selectColor, }); - - const formatToggle = tag("span", { - className: "format-toggle", - onclick: function (e) { - e.preventDefault(); - e.stopPropagation(); - formatPopup.classList.toggle("visible"); + const initialColor = defaultColor || swatches.lastUsed || "#ffffff"; + const $formatLabel = ; + const $pickerHost = ; + const $mask = ; + const $box = ( +
+
+ {strings["choose color"]} + +
+
{$pickerHost}
+
+ + +
+
+ ); + + $previousFocus?.blur(); + document.body.append($box, $mask); + + const pickr = Pickr.create({ + el: $pickerHost, + theme: "nano", + inline: true, + useAsButton: true, + showAlways: true, + closeWithKey: "", + default: initialColor, + defaultRepresentation: defaultColor + ? getRepresentation(defaultColor) + : getRepresentation(swatches.lastRepresentation), + components: { + preview: true, + opacity: true, + hue: true, + interaction: { + hex: true, + rgba: true, + hsla: true, + input: true, + }, }, - children: [ - tag("span", { - className: "format-toggle-text", - textContent: type.toUpperCase(), - }), - tag("span", { - className: "icon keyboard_arrow_down", - }), - ], - }); - - const formatPopup = tag("div", { - className: "format-popup", - children: [ - tag("div", { - className: "format-popup-backdrop", - onclick: function () { - formatPopup.classList.remove("visible"); - }, - }), - tag("div", { - className: "format-popup-body", - children: colorModes.map((m) => - tag("span", { - className: `format-option${m === type ? " active" : ""}`, - textContent: m.toUpperCase(), - onclick: function () { - mode = colorModes.indexOf(m); - type = m; - formatToggle.get(".format-toggle-text").textContent = - m.toUpperCase(); - formatPopup.querySelector(".active").classList.remove("active"); - this.classList.add("active"); - formatPopup.classList.remove("visible"); - picker.setOptions({ - color: color || defaultColor, - editorFormat: type, - }); - }, - }), - ), - }), - ], - }); - - const okBtn = tag("button", { - textContent: strings.ok, - onclick: function () { - hide(); - lastPicked = color; - localStorage.__picker_last_picked = color; - resolve(color); + i18n: { + "btn:last-color": strings.reset, + "aria:input": strings["choose color"], }, }); - const cancelBtn = tag("button", { - textContent: strings.cancel, - onclick: function () { - hide(); - reject(new Error("cancelled")); - }, - }); - const box = tag("div", { - className: "prompt box", - children: [ - tag("div", { - className: "title", - children: [ - tag("span", { - className: "title-text", - textContent: strings["choose color"], - }), - formatToggle, - ], - }), - parent, - tag("div", { - className: "button-container", - children: [cancelBtn, okBtn], - }), - ], - }); - const mask = tag("span", { - className: "mask", - onclick: function () { - hide(); - reject(new Error("cancelled")); - }, - }); - const picker = new Picker({ - parent, - popup: false, - editor: true, - color: defaultColor, - onChange, - alpha: true, - editorFormat: type, - }); - picker.show(); - parent.append(formatPopup); + pickr.on("init", onInit).on("change", syncColor).on("cancel", syncColor); actionStack.push({ id: "box", - action() { - hide(); - reject(new Error("cancelled")); - }, + action: cancel, }); - document.body.append(box, mask); - restoreTheme(true); - function hideSelect() { - box.classList.add("hide"); - restoreTheme(); - setTimeout(() => { - document.body.removeChild(box); - document.body.removeChild(mask); - if (typeof onhide === "function") onhide(); - }, 300); + function onInit() { + pickr.getRoot().interaction.result.after(swatches.$element); + syncColor(); } - function hide() { - actionStack.remove("box"); - const height = box.clientHeight; - box.style.height = height + "px"; - picker.destroy(); - hideSelect(); + function syncColor() { + const [red, green, blue, alpha] = pickr.getColor().toRGBA(); + const channels = [red, green, blue].map(Math.round).join(", "); + const { app, interaction } = pickr.getRoot(); + app.style.setProperty("--opaque-color", `rgb(${channels})`); + app.style.setProperty("--current-color", `rgba(${channels}, ${alpha})`); + if (document.activeElement !== interaction.result) { + interaction.result.value = getFormattedColor(); + } + $formatLabel.textContent = FORMATS[getFormatIndex()]; + swatches.update(); } - function onChange(c) { - if (!c) return; - - const alpha = c.rgba[3] < 1 ? true : false; - if (type === "hex") { - if (alpha) color = c.hex; - else color = c.hex.slice(0, -2); - } else if (type === "rgb") { - if (alpha) color = c.rgbaString; - else color = c.rgbString; - } else { - if (alpha) color = c.hslaString; - else color = c.hslString; - } + function getFormattedColor() { + return formatColor(pickr.getColor(), pickr.getColorRepresentation()); + } - if (color) { - setTimeout(() => { - const $editor = box.get(".picker_editor"); - if ($editor) $editor.style.backgroundColor = color; - }, 0); - } + function getHexColor() { + return formatColor(pickr.getColor(), "HEX"); + } + + function cycleFormat() { + const next = (getFormatIndex() + 1) % FORMATS.length; + pickr.setColorRepresentation(FORMATS[next]); + syncColor(); + } + + function getFormatIndex() { + const representation = pickr.getColorRepresentation(); + return Math.max( + FORMATS.findIndex((format) => representation.startsWith(format)), + 0, + ); + } + + function selectColor(value) { + const representation = pickr.getColorRepresentation(); + pickr.setColor(value, true); + pickr.setColorRepresentation(representation); + syncColor(); + } + + function confirm() { + if (!hide()) return; + const value = getFormattedColor(); + const hexColor = getHexColor(); + const representation = pickr.getColorRepresentation(); + resolve(value); + swatches.addRecent(hexColor, representation); + } + + function cancel() { + if (!hide()) return; + reject(new Error("cancelled")); + } + + function hide() { + if (isHidden) return false; + isHidden = true; + actionStack.remove("box"); + $box.style.height = `${$box.clientHeight}px`; + $box.classList.add("hide"); + restoreTheme(); + setTimeout(() => { + pickr.destroyAndRemove(); + $box.remove(); + $mask.remove(); + restoreFocus($previousFocus); + if (typeof onhide === "function") onhide(); + }, 300); + return true; } }); } /** - * - * @param {string} color - * @returns {'hex'|'rgb'|'hsl'} + * Blurring the focused element dismisses the on-screen keyboard + * @returns {HTMLElement | null} + */ +function getFocusedElement() { + let $focused = document.activeElement; + while ($focused?.shadowRoot?.activeElement) { + $focused = $focused.shadowRoot.activeElement; + } + return $focused === document.body ? null : $focused; +} + +/** + * @param {HTMLElement | null} $element + */ +function restoreFocus($element) { + if (!$element?.isConnected || getFocusedElement()) return; + $element.focus({ preventScroll: true }); +} + +/** + * Accepts a color string or a stored Pickr representation such as "RGBA" + * @param {string} [value] + * @returns {"HEX"|"RGBA"|"HSLA"} */ -function checkColorType(color) { - if (color.startsWith("#")) return "hex"; - if (color.startsWith("rgb")) return "rgb"; - if (color.startsWith("hsl")) return "hsl"; - return null; +function getRepresentation(value = "") { + const normalized = value.toLowerCase(); + if (normalized.startsWith("rgb")) return "RGBA"; + if (normalized.startsWith("hsl")) return "HSLA"; + return "HEX"; } export default color; diff --git a/src/dialogs/color.scss b/src/dialogs/color.scss new file mode 100644 index 0000000000..77436d1553 --- /dev/null +++ b/src/dialogs/color.scss @@ -0,0 +1,252 @@ +$checkerboard: url('data:image/svg+xml;utf8,'); +$surface: rgba(127, 127, 127, 0.14); +$hairline: inset 0 0 0 1px rgba(127, 127, 127, 0.25); +$swatch-size: 24px; + +@mixin color-fill($color) { + position: relative; + isolation: isolate; + overflow: hidden; + background: transparent; + + &::before, + &::after { + content: ""; + position: absolute; + inset: 0; + border-radius: inherit; + } + + &::before { + z-index: -1; + background: $checkerboard; + background-size: 8px; + } + + &::after { + background: $color; + box-shadow: $hairline; + } +} + +.prompt.color-picker { + .title, + .button-container { + flex-shrink: 0; + } + + .title { + display: flex; + align-items: center; + justify-content: space-between; + gap: 8px; + } + + .title-text { + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + } + + .format-toggle { + display: inline-flex; + flex-shrink: 0; + align-items: center; + gap: 2px; + height: 26px; + padding: 0 4px 0 8px; + border: none; + border-radius: 6px; + font-size: 12px; + font-weight: 600; + letter-spacing: 0.06em; + color: var(--popup-text-color); + background: $surface; + + .icon { + font-size: 16px; + opacity: 0.6; + } + } + + .color-picker-body { + flex: 1 1 auto; + min-height: 0; + overflow-y: auto; + padding: 14px 16px 4px; + color: var(--popup-text-color); + } + + .button-container { + margin-top: 8px; + } + + .pcr-app[data-theme="nano"] { + position: static; + width: 100%; + max-width: none; + font-size: 15px; + background: transparent; + box-shadow: none; + border-radius: 0; + transition: none; + + .pcr-selection { + height: auto; + grid-template-columns: 2.25em 1fr; + grid-template-rows: 9.5em auto auto; + grid-gap: 12px; + + .pcr-color-palette { + grid-area: 1 / 1 / 2 / 3; + + .pcr-palette { + border-radius: 4px; + box-shadow: $hairline; + + &::before { + border-radius: inherit; + } + } + } + + .pcr-color-preview { + grid-area: 2 / 1 / 4 / 2; + width: 2.25em; + height: 2.25em; + margin: 0; + align-self: center; + border-radius: 50%; + overflow: hidden; + box-shadow: $hairline; + + .pcr-last-color, + .pcr-current-color { + @include color-fill(var(--pcr-color)); + display: block; + flex: 1; + width: auto; + height: 100%; + border-radius: 0; + + &::after { + box-shadow: none; + } + } + } + + .pcr-color-chooser { + grid-area: 2 / 2 / 3 / 3; + } + + .pcr-color-opacity { + grid-area: 3 / 2 / 4 / 3; + + .pcr-slider { + background: + linear-gradient(to right, transparent, var(--opaque-color, black)), + $checkerboard; + background-size: + 100%, + 8px; + } + + .pcr-picker { + background: + linear-gradient(var(--current-color), var(--current-color)), + $checkerboard !important; + background-size: + 100%, + 8px !important; + } + } + + .pcr-color-chooser, + .pcr-color-opacity { + height: 10px; + margin: 0 10px; + + .pcr-slider { + box-shadow: $hairline; + } + } + + .pcr-picker { + width: 20px; + height: 20px; + border: 3px solid #fff; + box-shadow: + 0 0 0 1px rgba(0, 0, 0, 0.1), + 0 1px 4px rgba(0, 0, 0, 0.35); + } + } + + .pcr-interaction { + margin: 12px 0 0; + padding: 0; + gap: 10px; + + > * { + margin: 0; + } + + .pcr-type { + display: none; + } + + .pcr-result { + flex: 1 1 100%; + height: 36px; + margin: 0; + border-radius: 8px; + font-family: monospace; + font-size: 14px; + letter-spacing: 0.02em; + text-align: center; + color: var(--popup-text-color); + background: $surface; + user-select: text; + + &:focus { + box-shadow: 0 0 0 2px var(--active-color); + } + } + } + } + + .color-swatches { + display: flex; + flex: 1 1 100%; + flex-wrap: wrap; + gap: 10px; + padding: 2px 4px; + + &[hidden] { + display: none; + } + } + + .swatch { + @include color-fill(var(--swatch-color)); + overflow: visible; + width: $swatch-size; + height: $swatch-size; + padding: 0; + border: none; + border-radius: 50%; + transition: + transform 0.15s, + box-shadow 0.15s; + + &:active { + transform: scale(0.9); + } + + &.active { + box-shadow: + 0 0 0 2px var(--popup-background-color), + 0 0 0 4px var(--popup-text-color); + } + } +} diff --git a/src/dialogs/colorSwatches.js b/src/dialogs/colorSwatches.js new file mode 100644 index 0000000000..6ac5595096 --- /dev/null +++ b/src/dialogs/colorSwatches.js @@ -0,0 +1,123 @@ +import Color from "utils/color"; +import { isValidColor } from "utils/color/regex"; + +const RECENT_COLORS_KEY = "__picker_recent"; +const REPRESENTATION_KEY = "__picker_representation"; +const LEGACY_LAST_PICKED_KEY = "__picker_last_picked"; +const MAX_RECENT_COLORS = 8; + +/** + * @typedef {object} ColorSwatches + * @property {HTMLElement} $element + * @property {string} [lastUsed] Last confirmed color as lowercase hex + * @property {string} [lastRepresentation] Format the last color was confirmed in + * @property {() => void} update Syncs the selection with the current color + * @property {(color: string, representation: string) => void} addRecent + */ + +/** + * Recently used color swatches + * @param {object} options + * @param {() => string} options.getColor Returns the current color as lowercase hex + * @param {(color: string) => void} options.onSelect + * @returns {ColorSwatches} + */ +export default function colorSwatches({ getColor, onSelect }) { + const recentColors = getRecentColors(); + const $swatches = recentColors.map(createSwatch); + const $element =
{$swatches}
; + $element.hidden = !$swatches.length; + + return { + $element, + lastUsed: recentColors[0], + lastRepresentation: readValue(REPRESENTATION_KEY), + update, + addRecent, + }; + + function update() { + const current = getColor(); + for (const $swatch of $swatches) { + $swatch.classList.toggle("active", $swatch.dataset.color === current); + } + } + + function addRecent(color, representation) { + const recent = [ + color, + ...recentColors.filter((recentColor) => recentColor !== color), + ]; + writeValue( + RECENT_COLORS_KEY, + JSON.stringify(recent.slice(0, MAX_RECENT_COLORS)), + ); + writeValue(REPRESENTATION_KEY, representation); + } + + function createSwatch(color) { + const $swatch = ( + + ); + $swatch.dataset.color = color; + $swatch.style.setProperty("--swatch-color", color); + return $swatch; + } +} + +function getRecentColors() { + const recent = readColors(RECENT_COLORS_KEY); + if (recent.length) return recent.slice(0, MAX_RECENT_COLORS); + + const lastPicked = readValue(LEGACY_LAST_PICKED_KEY); + if (!isValidColor(lastPicked)) return []; + return [Color(lastPicked).hex.toString().toLowerCase()]; +} + +/** + * @param {string} key + * @returns {string[]} + */ +function readColors(key) { + try { + const colors = JSON.parse(readValue(key) || "[]"); + if (!Array.isArray(colors)) return []; + return colors.filter( + (color) => typeof color === "string" && isValidColor(color), + ); + } catch (error) { + console.error(error); + return []; + } +} + +/** + * @param {string} key + * @returns {string | undefined} + */ +function readValue(key) { + try { + return localStorage.getItem(key) ?? undefined; + } catch (error) { + console.error(error); + return undefined; + } +} + +/** + * @param {string} key + * @param {string} value + */ +function writeValue(key, value) { + try { + localStorage.setItem(key, value); + } catch (error) { + console.error(error); + } +} diff --git a/src/dialogs/formatColor.js b/src/dialogs/formatColor.js new file mode 100644 index 0000000000..27e8ba9169 --- /dev/null +++ b/src/dialogs/formatColor.js @@ -0,0 +1,41 @@ +/** + * Formats a Pickr color in the selected representation, omitting alpha when + * its 8-bit channel is opaque + * @param {Pickr.HSVaColor} hsva + * @param {string} representation + * @returns {string} + */ +export default function formatColor(hsva, representation) { + const alphaChannel = Math.round(hsva.a * 255); + + if (representation.startsWith("HEX")) { + const [red, green, blue] = hsva.toHEXA(); + const alpha = + alphaChannel < 255 ? alphaChannel.toString(16).padStart(2, "0") : ""; + return `#${red}${green}${blue}${alpha}`.toLowerCase(); + } + + const isHsl = representation.startsWith("HSL"); + const unit = isHsl ? "%" : ""; + const name = isHsl ? "hsl" : "rgb"; + const [first, second, third] = (isHsl ? hsva.toHSLA() : hsva.toRGBA()).map( + Math.round, + ); + const channels = `${first}, ${second}${unit}, ${third}${unit}`; + + if (alphaChannel >= 255) return `${name}(${channels})`; + return `${name}a(${channels}, ${formatAlpha(alphaChannel)})`; +} + +/** + * Two decimals unless that would change the 8-bit channel, so faint colors + * such as #ff000001 don't collapse to fully transparent + * @param {number} channel + * @returns {number} + */ +function formatAlpha(channel) { + const alpha = channel / 255; + const rounded = Number(alpha.toFixed(2)); + if (Math.round(rounded * 255) === channel) return rounded; + return Number(alpha.toFixed(3)); +} diff --git a/src/dialogs/style.scss b/src/dialogs/style.scss index 9ca51020df..9724d85222 100644 --- a/src/dialogs/style.scss +++ b/src/dialogs/style.scss @@ -250,32 +250,6 @@ min-height: 40px; margin: 5px 10px 0 10px; } - - .title-text { - flex: 1; - } - - .format-toggle { - flex-shrink: 0; - display: inline-flex; - align-items: center; - font-size: 0.55em; - font-weight: 600; - padding: 2px 4px 2px 6px; - border: solid 1px var(--popup-border-color, #ccc); - border-radius: 3px; - color: var(--popup-text-color, #333); - cursor: pointer; - user-select: none; - letter-spacing: 0.5px; - gap: 1px; - - .icon.keyboard_arrow_down { - font-size: 1.3em; - opacity: 0.5; - transition: opacity 0.15s; - } - } } .message { @@ -300,111 +274,6 @@ } } - &.color-picker { - position: relative; - - .button-container { - margin: 0; - } - - .format-popup { - position: absolute; - inset: 0; - display: none; - align-items: center; - justify-content: center; - z-index: 2; - - &.visible { - display: flex; - } - - .format-popup-backdrop { - position: absolute; - inset: 0; - background: rgba(0, 0, 0, 0.5); - } - - .format-popup-body { - position: relative; - display: flex; - gap: 4px; - padding: 6px; - border-radius: 8px; - background: var(--popup-background-color, #fff); - box-shadow: 0 4px 16px var(--box-shadow-color, rgba(0, 0, 0, 0.15)); - - .format-option { - padding: 6px 14px; - font-size: 12px; - font-weight: 600; - border-radius: 5px; - cursor: pointer; - user-select: none; - color: var(--popup-text-color, #333); - opacity: 0.5; - transition: - opacity 0.15s, - background-color 0.15s, - color 0.15s; - - &:hover { - opacity: 0.8; - } - - &.active { - opacity: 1; - background-color: var(--button-background-color, #39f); - color: var(--button-text-color, #fff); - } - } - } - } - } - - .picker_wrapper { - background-color: inherit; - box-shadow: none; - margin: auto; - - .picker_selector { - border: solid 1px rgb(37, 37, 37); - border: solid 1px var(--popup-text-color); - box-shadow: 0 0 2px 0 rgba(0, 0, 0, 0.2); - box-shadow: 0 0 2px 0 var(--box-shadow-color); - } - - .picker_hue { - .picker_selector { - border-radius: 0; - padding: 10px 2px; - } - } - - .picker_alpha { - .picker_selector { - border-radius: 0; - padding: 2px 10px; - } - } - - .picker_sample, - .picker_done { - display: none; - } - - .picker_editor { - width: 100%; - - input { - text-align: center; - background-color: rgb(0, 0, 0) !important; - mix-blend-mode: difference; - color: inherit; - } - } - } - img { max-width: 100%; max-height: 100%; diff --git a/src/utils/color/hex.js b/src/utils/color/hex.js index d297c6aa1a..6136a41dce 100644 --- a/src/utils/color/hex.js +++ b/src/utils/color/hex.js @@ -26,7 +26,7 @@ export default class Hex { */ static fromRgb(rgb) { const { r, g, b, a } = rgb; - return new Hex(r, g, b, a * 255); + return new Hex(r, g, b, Math.round(a * 255)); } /** diff --git a/tests/unit/color.test.js b/tests/unit/color.test.js index 703c6f1e14..0e7c3f6955 100644 --- a/tests/unit/color.test.js +++ b/tests/unit/color.test.js @@ -43,6 +43,19 @@ describe("Hex", () => { expect(rgb).toBeInstanceOf(Rgb); expect([rgb.r, rgb.g, rgb.b, rgb.a]).toEqual([10, 20, 30, 40]); }); + + it("rounds fractional alpha when converting from Rgb", () => { + const cases = [ + [new Rgb(255, 0, 0, 0.5), "#FF000080"], + [new Rgb(0, 128, 255, 1), "#0080FF"], + [new Rgb(18, 52, 86, 0), "#12345600"], + [new Rgb(10, 20, 30, 1 / 255), "#0A141E01"], + [new Rgb(200, 100, 50, 0.333), "#C8643255"], + ]; + for (const [rgb, expected] of cases) { + expect(Hex.fromRgb(rgb).toString()).toBe(expected); + } + }); }); describe("Hsl", () => { diff --git a/tests/unit/colorSwatches.test.js b/tests/unit/colorSwatches.test.js new file mode 100644 index 0000000000..6e8a4e7648 --- /dev/null +++ b/tests/unit/colorSwatches.test.js @@ -0,0 +1,117 @@ +// @vitest-environment happy-dom +import { createRequire } from "node:module"; +import tag from "html-tag-js"; +import Hex from "utils/color/hex"; +import { isValidColor } from "utils/color/regex"; +import Rgb from "utils/color/rgb"; +import { beforeEach, describe, expect, it, vi } from "vitest"; +import { loadSourceModule } from "../helpers/loadSourceModule"; + +createRequire(import.meta.url)("html-tag-js/polyfill"); + +const toColor = vi.fn(); +const colorSwatches = loadSourceModule( + "src/dialogs/colorSwatches.js", + { + "utils/color": toColor, + "utils/color/regex": { isValidColor }, + }, + { tag, document, localStorage }, +).default; + +describe("colorSwatches", () => { + beforeEach(() => { + localStorage.clear(); + toColor.mockReset(); + }); + + it("renders stored recent colors and ignores invalid entries", () => { + localStorage.setItem( + "__picker_recent", + JSON.stringify(["#112233", 42, "not a color", "#abcdef"]), + ); + const swatches = createSwatches(); + + expect(swatches.lastUsed).toBe("#112233"); + expect(getSwatchColors(swatches)).toEqual(["#112233", "#abcdef"]); + expect(swatches.$element.hidden).toBe(false); + }); + + it("falls back to the legacy last picked color as lowercase hex", () => { + toColor.mockReturnValue({ hex: Hex.fromRgb(new Rgb(18, 52, 86, 0.5)) }); + localStorage.setItem("__picker_last_picked", "rgba(18, 52, 86, 0.5)"); + + expect(createSwatches().lastUsed).toBe("#12345680"); + expect(toColor).toHaveBeenCalledWith("rgba(18, 52, 86, 0.5)"); + }); + + it("ignores an invalid legacy color", () => { + localStorage.setItem("__picker_last_picked", "garbage"); + const swatches = createSwatches(); + expect(toColor).not.toHaveBeenCalled(); + expect(swatches.lastUsed).toBeUndefined(); + expect(swatches.$element.hidden).toBe(true); + }); + + it("survives corrupt stored data", () => { + localStorage.setItem("__picker_recent", "{broken"); + vi.spyOn(console, "error").mockImplementation(() => {}); + expect(createSwatches().lastUsed).toBeUndefined(); + }); + + it("moves a confirmed color to the front and remembers its format", () => { + localStorage.setItem( + "__picker_recent", + JSON.stringify(["#111111", "#222222", "#333333"]), + ); + createSwatches().addRecent("#333333", "HSLA"); + + expect(JSON.parse(localStorage.getItem("__picker_recent"))).toEqual([ + "#333333", + "#111111", + "#222222", + ]); + expect(localStorage.getItem("__picker_representation")).toBe("HSLA"); + }); + + it("keeps at most eight recent colors", () => { + const colors = Array.from( + { length: 8 }, + (value, index) => `#00000${index}`, + ); + localStorage.setItem("__picker_recent", JSON.stringify(colors)); + createSwatches().addRecent("#ffffff", "HEX"); + + const recent = JSON.parse(localStorage.getItem("__picker_recent")); + expect(recent).toHaveLength(8); + expect(recent[0]).toBe("#ffffff"); + }); + + it("marks the swatch matching the current color and selects on click", () => { + localStorage.setItem( + "__picker_recent", + JSON.stringify(["#112233", "#abcdef"]), + ); + const onSelect = vi.fn(); + const swatches = createSwatches({ current: "#abcdef", onSelect }); + swatches.update(); + + const $active = swatches.$element.querySelectorAll(".swatch.active"); + expect([...$active].map(($swatch) => $swatch.dataset.color)).toEqual([ + "#abcdef", + ]); + + swatches.$element.querySelector(".swatch").click(); + expect(onSelect).toHaveBeenCalledWith("#112233"); + }); +}); + +function createSwatches({ current = "#000000", onSelect = vi.fn() } = {}) { + return colorSwatches({ getColor: () => current, onSelect }); +} + +function getSwatchColors(swatches) { + return [...swatches.$element.querySelectorAll(".swatch")].map( + ($swatch) => $swatch.dataset.color, + ); +} diff --git a/tests/unit/formatColor.test.js b/tests/unit/formatColor.test.js new file mode 100644 index 0000000000..0be1490334 --- /dev/null +++ b/tests/unit/formatColor.test.js @@ -0,0 +1,56 @@ +import formatColor from "dialogs/formatColor"; +import { describe, expect, it } from "vitest"; + +describe("formatColor", () => { + it("omits alpha for opaque colors", () => { + const color = createColor(1); + expect(formatColor(color, "HEXA")).toBe("#ff0000"); + expect(formatColor(color, "RGBA")).toBe("rgb(255, 0, 0)"); + expect(formatColor(color, "HSLA")).toBe("hsl(0, 100%, 50%)"); + }); + + it("keeps faint colors translucent", () => { + const color = createColor(1 / 255); + expect(formatColor(color, "HEX")).toBe("#ff000001"); + expect(formatColor(color, "RGBA")).toBe("rgba(255, 0, 0, 0.004)"); + }); + + it("uses two decimals when they keep the 8-bit channel", () => { + expect(formatColor(createColor(128 / 255), "RGBA")).toBe( + "rgba(255, 0, 0, 0.5)", + ); + expect(formatColor(createColor(0.25), "HSLA")).toBe( + "hsla(0, 100%, 50%, 0.25)", + ); + }); + + it("round-trips every 8-bit alpha through rgba()", () => { + for (let channel = 0; channel < 255; channel++) { + const formatted = formatColor(createColor(channel / 255), "RGBA"); + const [, alpha] = formatted.match(/^rgba\(255, 0, 0, ([\d.]+)\)$/); + expect(Math.round(Number(alpha) * 255)).toBe(channel); + } + }); + + it("snaps typed alpha to its 8-bit channel", () => { + expect(formatColor(createColor(0.0055), "RGBA")).toBe( + "rgba(255, 0, 0, 0.004)", + ); + }); + + it("treats alpha that rounds to 255 as opaque in every format", () => { + const color = createColor(0.999); + expect(formatColor(color, "HEX")).toBe("#ff0000"); + expect(formatColor(color, "RGBA")).toBe("rgb(255, 0, 0)"); + expect(formatColor(color, "HSLA")).toBe("hsl(0, 100%, 50%)"); + }); +}); + +function createColor(alpha) { + return { + a: alpha, + toHEXA: () => ["FF", "00", "00", "IGNORED"], + toRGBA: () => [255, 0, 0, alpha], + toHSLA: () => [0, 100, 50, alpha], + }; +}