From e3821a62b42b6ec587bbcaf886d57d587f0fb105 Mon Sep 17 00:00:00 2001 From: Mohamed Fadl Date: Mon, 2 Nov 2026 00:40:29 +0200 Subject: [PATCH 1/3] Fix transparent color output and preserve stylesheet syntax during batch conversion --- README.md | 4 +++ app/components/file/FileUploader.vue | 2 +- app/composables/useColorConverter.ts | 4 +-- app/composables/useFileProcessor.ts | 43 +++++++++++++++-------- app/pages/file-converter.vue | 29 +++++++++++----- package-lock.json | 51 ++++++++++++++++++++++------ package.json | 3 ++ test/unit/colorConverter.test.ts | 8 +++++ test/unit/fileProcessor.test.ts | 36 ++++++++++++++++++++ 9 files changed, 142 insertions(+), 38 deletions(-) diff --git a/README.md b/README.md index a47af07..1775109 100644 --- a/README.md +++ b/README.md @@ -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 interpolated values are preserved. Indented `.sass` is not supported; export it as `.scss` or CSS first. Invalid stylesheets show an error instead of producing a partially converted file. 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..52f24f0 100644 --- a/app/composables/useColorConverter.ts +++ b/app/composables/useColorConverter.ts @@ -92,7 +92,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 +105,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..e369631 100644 --- a/app/composables/useFileProcessor.ts +++ b/app/composables/useFileProcessor.ts @@ -1,4 +1,6 @@ import { parse } from 'culori' +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' @@ -40,22 +42,33 @@ export function useFileProcessor() { 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 + // Parse declarations, never selectors, comments, strings or URL contents. + // SCSS interpolation is deliberately left untouched instead of guessing its value. + const stylesheet = parseStylesheet(content) + stylesheet.walkDecls((declaration) => { + const value = declaration.raws.value?.raw ?? declaration.value + if (value.includes('#{')) return + const start = declaration.source?.start?.offset + if (start === undefined) return + const valueStart = start + declaration.prop.length + declaration.raws.between!.length + valueParser(value).walk((node) => { + if (node.type !== 'word' && node.type !== 'function') return false + if (node.type === 'function' && /^(url|var|env)$/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, + ...getLineAndColumn(content, index) + }) + return false }) - } + }) return matches } diff --git a/app/pages/file-converter.vue b/app/pages/file-converter.vue index 78b0ef9..e9a5a6e 100644 --- a/app/pages/file-converter.vue +++ b/app/pages/file-converter.vue @@ -6,7 +6,7 @@ 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', ogTitle: 'ColorShift File Converter - Batch CSS Color Conversion', @@ -20,7 +20,7 @@ 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.' }) ]) @@ -39,6 +39,7 @@ const alphaFormat = ref<'decimal' | 'percentage' | 'preserve'>('decimal') // Result const processingResult = ref(null) const isProcessing = ref(false) +const toast = useToast() const previewTab = ref('side-by-side') // Handle file content loaded @@ -60,12 +61,22 @@ function processContent() { // Use requestAnimationFrame to keep UI responsive requestAnimationFrame(() => { - processingResult.value = processFile(fileContent.value, { - targetFormat: targetFormat.value, - precision: precision.value, - alphaFormat: alphaFormat.value - }) - isProcessing.value = false + try { + processingResult.value = processFile(fileContent.value, { + targetFormat: targetFormat.value, + precision: precision.value, + alphaFormat: alphaFormat.value + }) + } catch { + processingResult.value = null + toast.add({ + title: 'Unable to process stylesheet', + description: 'Use valid CSS or brace-based SCSS. Indented Sass is not supported.', + color: 'error' + }) + } finally { + isProcessing.value = false + } }) } @@ -81,7 +92,7 @@ watch([targetFormat, precision, alphaFormat], () => {
diff --git a/package-lock.json b/package-lock.json index 7613fbf..cf20a5d 100644 --- a/package-lock.json +++ b/package-lock.json @@ -19,6 +19,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" }, @@ -13679,9 +13682,9 @@ } }, "node_modules/postcss": { - "version": "8.5.6", - "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.6.tgz", - "integrity": "sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==", + "version": "8.5.32", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.32.tgz", + "integrity": "sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==", "funding": [ { "type": "opencollective", @@ -13698,9 +13701,9 @@ ], "license": "MIT", "dependencies": { - "nanoid": "^3.3.11", + "nanoid": "^3.3.20", "picocolors": "^1.1.1", - "source-map-js": "^1.2.1" + "source-map-js": "^1.2.2" }, "engines": { "node": "^10 || ^12 || >=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..c0ca372 100644 --- a/package.json +++ b/package.json @@ -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..443372a 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 } from 'culori' import { useColorConverter } from '../../app/composables/useColorConverter' // Mock the useColorFormats composable @@ -134,6 +135,13 @@ 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) + expect(parse(result.value)?.alpha).toBeCloseTo(0.5) + 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..41640c1 100644 --- a/test/unit/fileProcessor.test.ts +++ b/test/unit/fileProcessor.test.ts @@ -117,6 +117,42 @@ 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('/* #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('&:hover') + }) + + 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) From 8bb2a8924f1fb94a5d911d6040745731d97a037e Mon Sep 17 00:00:00 2001 From: Mohamed Fadl Date: Mon, 2 Nov 2026 00:58:14 +0200 Subject: [PATCH 2/3] Address review feedback on literal contexts, worker responsiveness, and conversion assertions --- CLAUDE.md | 2 +- README.md | 6 +- app/app.vue | 2 +- app/composables/useColorConverter.ts | 1 + app/composables/useFileProcessor.ts | 87 +++++++++++++++++++--------- app/composables/useSeoSchemas.ts | 6 +- app/pages/about.vue | 4 +- app/pages/file-converter.vue | 64 +++++++++++++------- app/pages/index.vue | 2 +- app/workers/fileProcessor.worker.ts | 17 ++++++ package.json | 2 +- test/unit/colorConverter.test.ts | 9 ++- test/unit/fileProcessor.test.ts | 25 ++++++++ 13 files changed, 167 insertions(+), 60 deletions(-) create mode 100644 app/workers/fileProcessor.worker.ts 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 1775109..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 @@ -158,4 +158,4 @@ Made with ❤️ using [Nuxt](https://nuxt.com) and [culori](https://culorijs.or ## Batch conversion boundaries -Batch conversion parses CSS and brace-based SCSS declarations, including nested rules and SCSS variable values. Selectors, comments, strings, URLs, and interpolated values are preserved. Indented `.sass` is not supported; export it as `.scss` or CSS first. Invalid stylesheets show an error instead of producing a partially converted file. +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/composables/useColorConverter.ts b/app/composables/useColorConverter.ts index 52f24f0..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 { diff --git a/app/composables/useFileProcessor.ts b/app/composables/useFileProcessor.ts index e369631..05a984c 100644 --- a/app/composables/useFileProcessor.ts +++ b/app/composables/useFileProcessor.ts @@ -1,4 +1,5 @@ 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' @@ -32,28 +33,69 @@ 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[] = [] + 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. - // SCSS interpolation is deliberately left untouched instead of guessing its value. const stylesheet = parseStylesheet(content) stylesheet.walkDecls((declaration) => { const value = declaration.raws.value?.raw ?? declaration.value - if (value.includes('#{')) return + // 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(value).walk((node) => { + 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|var|env)$/i.test(node.value)) 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) @@ -64,7 +106,7 @@ export function useFileProcessor() { converted: '', index, length: candidate.length, - ...getLineAndColumn(content, index) + ...position(index) }) return false }) @@ -78,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 @@ -90,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({ @@ -115,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 e9a5a6e..06c7d52 100644 --- a/app/pages/file-converter.vue +++ b/app/pages/file-converter.vue @@ -8,7 +8,7 @@ useSeoMeta({ description: '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.' @@ -24,8 +24,6 @@ useSchemaOrg([ }) ]) -const { processFile } = useFileProcessor() - // State const file = ref(null) const fileContent = ref('') @@ -40,10 +38,15 @@ const alphaFormat = ref<'decimal' | 'percentage' | 'preserve'>('decimal') const processingResult = ref(null) const isProcessing = ref(false) const toast = useToast() +let worker: Worker | null = null +onBeforeUnmount(() => worker?.terminate()) 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 @@ -58,24 +61,45 @@ function processContent() { if (!fileContent.value) return isProcessing.value = true + processingResult.value = null - // Use requestAnimationFrame to keep UI responsive - requestAnimationFrame(() => { - try { - processingResult.value = processFile(fileContent.value, { - targetFormat: targetFormat.value, - precision: precision.value, - alphaFormat: alphaFormat.value - }) - } catch { - processingResult.value = null - toast.add({ - title: 'Unable to process stylesheet', - description: 'Use valid CSS or brace-based SCSS. Indented Sass is not supported.', - color: 'error' - }) - } finally { - isProcessing.value = false + worker?.terminate() + 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 } }) } 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 = [ { 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) - expect(parse(result.value)?.alpha).toBeCloseTo(0.5) + 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(',') }) diff --git a/test/unit/fileProcessor.test.ts b/test/unit/fileProcessor.test.ts index 41640c1..c4358ed 100644 --- a/test/unit/fileProcessor.test.ts +++ b/test/unit/fileProcessor.test.ts @@ -127,6 +127,10 @@ describe('useFileProcessor', () => { }` 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"') @@ -138,9 +142,30 @@ describe('useFileProcessor', () => { 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' }) From 13ef46c46be95dfc0ec5f7191dd2debee925e274 Mon Sep 17 00:00:00 2001 From: Mohamed Fadl Date: Mon, 2 Nov 2026 01:08:23 +0200 Subject: [PATCH 3/3] Invalidate terminated worker references on reset and unmount --- app/pages/file-converter.vue | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/app/pages/file-converter.vue b/app/pages/file-converter.vue index 06c7d52..ca65040 100644 --- a/app/pages/file-converter.vue +++ b/app/pages/file-converter.vue @@ -39,7 +39,10 @@ const processingResult = ref(null) const isProcessing = ref(false) const toast = useToast() let worker: Worker | null = null -onBeforeUnmount(() => worker?.terminate()) +onBeforeUnmount(() => { + worker?.terminate() + worker = null +}) const previewTab = ref('side-by-side') // Handle file content loaded @@ -64,6 +67,7 @@ function processContent() { processingResult.value = null worker?.terminate() + worker = null let currentWorker: Worker try { currentWorker = new Worker(new URL('../workers/fileProcessor.worker.ts', import.meta.url), {