diff --git a/CLAUDE.md b/CLAUDE.md index 5f0d1b3..4577b26 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -ColorShift is a client-side color conversion web app for designers and developers. It converts colors between CSS formats (HEX, RGB, HSL, OKLCH, LAB, LCH, HWB, named colors) and batch-processes CSS/SASS/PostCSS files. All processing happens in the browser—no backend. +ColorShift is a client-side color conversion web app for designers and developers. It converts colors between CSS formats (HEX, RGB, HSL, OKLCH, LAB, LCH, HWB, named colors) and batch-processes CSS/SCSS/PostCSS files. All processing happens in the browser—no backend. ## Commands diff --git a/README.md b/README.md index a47af07..57f521d 100644 --- a/README.md +++ b/README.md @@ -1,13 +1,13 @@ # ColorShift -A free, privacy-focused color conversion tool for designers and developers. Convert colors between CSS formats instantly and batch-process entire CSS/SASS/PostCSS files—all client-side. +A free, privacy-focused color conversion tool for designers and developers. Convert colors between CSS formats instantly and batch-process entire CSS/SCSS/PostCSS files—all client-side. [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](https://opensource.org/licenses/MIT) ## Features - **Instant Conversion** — Convert colors in real-time as you type with live preview -- **Batch Processing** — Upload CSS/SASS files and convert all colors at once +- **Batch Processing** — Upload CSS/SCSS files and convert all colors at once - **100% Client-Side** — All processing happens in your browser. No data sent to servers - **All CSS Formats** — Supports HEX, RGB, HSL, HWB, LAB, LCH, OKLAB, OKLCH @@ -155,3 +155,7 @@ This project is licensed under the MIT License - see the [LICENSE](LICENSE) file --- Made with ❤️ using [Nuxt](https://nuxt.com) and [culori](https://culorijs.org) + +## Batch conversion boundaries + +Batch conversion parses CSS and brace-based SCSS declarations, including nested rules and SCSS variable values. Selectors, comments, strings, URLs, and interpolation spans are preserved. Indented `.sass` is not supported; export it as `.scss` or CSS first. Literal colors alongside interpolation and inside var()/env() fallbacks are converted. Invalid stylesheets show an error instead of producing a partially converted file. Parsing and conversion run in a cancellable Web Worker, and stale results are discarded when files or settings change. diff --git a/app/app.vue b/app/app.vue index af0f226..c16d2b3 100644 --- a/app/app.vue +++ b/app/app.vue @@ -27,7 +27,7 @@ useHead(() => ({ })) const ogTitle = `${appConfig.name} - Convert Colors Between CSS Formats` -const ogDescription = `${appConfig.description}. Batch process CSS/SASS/PostCSS files client-side.` +const ogDescription = `${appConfig.description}. Batch process CSS/SCSS/PostCSS files client-side.` useSeoMeta({ titleTemplate: `%s - ${appConfig.name}`, diff --git a/app/components/file/FileUploader.vue b/app/components/file/FileUploader.vue index a2602a8..85f9c5a 100644 --- a/app/components/file/FileUploader.vue +++ b/app/components/file/FileUploader.vue @@ -11,7 +11,7 @@ const emit = defineEmits<{ const toast = useToast() const isDragging = ref(false) -const acceptedTypes = ['.css', '.scss', '.sass', '.postcss'] +const acceptedTypes = ['.css', '.scss', '.postcss'] const maxFileSize = 5 * 1024 * 1024 // 5MB async function handleFile(file: File) { diff --git a/app/composables/useColorConverter.ts b/app/composables/useColorConverter.ts index 3bfc0ef..418fcbd 100644 --- a/app/composables/useColorConverter.ts +++ b/app/composables/useColorConverter.ts @@ -1,5 +1,6 @@ import { parse, converter, formatHex, formatCss } from 'culori' import type { Color } from 'culori' +import { useColorFormats } from './useColorFormats' import type { ColorFormat } from './useColorFormats' export interface ConversionOptions { @@ -92,7 +93,7 @@ export function useColorConverter() { const b = Math.round((rgb.b ?? 0) * 255) const alpha = formatAlpha(rgb.alpha, alphaFormat) if (alpha) { - return `rgba(${r}, ${g}, ${b}${alpha})` + return `rgb(${r} ${g} ${b}${alpha})` } return `rgb(${r}, ${g}, ${b})` } @@ -105,7 +106,7 @@ export function useColorConverter() { const l = formatNumber((hsl.l ?? 0) * 100, 1) const alpha = formatAlpha(hsl.alpha, alphaFormat) if (alpha) { - return `hsla(${h}, ${s}%, ${l}%${alpha})` + return `hsl(${h} ${s}% ${l}%${alpha})` } return `hsl(${h}, ${s}%, ${l}%)` } diff --git a/app/composables/useFileProcessor.ts b/app/composables/useFileProcessor.ts index 34f0ea4..05a984c 100644 --- a/app/composables/useFileProcessor.ts +++ b/app/composables/useFileProcessor.ts @@ -1,4 +1,7 @@ import { parse } from 'culori' +import { useColorConverter } from './useColorConverter' +import { parse as parseStylesheet } from 'postcss-scss' +import valueParser from 'postcss-value-parser' import type { ColorFormat } from './useColorFormats' import type { ConversionOptions } from './useColorConverter' import { COMBINED_COLOR_REGEX } from '~/utils/colorPatterns' @@ -30,32 +33,84 @@ export interface ProcessingOptions extends ConversionOptions { export function useFileProcessor() { const { convertToFormat } = useColorConverter() - function getLineAndColumn(content: string, index: number): { line: number; column: number } { - const lines = content.substring(0, index).split('\n') - return { - line: lines.length, - column: (lines[lines.length - 1]?.length ?? 0) + 1 - } - } - function detectColors(content: string): ColorMatch[] { const matches: ColorMatch[] = [] - let match - - // Reset regex - COMBINED_COLOR_REGEX.lastIndex = 0 - - while ((match = COMBINED_COLOR_REGEX.exec(content)) !== null) { - const { line, column } = getLineAndColumn(content, match.index) - matches.push({ - original: match[0], - converted: '', - index: match.index, - length: match[0].length, - line, - column - }) + const lineStarts = [0] + for (let i = 0; i < content.length; i++) if (content[i] === '\n') lineStarts.push(i + 1) + const position = (index: number) => { + let low = 0, + high = lineStarts.length + while (low + 1 < high) { + const mid = (low + high) >>> 1 + if (lineStarts[mid]! <= index) low = mid + else high = mid + } + return { line: low + 1, column: index - lineStarts[low]! + 1 } } + // Parse declarations, never selectors, comments, strings or URL contents. + const stylesheet = parseStylesheet(content) + stylesheet.walkDecls((declaration) => { + const value = declaration.raws.value?.raw ?? declaration.value + // Mask only interpolation spans, keeping offsets and other literal colors intact. + let depth = 0 + let quote = '' + const masked = value.split('') + for (let i = 0; i < value.length; i++) { + const char = value[i]! + if (!depth) { + if (char === '"' || char === "'") { + const delimiter = char + while (++i < value.length) { + if (value[i] === '\\') i++ + else if (value[i] === delimiter) break + } + } else if (char === '/' && value[i + 1] === '*') { + const end = value.indexOf('*/', i + 2) + i = end < 0 ? value.length : end + 1 + } else if (char === '#' && value[i + 1] === '{') { + depth = 1 + masked[i] = masked[i + 1] = ' ' + i++ + } + continue + } + masked[i] = char === '\n' ? '\n' : ' ' + if (char === '\\') { + if (i + 1 < value.length) masked[++i] = ' ' + continue + } + if (quote) { + if (char === quote) quote = '' + continue + } + if (char === '"' || char === "'") { + quote = char + continue + } + if (char === '{') depth++ + else if (char === '}') depth-- + } + const start = declaration.source?.start?.offset + if (start === undefined) return + const valueStart = start + declaration.prop.length + (declaration.raws.between ?? ':').length + valueParser(masked.join('')).walk((node) => { + if (node.type !== 'word' && node.type !== 'function') return false + if (node.type === 'function' && /^url$/i.test(node.value)) return false + const candidate = value.slice(node.sourceIndex, node.sourceEndIndex) + COMBINED_COLOR_REGEX.lastIndex = 0 + const match = COMBINED_COLOR_REGEX.exec(candidate) + if (match?.[0] !== candidate) return + const index = valueStart + node.sourceIndex + matches.push({ + original: candidate, + converted: '', + index, + length: candidate.length, + ...position(index) + }) + return false + }) + }) return matches } @@ -65,8 +120,8 @@ export function useFileProcessor() { const matches = detectColors(content) const changes: ColorMatch[] = [] - let converted = content - let offset = 0 + const chunks: string[] = [] + let cursor = 0 let convertedCount = 0 let failedCount = 0 @@ -77,15 +132,8 @@ export function useFileProcessor() { const convertedValue = convertToFormat(color, targetFormat, conversionOptions) if (convertedValue && convertedValue !== match.original) { - // Update the converted content - const adjustedIndex = match.index + offset - converted = - converted.substring(0, adjustedIndex) + - convertedValue + - converted.substring(adjustedIndex + match.length) - - // Update offset for future replacements - offset += convertedValue.length - match.length + chunks.push(content.slice(cursor, match.index), convertedValue) + cursor = match.index + match.length // Track the change changes.push({ @@ -102,7 +150,7 @@ export function useFileProcessor() { return { original: content, - converted, + converted: chunks.join('') + content.slice(cursor), changes, stats: { total: matches.length, diff --git a/app/composables/useSeoSchemas.ts b/app/composables/useSeoSchemas.ts index 214cdca..672cc72 100644 --- a/app/composables/useSeoSchemas.ts +++ b/app/composables/useSeoSchemas.ts @@ -14,7 +14,7 @@ export function useSeoSchemas() { name: appConfig.name, url: appConfig.url, description: - 'Free online color converter tool. Convert colors between HEX, RGB, HSL, OKLCH, LAB, LCH, OKLAB, and HWB formats. Batch process CSS/SASS files. 100% client-side, privacy-focused.', + 'Free online color converter tool. Convert colors between HEX, RGB, HSL, OKLCH, LAB, LCH, OKLAB, and HWB formats. Batch process CSS/SCSS files. 100% client-side, privacy-focused.', applicationCategory: 'UtilitiesApplication', applicationSubCategory: 'DeveloperApplication', operatingSystem: 'All', @@ -42,7 +42,7 @@ export function useSeoSchemas() { 'HWB color format support', 'Alpha channel transparency support', 'Batch CSS file color conversion', - 'SASS file color conversion', + 'SCSS file color conversion', 'PostCSS file color conversion', 'Real-time color preview', 'Copy to clipboard functionality', @@ -81,7 +81,7 @@ export function useSeoSchemas() { { question: 'Can I convert entire CSS files?', answer: - 'Yes, ColorShift offers batch file conversion. Upload your CSS, SASS, or PostCSS files and convert all color values to your preferred format at once.' + 'Yes, ColorShift offers batch file conversion. Upload your CSS, SCSS, or PostCSS files and convert all color values to your preferred format at once.' }, { question: 'What is OKLCH and why should I use it?', diff --git a/app/pages/about.vue b/app/pages/about.vue index 4681586..bec3ae8 100644 --- a/app/pages/about.vue +++ b/app/pages/about.vue @@ -44,7 +44,7 @@ const features = [ { icon: 'i-lucide-file-code', title: 'Batch Processing', - description: 'Upload CSS/SASS files and convert all colors at once', + description: 'Upload CSS/SCSS files and convert all colors at once', highlight: true, highlightColor: 'info' as const }, @@ -68,7 +68,7 @@ const steps = [ { icon: 'i-lucide-upload', title: '1. Enter or Upload', - description: 'Type a color value or upload your CSS/SASS file' + description: 'Type a color value or upload your CSS/SCSS file' }, { icon: 'i-lucide-scan-search', diff --git a/app/pages/file-converter.vue b/app/pages/file-converter.vue index 78b0ef9..ca65040 100644 --- a/app/pages/file-converter.vue +++ b/app/pages/file-converter.vue @@ -6,9 +6,9 @@ import type { ProcessingResult } from '~/composables/useFileProcessor' useSeoMeta({ title: 'Batch CSS Color Converter - Convert Entire Files to OKLCH', description: - 'Batch convert all colors in CSS, SASS, and PostCSS files. Transform HEX to OKLCH, RGB to HSL, and more. 100% client-side processing, your files stay private.', + 'Batch convert all colors in CSS, SCSS, and PostCSS files. Transform HEX to OKLCH, RGB to HSL, and more. 100% client-side processing, your files stay private.', keywords: - 'batch color converter, css color converter, sass color converter, postcss color converter, bulk color conversion, hex to oklch converter, css file converter, convert css colors, batch hex to rgb, css color migration', + 'batch color converter, css color converter, scss color converter, postcss color converter, bulk color conversion, hex to oklch converter, css file converter, convert css colors, batch hex to rgb, css color migration', ogTitle: 'ColorShift File Converter - Batch CSS Color Conversion', ogDescription: 'Upload CSS files and convert all colors at once. Perfect for migrating to modern OKLCH format. 100% private, client-side processing.' @@ -20,12 +20,10 @@ useSchemaOrg([ '@type': 'WebPage', name: 'Batch CSS Color Converter - ColorShift', description: - 'Batch convert all colors in CSS, SASS, and PostCSS files to your preferred format.' + 'Batch convert all colors in CSS, SCSS, and PostCSS files to your preferred format.' }) ]) -const { processFile } = useFileProcessor() - // State const file = ref(null) const fileContent = ref('') @@ -39,10 +37,19 @@ const alphaFormat = ref<'decimal' | 'percentage' | 'preserve'>('decimal') // Result const processingResult = ref(null) const isProcessing = ref(false) +const toast = useToast() +let worker: Worker | null = null +onBeforeUnmount(() => { + worker?.terminate() + worker = null +}) const previewTab = ref('side-by-side') // Handle file content loaded function onContentLoaded(content: string, name: string) { + worker?.terminate() + worker = null + isProcessing.value = false fileContent.value = content filename.value = name processingResult.value = null @@ -57,15 +64,47 @@ function processContent() { if (!fileContent.value) return isProcessing.value = true + processingResult.value = null - // Use requestAnimationFrame to keep UI responsive - requestAnimationFrame(() => { - processingResult.value = processFile(fileContent.value, { + worker?.terminate() + worker = null + let currentWorker: Worker + try { + currentWorker = new Worker(new URL('../workers/fileProcessor.worker.ts', import.meta.url), { + type: 'module' + }) + } catch { + isProcessing.value = false + toast.add({ + title: 'Unable to process stylesheet', + description: 'This browser could not start file processing.', + color: 'error' + }) + return + } + worker = currentWorker + const finish = (result: ProcessingResult | null, error?: string) => { + if (worker !== currentWorker) return + processingResult.value = result + isProcessing.value = false + currentWorker.terminate() + worker = null + if (error) + toast.add({ title: 'Unable to process stylesheet', description: error, color: 'error' }) + } + currentWorker.onmessage = ({ + data + }: MessageEvent<{ result?: ProcessingResult; error?: string }>) => { + finish(data.result ?? null, data.error) + } + currentWorker.onerror = () => finish(null, 'Could not process this stylesheet. Please try again.') + currentWorker.postMessage({ + content: fileContent.value, + options: { targetFormat: targetFormat.value, precision: precision.value, alphaFormat: alphaFormat.value - }) - isProcessing.value = false + } }) } @@ -81,7 +120,7 @@ watch([targetFormat, precision, alphaFormat], () => {
diff --git a/app/pages/index.vue b/app/pages/index.vue index 41e1378..e1e65c3 100644 --- a/app/pages/index.vue +++ b/app/pages/index.vue @@ -226,7 +226,7 @@ const features = [ =14" @@ -14086,6 +14089,32 @@ "postcss": "^8.4.32" } }, + "node_modules/postcss-scss": { + "version": "4.0.9", + "resolved": "https://registry.npmjs.org/postcss-scss/-/postcss-scss-4.0.9.tgz", + "integrity": "sha512-AjKOeiwAitL/MXxQW2DliT28EKukvvbEWx3LBmJIRN8KfBGZbRTxNYW0kSqi1COiTZ57nZ9NW06S6ux//N1c9A==", + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss-scss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "engines": { + "node": ">=12.0" + }, + "peerDependencies": { + "postcss": "^8.4.29" + } + }, "node_modules/postcss-selector-parser": { "version": "7.1.1", "resolved": "https://registry.npmjs.org/postcss-selector-parser/-/postcss-selector-parser-7.1.1.tgz", @@ -14137,9 +14166,9 @@ "license": "MIT" }, "node_modules/postcss/node_modules/nanoid": { - "version": "3.3.11", - "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.11.tgz", - "integrity": "sha512-N8SpfPUnUp1bK+PMYW8qSWdl9U+wwNWI4QKxOYDy9JAro3WMX7p2OeVRF9v+347pnakNevPmiHhNmZ2HbFA76w==", + "version": "3.3.20", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz", + "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==", "funding": [ { "type": "github", @@ -15111,9 +15140,9 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz", + "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==", "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" diff --git a/package.json b/package.json index 7e9ed89..176baec 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "type": "module", "private": true, "version": "0.0.1", - "description": "A client-side web application for designers and developers to convert colors between different CSS color formats and batch-process CSS/SASS/PostCSS files.", + "description": "A client-side web application for designers and developers to convert colors between different CSS color formats and batch-process CSS/SCSS/PostCSS files.", "author": "Mohamed Fadl", "license": "MIT", "repository": { @@ -43,6 +43,9 @@ "eslint": "^9.39.1", "magic-regexp": "^0.10.0", "nuxt": "^4.2.1", + "postcss": "^8.5.32", + "postcss-scss": "^4.0.9", + "postcss-value-parser": "^4.2.0", "vue": "^3.5.25", "vue-router": "^4.6.3" }, diff --git a/test/unit/colorConverter.test.ts b/test/unit/colorConverter.test.ts index f3956e4..123afe0 100644 --- a/test/unit/colorConverter.test.ts +++ b/test/unit/colorConverter.test.ts @@ -1,4 +1,5 @@ import { describe, it, expect, vi } from 'vitest' +import { parse, converter } from 'culori' import { useColorConverter } from '../../app/composables/useColorConverter' // Mock the useColorFormats composable @@ -134,6 +135,18 @@ describe('useColorConverter', () => { expect(result.value).toBe('#ff573380') }) + it.each(['rgb', 'hsl'] as const)('serializes transparent %s as a valid CSS color', (format) => { + const result = convertColor('rgba(255, 87, 51, 0.5)', format) + expect(result.isValid).toBe(true) + const rgb = converter('rgb')(parse(result.value)!)! + expect(rgb.alpha).toBeCloseTo(0.5) + expect(rgb.r).toBeCloseTo(1, 2) + expect(rgb.g).toBeCloseTo(87 / 255, 2) + expect(rgb.b).toBeCloseTo(51 / 255, 2) + expect(result.value).toMatch(format === 'rgb' ? /^rgb\(/ : /^hsl\(/) + expect(result.value).not.toContain(',') + }) + it('should return invalid result for invalid input', () => { const result = convertColor('notacolor', 'hex') expect(result.isValid).toBe(false) diff --git a/test/unit/fileProcessor.test.ts b/test/unit/fileProcessor.test.ts index 023a28b..c4358ed 100644 --- a/test/unit/fileProcessor.test.ts +++ b/test/unit/fileProcessor.test.ts @@ -117,6 +117,67 @@ describe('useFileProcessor', () => { expect(matches).toHaveLength(3) }) + it('only detects declaration colors and preserves syntax contexts', () => { + const content = `/* #fff */ +#fff:hover { + content: "#fff"; + background-image: url("icons.svg#fff"); + color: #fff; + background: linear-gradient(#000, #fff); +}` + const result = processFile(content, { targetFormat: 'oklch' }) + expect(result.stats.converted).toBe(3) + expect(result.converted).toContain('color: oklch(0.68 0.17 40)') + expect(result.converted).toContain( + 'linear-gradient(oklch(0.68 0.17 40), oklch(0.68 0.17 40))' + ) + expect(result.converted).toContain('/* #fff */') + expect(result.converted).toContain('#fff:hover') + expect(result.converted).toContain('content: "#fff"') + expect(result.converted).toContain('url("icons.svg#fff")') + }) + + it('supports nested SCSS declarations without modifying interpolation', () => { + const content = '$brand: #fff; .card { &:hover { color: #000; } content: "#{#fff}"; }' + const result = processFile(content, { targetFormat: 'oklch' }) + expect(result.stats.converted).toBe(2) + expect(result.converted).toContain('content: "#{#fff}"') + expect(result.converted).toContain('$brand: oklch(0.68 0.17 40)') + expect(result.converted).toContain('color: oklch(0.68 0.17 40)') + expect(result.converted).toContain('&:hover') + }) + + it('converts literal neighbors of interpolation and var/env fallbacks only', () => { + const content = + '.x { --name: 1; box-shadow: 0 0 #fff #{ mix(#000, #fff) }; color: var(--brand, #fff); background: env(custom-color, #000); }' + const result = processFile(content, { targetFormat: 'oklch' }) + expect(result.stats.converted).toBe(3) + expect(result.converted).toContain('0 0 oklch(0.68 0.17 40) #{ mix(#000, #fff) }') + expect(result.converted).toContain('var(--brand, oklch(0.68 0.17 40))') + expect(result.converted).toContain('env(custom-color, oklch(0.68 0.17 40))') + expect(result.converted).toContain('--name: 1') + }) + + it('preserves UTF-16 offsets when interpolation follows emoji', () => { + const content = '.x { content: "😀"; box-shadow: #fff #{ $extra }; }' + const result = processFile(content, { targetFormat: 'oklch' }) + expect(result.converted).toContain( + 'content: "😀"; box-shadow: oklch(0.68 0.17 40) #{ $extra }' + ) + }) + + it('preserves comments inside declaration values and accurate source locations', () => { + const content = '.a { color: /* #000 */ #fff; }' + const result = processFile(content, { targetFormat: 'oklch' }) + expect(result.stats.converted).toBe(1) + expect(result.converted).toContain('/* #000 */') + expect(result.changes[0].index).toBe(content.indexOf('#fff')) + }) + + it('rejects malformed stylesheets instead of returning destructive partial edits', () => { + expect(() => processFile('.a { color: #fff;', { targetFormat: 'rgb' })).toThrow() + }) + it('should return empty array for content without colors', () => { const content = '.button { font-size: 16px; }' const matches = detectColors(content)