Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Playground] Color Swatches #1214

Merged
merged 15 commits into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@
"@typescript-eslint/eslint-plugin": "^8.8.0",
"cheerio": "^1.0.0-rc.12",
"codemirror": "^6.0.1",
"colorjs.io": "^0.5.2",
"date-fns": "^4.1.0",
"deep-equal": "^2.2.3",
"eslint-plugin-etc": "^2.0.3",
Expand Down
129 changes: 129 additions & 0 deletions source/assets/js/playground/color-decorator.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,129 @@
import {
Decoration,
DecorationSet,
EditorView,
ViewPlugin,
ViewUpdate,
WidgetType,
} from '@codemirror/view';
import {Range} from '@codemirror/state';
import {syntaxTree} from '@codemirror/language';
import Color from 'colorjs.io';

// The node types that may contain a color.
const COLOR_NODE_TYPES = ['CallExpression', 'ColorLiteral', 'ValueName'];

// The CallExpression types that may contain a color.
const COLOR_FUNCTIONS = [
jamesnw marked this conversation as resolved.
Show resolved Hide resolved
'color',
'hsl',
'hsla',
'lab',
'lch',
'oklab',
'oklch',
'rgb',
'rgba',
];

/** Parses content to add {@link ColorWidget} s after valid color declarations. */
function getColorDecorations(view: EditorView): DecorationSet {
const widgets: Range<Decoration>[] = [];
for (const {from, to} of view.visibleRanges) {
syntaxTree(view.state).iterate({
from,
to,
enter: node => {
if (COLOR_NODE_TYPES.includes(node.name)) {
const colorString = view.state.doc.sliceString(node.from, node.to);
if (
node.name === 'CallExpression' &&
// Ensure the CallExpression is a color.
!COLOR_FUNCTIONS.some(func => colorString.split('(')[0] === func)
) {
return;
}
try {
const color = new Color(colorString);
const deco = Decoration.widget({
widget: new ColorWidget(color),
side: 1,
});
widgets.push(deco.range(node.to));
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (error) {
// Color constuctor throws when colorString does not represent a
// color.
return;
}
}
},
});
}
return Decoration.set(widgets, true);
}

/** A {@link WidgetType} showing a color and gamut info. */
class ColorWidget extends WidgetType {
inP3: boolean | undefined;
constructor(readonly color: Color) {
super();
this.inP3 = this.color.inGamut('p3');
}

eq(other: ColorWidget): boolean {
return other.color === this.color;
}

toDOM(): HTMLDivElement {
return colorSwatchView(this.color.toString(), Boolean(this.inP3));
}
}

/* Generates div with color swatch and out of gamut warning. */
export function colorSwatchView(
color: string,
inP3Gamut: boolean
): HTMLDivElement {
const wrap = document.createElement('div');
wrap.setAttribute('aria-hidden', 'true');
wrap.className = 'cm-color-swatch';
wrap.style.setProperty('--color', color);
const box = wrap.appendChild(document.createElement('div'));
box.innerText = ' ';

if (!inP3Gamut) {
wrap.setAttribute('title', 'Outside of P3 gamut');
const warning = document.createElement('span');
warning.innerText = '⚠️';
wrap.appendChild(warning);
}

return wrap;
}

/** A {@link ViewPlugin} that shows colors inline with their declarations. */
export const colorDecorator = ViewPlugin.fromClass(
class {
colors: DecorationSet;
constructor(view: EditorView) {
this.colors = getColorDecorations(view);
}

update(update: ViewUpdate): void {
if (
update.docChanged ||
update.viewportChanged ||
syntaxTree(update.startState) !== syntaxTree(update.state)
)
this.colors = getColorDecorations(update.view);
}
},
{
decorations: instance => instance.colors,
provide: plugin =>
EditorView.atomicRanges.of(view => {
return view.plugin(plugin)?.colors || Decoration.none;
}),
}
);
16 changes: 16 additions & 0 deletions source/assets/js/playground/console-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ import {Exception, SourceSpan} from 'sass';

import {PlaygroundSelection, PlaygroundState, serializeState} from './utils';

import Color from 'colorjs.io';
import {colorSwatchView} from './color-decorator';

export interface ConsoleLogDebug {
options: {
span: SourceSpan;
Expand Down Expand Up @@ -99,6 +102,19 @@ export function displayForConsoleLog(
];
}
}
if (item.type === 'debug') {
try {
const color = new Color(item.message);
jamesnw marked this conversation as resolved.
Show resolved Hide resolved
const colorSwatch = colorSwatchView(
color.toString(),
color.inGamut('p3')
);
message = message + colorSwatch.outerHTML;
// eslint-disable-next-line @typescript-eslint/no-unused-vars
jamesnw marked this conversation as resolved.
Show resolved Hide resolved
} catch (error) {
// Ignore
}
}

if (item.type === 'warn' && item.options.deprecationType?.id) {
const safeLink = `https://sass-lang.com/d/${item.options.deprecationType.id}`;
Expand Down
3 changes: 3 additions & 0 deletions source/assets/js/playground/editor-setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ import {
import {playgroundHighlightStyle} from './theme.js';
import playgroundCompletions from './autocomplete.js';
import {EditorView} from 'codemirror';
import {colorDecorator} from './color-decorator.js';

const syntax = new Compartment();

Expand Down Expand Up @@ -71,6 +72,7 @@ const editorSetup = (() => [
autocompletion({override: playgroundCompletions}),
highlightActiveLine(),
drawSelection(),
colorDecorator,
keymap.of([
...closeBracketsKeymap,
...defaultKeymap,
Expand All @@ -92,6 +94,7 @@ const outputSetup = (() => [
syntaxHighlighting(playgroundHighlightStyle),
syntaxHighlighting(defaultHighlightStyle, {fallback: true}),
highlightActiveLine(),
colorDecorator,
EditorState.readOnly.of(true),
],
langCss(),
Expand Down
32 changes: 32 additions & 0 deletions source/assets/sass/components/_playground.scss
Original file line number Diff line number Diff line change
Expand Up @@ -307,8 +307,17 @@ $playground-base-colors: (

.console-message {
display: grid;
grid-template-columns: [console-text] 1fr [swatch] max-content;
line-height: var(--sl-line-height--console);

> * {
grid-column: console-text;
}

.cm-color-swatch {
grid-column: swatch;
}

a {
justify-self: start;
}
Expand Down Expand Up @@ -450,3 +459,26 @@ $playground-base-colors: (
height: 1.5rem;
}
}

// ColorSwatch
.cm-color-swatch {
display: inline-flex;

div {
background-color: var(--color);
height: var(--sl-size--swatch);
margin-inline-start: var(--sl-gutter--quarter);
outline: var(--sl-border--small) solid var(--sl-color--text-medium-dark);
outline-offset: calc(var(--sl-border--small) * -1);
width: var(--sl-size--swatch);
}

span {
font-family: var(--sl-font-family--emoji);
// Make slightly larger
font-size: var(--sl-font-size--small);
// Adjusted to accommodate larger font-size
line-height: 1.2;
margin-inline-start: var(--sl-gutter--quarter);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Let's make the warning sign more of a decoration on the swatch rather than a full-size inline element:

image

Suggested change
display: inline-flex;
div {
background-color: var(--color);
height: var(--sl-size--swatch);
margin-inline-start: var(--sl-gutter--quarter);
outline: var(--sl-border--small) solid var(--sl-color--text-medium-dark);
outline-offset: calc(var(--sl-border--small) * -1);
width: var(--sl-size--swatch);
}
span {
font-family: var(--sl-font-family--emoji);
// Make slightly larger
font-size: var(--sl-font-size--small);
// Adjusted to accommodate larger font-size
line-height: 1.2;
margin-inline-start: var(--sl-gutter--quarter);
}
position: relative;
div {
background-color: var(--color);
height: var(--sl-size--swatch);
margin-inline-start: var(--sl-gutter--quarter);
outline: var(--sl-border--small) solid var(--sl-color--text-medium-dark);
outline-offset: calc(var(--sl-border--small) * -1);
width: var(--sl-size--swatch);
}
span {
font-family: var(--sl-font-family--emoji);
font-size: 0.5625rem;
position: absolute;
top: -0.3125rem;
right: -0.3125rem;
}

You could even replace the span with an ::after based on a class name, although I don't have a strong opinion about whether or not that's better.

}
1 change: 1 addition & 0 deletions source/assets/sass/config/_scale.scss
Original file line number Diff line number Diff line change
Expand Up @@ -60,3 +60,4 @@ $sl-playground-heading: 2.75rem;
$sl-line-height--console: 0.95;
$sl-width--mac-stadium-icon: 7rem;
$sl-width--twitter-link: 8rem;
$sl-size--swatch: var(--sl-gutter);
2 changes: 2 additions & 0 deletions source/assets/sass/config/_typography.scss
Original file line number Diff line number Diff line change
Expand Up @@ -21,3 +21,5 @@ $sl-font-family--display: 'Source Serif Pro', 'Apple Garamond', 'Baskerville',
'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji' !default;
$sl-font-family--code: 'Source Code Pro', Menlo, 'SF Mono', monaco, inconsolata,
'Fira Mono', 'Droid Sans Mono', monospace, monospace !default;
$sl-font-family--emoji: 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji', system-ui !default;