Skip to content

Commit 42a68a9

Browse files
authored
💭 Dream window: gradient-style — import keeps conic angle stops (hard-edged pies) + any-order at-positions (#138)
1 parent b21fe9a commit 42a68a9

4 files changed

Lines changed: 298 additions & 32 deletions

File tree

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import { describe, it, expect } from 'vitest'
2+
import { get } from 'svelte/store'
3+
import { parseGradient, parsePosition } from './parseGradient'
4+
import { applyParsedToStores } from './importGradient'
5+
import { buildGradientStrings } from '../utils/gradientString'
6+
import { gradient_stops } from '../store/gradient'
7+
8+
const stopPositions = (css: string) =>
9+
parseGradient(css).stops.filter((s: any) => s.kind === 'stop').map((s: any) => [s.position1, s.position2])
10+
11+
describe('conic stops given as angles', () => {
12+
it('keeps a hard-edged pie chart instead of blending it', () => {
13+
expect(stopPositions('conic-gradient(red 0 90deg, gold 90deg 180deg, teal 180deg 270deg, navy 270deg)'))
14+
.toEqual([['0', '25%'], ['25%', '50%'], ['50%', '75%'], ['75%', null]])
15+
})
16+
17+
it('converts turn, grad and rad to a fraction of the turn', () => {
18+
expect(stopPositions('conic-gradient(red .25turn, blue 200grad, green 4.71238898rad)'))
19+
.toEqual([['25%', null], ['50%', null], ['75%', null]])
20+
})
21+
22+
it('converts angle hints too', () => {
23+
const hint = parseGradient('conic-gradient(red, 120deg, blue)').stops.find((s: any) => s.kind === 'hint') as any
24+
expect(hint.percentage).toBe('33.3333')
25+
})
26+
27+
it('leaves linear stops alone (deg is not a linear position)', () => {
28+
expect(stopPositions('linear-gradient(red 10%, blue 90%)')).toEqual([['10%', null], ['90%', null]])
29+
})
30+
31+
it('imported pie re-exports with the same hard edges', () => {
32+
applyParsedToStores(parseGradient('conic-gradient(red 0 90deg, gold 90deg 180deg, teal 180deg 270deg, navy 270deg)'))
33+
const { modern } = buildGradientStrings({
34+
type: 'conic', space: 'srgb', interpolation: 'shorter', stops: get(gradient_stops),
35+
linear: { named_angle: 'to bottom', angle: null },
36+
radial: { shape: 'circle', size: 'farthest-corner', named_position: 'center', position: { x: null, y: null } },
37+
conic: { angle: 0, named_position: 'center', position: { x: null, y: null } },
38+
} as any)
39+
expect(modern.replace(/\s+/g, ' ')).toMatch(/red 25%, gold 25% 50%, teal 50% 75%, navy 75% \)/)
40+
})
41+
})
42+
43+
describe('parsePosition (CSS <position> after `at`)', () => {
44+
it.each([
45+
['center', 'center'],
46+
['top', 'top'],
47+
['center top', 'top'],
48+
['top center', 'top'],
49+
['left top', 'top left'],
50+
['top left', 'top left'],
51+
['right bottom', 'bottom right'],
52+
['left center', 'left'],
53+
])('%s -> named %s', (input, named) => {
54+
expect(parsePosition(input)).toEqual({ namedPosition: named })
55+
})
56+
57+
it.each([
58+
['30%', '30%', '50%'],
59+
['25% 75%', '25%', '75%'],
60+
['right 20%', '100%', '20%'],
61+
['20% top', '20%', '0%'],
62+
['right 10% bottom 20%', '90%', '80%'],
63+
['top 15% left 5%', '5%', '15%'],
64+
['20px 30%', '50%', '30%'],
65+
['left 2em', '0%', '50%'],
66+
['3rem top', '50%', '0%'],
67+
])('%s -> %s %s', (input, x, y) => {
68+
expect(parsePosition(input)).toEqual({ position: { x, y } })
69+
})
70+
71+
it.each(['5foo 30%', 'left right', 'top 20%', 'center 10% top', 'left 12px top', '20px 30px', 'foo bar', 'left 30', '30', 'left 10% top', 'center bottom 25%', '30deg 20%', 'right 10px bottom 20%'])('%s is rejected', input => {
72+
expect(parsePosition(input)).toEqual({})
73+
})
74+
75+
it('radial and conic preludes use it', () => {
76+
expect(parseGradient('radial-gradient(circle at center top, red, blue)').radial?.namedPosition).toBe('top')
77+
expect(parseGradient('conic-gradient(from 90deg at left bottom, red, blue)').conic?.namedPosition).toBe('bottom left')
78+
expect(parseGradient('radial-gradient(at right 20%, red, blue)').radial?.position).toEqual({ x: '100%', y: '20%' })
79+
})
80+
})
81+
82+
describe('repeating conic keeps raw angle units', () => {
83+
it('does not convert repeating-conic stop angles', () => {
84+
expect(stopPositions('repeating-conic-gradient(red 0deg 10deg, blue 10deg 20deg)')).toEqual([['0deg', '10deg'], ['10deg', '20deg']])
85+
})
86+
})

‎src/lib/importGradient.ts‎

Lines changed: 27 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,8 @@ import { radial_shape, radial_position, radial_named_position, radial_size } fro
44
import { conic_angle, conic_position, conic_named_position } from '../store/conic'
55
import type { ParsedGradient } from './parseGradient'
66
import { updateStops } from '../utils/stops'
7+
import { namedPosToPercent } from '../utils/radial'
8+
import type { Writable } from 'svelte/store'
79

810
function toDegreesString(valueWithUnit: string): string {
911
if (!valueWithUnit) return '0'
@@ -42,6 +44,29 @@ function stripPct(v: string | null): any {
4244
return v == null ? null : String(v).replace(/%$/, '')
4345
}
4446

47+
// Every branch leaves numeric x/y behind. Null x/y (a leftover of a previous import) is what
48+
// the position sliders coerce to 0, and the stores read 0,0 back as `top left`, so a 2nd import
49+
// would land in the corner instead of where the pasted CSS put it.
50+
function applyPosition(
51+
named: Writable<string>,
52+
position: Writable<any>,
53+
parsed?: { namedPosition?: string | null; position?: { x: string | null; y: string | null } },
54+
) {
55+
if (parsed?.namedPosition) {
56+
const name = normalizeNamedPosition(parsed.namedPosition)
57+
named.set(name)
58+
position.set(namedPosToPercent(name))
59+
} else if (parsed?.position?.x == null) {
60+
// no usable position (none given, or one the percentage controls can't hold): center
61+
named.set('center')
62+
position.set({ x: 50, y: 50 })
63+
} else {
64+
// '--' = custom position; a named 'center' would win over x/y in the output
65+
named.set('--')
66+
position.set({ x: stripPct(parsed.position.x), y: stripPct(parsed.position.y) })
67+
}
68+
}
69+
4570
export function applyParsedToStores(parsed: ParsedGradient, opts?: { clearLayers?: boolean }) {
4671
gradient_type.set(parsed.type)
4772
gradient_repeating.set(!!parsed.repeating)
@@ -64,25 +89,11 @@ export function applyParsedToStores(parsed: ParsedGradient, opts?: { clearLayers
6489
} else if (parsed.type === 'radial') {
6590
radial_shape.set(parsed.radial?.shape ?? 'circle')
6691
radial_size.set(parsed.radial?.size ?? 'farthest-corner')
67-
if (parsed.radial?.namedPosition) {
68-
radial_named_position.set(normalizeNamedPosition(parsed.radial.namedPosition))
69-
radial_position.set({ x: null, y: null })
70-
} else if (parsed.radial?.position) {
71-
// '--' = custom position; a named 'center' would win over x/y in the output
72-
radial_named_position.set('--')
73-
radial_position.set({ x: stripPct(parsed.radial.position.x), y: stripPct(parsed.radial.position.y) })
74-
}
92+
applyPosition(radial_named_position, radial_position, parsed.radial)
7593
} else if (parsed.type === 'conic') {
7694
const from = parsed.conic?.fromDeg ? toDegreesString(parsed.conic.fromDeg) : '0'
7795
conic_angle.set(from)
78-
if (parsed.conic?.namedPosition) {
79-
conic_named_position.set(normalizeNamedPosition(parsed.conic.namedPosition))
80-
conic_position.set({ x: null, y: null })
81-
} else if (parsed.conic?.position) {
82-
// '--' = custom position; a named 'center' would win over x/y in the output
83-
conic_named_position.set('--')
84-
conic_position.set({ x: stripPct(parsed.conic.position.x), y: stripPct(parsed.conic.position.y) })
85-
}
96+
applyPosition(conic_named_position, conic_position, parsed.conic)
8697
}
8798

8899
// Normalize position values: strip % suffix to get numeric strings
Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
import { describe, it, expect, beforeEach } from 'vitest'
2+
import { get } from 'svelte/store'
3+
import { parseGradient } from './parseGradient'
4+
import { applyParsedToStores } from './importGradient'
5+
import { buildGradientStrings } from '../utils/gradientString'
6+
import { gradient_stops } from '../store/gradient'
7+
import { radial_named_position, radial_position } from '../store/radial'
8+
import { conic_named_position, conic_position } from '../store/conic'
9+
10+
// The import dialog writes into long-lived stores, so the 2nd import of a session starts from
11+
// whatever the 1st left behind. A gradient with no usable position must land at center, not at
12+
// a leftover '--' or null x/y (the sliders coerce null to 0, which reads back as `top left`),
13+
// and a keyword `at` must land on that keyword's x/y for the same reason.
14+
const load = (css: string) => applyParsedToStores(parseGradient(css))
15+
16+
const output = (type: 'radial' | 'conic') =>
17+
buildGradientStrings({
18+
type, space: 'srgb', interpolation: 'shorter', stops: get(gradient_stops),
19+
linear: { named_angle: 'to bottom', angle: null },
20+
radial: { shape: 'circle', size: 'farthest-corner', named_position: get(radial_named_position), position: get(radial_position) },
21+
conic: { angle: 0, named_position: get(conic_named_position), position: get(conic_position) },
22+
} as any).modern.replace(/\s+/g, ' ')
23+
24+
const radial = () => ({ named: get(radial_named_position), pos: get(radial_position) })
25+
const conic = () => ({ named: get(conic_named_position), pos: get(conic_position) })
26+
const CENTER = { named: 'center', pos: { x: 50, y: 50 } }
27+
28+
beforeEach(() => {
29+
radial_named_position.set('center'); radial_position.set({ x: null, y: null })
30+
conic_named_position.set('center'); conic_position.set({ x: null, y: null })
31+
})
32+
33+
describe('importing twice keeps a missing/unusable position at center', () => {
34+
it('conic with no `at`, twice', () => {
35+
load('conic-gradient(red 0 90deg, gold 90deg 180deg, teal 180deg 270deg, navy 270deg)')
36+
expect(conic()).toEqual(CENTER)
37+
load('conic-gradient(from 45deg, red, blue)')
38+
expect(conic()).toEqual(CENTER)
39+
expect(output('conic')).not.toMatch(/at (0%|top left)/)
40+
})
41+
42+
it('conic with no `at` after a custom position', () => {
43+
load('conic-gradient(at 30% 40%, red, blue)')
44+
expect(conic()).toEqual({ named: '--', pos: { x: '30', y: '40' } })
45+
load('conic-gradient(red, blue)')
46+
expect(conic()).toEqual(CENTER)
47+
})
48+
49+
it('radial with no `at` after a custom position', () => {
50+
load('radial-gradient(circle at 30% 40%, red, blue)')
51+
load('radial-gradient(circle, red, blue)')
52+
expect(radial()).toEqual(CENTER)
53+
expect(output('radial')).not.toMatch(/at 0% 0%|top left/)
54+
})
55+
56+
it('radial with a px `at` after a custom position', () => {
57+
load('radial-gradient(circle at 30% 40%, red, blue)')
58+
load('radial-gradient(circle at 20px 20px, red, blue)')
59+
expect(radial()).toEqual(CENTER)
60+
// one length axis: only that axis centers, the percentage is kept
61+
load('radial-gradient(circle at 20px 30%, red, blue)')
62+
expect(radial()).toEqual({ named: '--', pos: { x: '50', y: '30' } })
63+
expect(output('radial')).toMatch(/at 50% 30%/)
64+
})
65+
66+
it('keyword `at` after a custom position', () => {
67+
load('conic-gradient(at 30% 40%, red, blue)')
68+
load('conic-gradient(from 90deg at left bottom, red, blue)')
69+
expect(conic()).toEqual({ named: 'bottom left', pos: { x: 0, y: 100 } })
70+
load('radial-gradient(circle at 10% 90%, red, blue)')
71+
load('radial-gradient(circle at center top, red, blue)')
72+
expect(radial()).toEqual({ named: 'top', pos: { x: 50, y: 0 } })
73+
expect(output('radial')).toMatch(/at top/)
74+
})
75+
})

‎src/lib/parseGradient.ts‎

Lines changed: 110 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -72,6 +72,106 @@ function isColorToken(token: string): boolean {
7272
// <length-percentage> or <angle-percentage>: `10%`, `0`, `12px`, `2em`, `-5%`, `30deg`, `.25turn`
7373
const POSITION_RE = /^[-+]?\d*\.?\d+(?:%|[a-z]+)?$/i
7474
const PCT_RE = /^[-+]?\d*\.?\d+%?$/
75+
// an `at` offset: the position controls hold percentages only (`0` is mapped to `0%` first)
76+
const POS_PCT_RE = /^[-+]?\d*\.?\d+%$/
77+
const LENGTH_RE = /^[-+]?\d*\.?\d+(?:px|r?em|r?ex|r?ch|r?lh|[sld]?v(?:w|h|i|b|min|max)|cq(?:w|h|i|b|min|max)|cm|mm|q|in|pt|pc)$/i
78+
79+
// A conic stop position given as an angle (`90deg`, `.25turn`, `100grad`, `1.5708rad`)
80+
const ANGLE_RE = /^([-+]?\d*\.?\d+)(deg|turn|grad|rad)$/i
81+
const TURN_UNITS: Record<string, number> = { deg: 360, turn: 1, grad: 400, rad: 2 * Math.PI }
82+
83+
// In a conic gradient a percentage is a fraction of the full turn, so `90deg` is exactly `25%`.
84+
// The stop store is percentage-based: converting keeps the stop where it was instead of
85+
// dropping it and letting the stop auto-distribute (which turns a hard-edged pie into a blend).
86+
function angleToTurnPct(token: string): string | null {
87+
const m = ANGLE_RE.exec(token.trim())
88+
if (!m) return null
89+
const pct = (parseFloat(m[1]) / TURN_UNITS[m[2].toLowerCase()]) * 100
90+
return parseFloat(pct.toFixed(4)) + '%'
91+
}
92+
93+
const H_KW: Record<string, number> = { left: 0, center: 50, right: 100 }
94+
const V_KW: Record<string, number> = { top: 0, center: 50, bottom: 100 }
95+
96+
// CSS <position> after `at` (radial/conic): 1-4 values, keywords in either order
97+
// (`center top`, `left top`), keyword + offset pairs (`right 10% bottom 20%`).
98+
// Two keywords become a named position the UI offers (`top`, `top left`); anything with an
99+
// offset becomes x/y percentages. A 1-2 value length offset (`20px 30%`) centers only that axis.
100+
// Returns {} for anything else the percentage-based controls can't hold (invalid CSS, px offsets
101+
// in a 3-4 value position), which leaves the position at center.
102+
export function parsePosition(input: string): { namedPosition?: string; position?: { x: string; y: string } } {
103+
const toks = input.trim().toLowerCase().split(/\s+/).filter(Boolean).map(t => (t === '0' ? '0%' : t))
104+
const isKw = (t: string) => t in H_KW || t in V_KW
105+
// the position stores are percentages (the output appends `%`), so only % or 0 offsets fit;
106+
// a unitless number (`left 30`) is invalid CSS, not 30%
107+
const isVal = (t: string) => POS_PCT_RE.test(t)
108+
// a length offset (`20px`) is valid CSS the controls can't hold
109+
const isLen = (t: string) => LENGTH_RE.test(t)
110+
// gradient <position> has no 3-value form (`left 10% top` is a background-position only)
111+
if (!toks.length || toks.length === 3 || toks.length > 4) return {}
112+
if (!toks.every(t => isKw(t) || isVal(t) || (toks.length <= 2 && isLen(t)))) return {}
113+
const pct = (n: number) => parseFloat(n.toFixed(4)) + '%'
114+
// 1-2 values: a length axis falls back to center, the other axis is kept (`20px 30%` = 50% 30%)
115+
if (toks.length <= 2 && toks.some(isLen)) {
116+
if (toks.every(t => isLen(t) || t === 'center')) return {}
117+
const [a, b = 'center'] = toks
118+
if (a in V_KW && !(a in H_KW)) return {}
119+
if (b in H_KW && !(b in V_KW)) return {}
120+
const axis = (t: string, kw: Record<string, number>) => (isLen(t) ? '50%' : t in kw ? pct(kw[t]) : t)
121+
return { position: { x: axis(a, H_KW), y: axis(b, V_KW) } }
122+
}
123+
124+
if (toks.every(isKw)) {
125+
if (toks.length > 2) return {}
126+
let h = 'center', v = 'center'
127+
for (const t of toks) {
128+
if (t === 'left' || t === 'right') { if (h !== 'center') return {}; h = t }
129+
else if (t === 'top' || t === 'bottom') { if (v !== 'center') return {}; v = t }
130+
}
131+
const name = [v, h].filter(k => k !== 'center').join(' ')
132+
return { namedPosition: name || 'center' }
133+
}
134+
135+
if (toks.length <= 2) {
136+
// 1-2 values with an offset: first is x, second is y (`30%`, `left 20%`, `25% top`)
137+
const [a, b = 'center'] = toks
138+
if (a in V_KW && !(a in H_KW)) return {}
139+
if (b in H_KW && !(b in V_KW)) return {}
140+
return {
141+
position: {
142+
x: a in H_KW ? pct(H_KW[a]) : a,
143+
y: b in V_KW ? pct(V_KW[b]) : b,
144+
},
145+
}
146+
}
147+
148+
// 3-4 values: keyword [offset] keyword [offset], axes given by the keywords
149+
const pairs: Array<{ kw: string; off: string | null }> = []
150+
for (let i = 0; i < toks.length; i++) {
151+
const kw = toks[i]
152+
if (!isKw(kw)) return {}
153+
const off = isVal(toks[i + 1] ?? '') ? toks[++i] : null
154+
if (off && kw === 'center') return {}
155+
pairs.push({ kw, off })
156+
}
157+
if (pairs.length !== 2) return {}
158+
let x: string | null = null, y: string | null = null
159+
// `right 10%` is 10% in from the right edge
160+
const resolve = (off: string | null, far: boolean) =>
161+
off == null ? pct(far ? 100 : 0) : pct(far ? 100 - parseFloat(off) : parseFloat(off))
162+
const assign = (axis: 'x'|'y', v: string) => {
163+
if (axis === 'x') { if (x != null) return false; x = v } else { if (y != null) return false; y = v }
164+
return true
165+
}
166+
let centers = 0
167+
for (const p of pairs) {
168+
if (p.kw === 'center') { centers++; continue }
169+
const axis = p.kw === 'left' || p.kw === 'right' ? 'x' : 'y'
170+
if (!assign(axis, resolve(p.off, p.kw === 'right' || p.kw === 'bottom'))) return {}
171+
}
172+
for (; centers > 0; centers--) if (!assign(x == null ? 'x' : 'y', pct(50))) return {}
173+
return x != null && y != null ? { position: { x, y } } : {}
174+
}
75175

76176
// The color at the start of a stop segment (`red 10px`, `oklch(70% .2 40) 5%`), or null.
77177
// Prelude segments (`to right`, `circle at 25% 25%`, `from 45deg in oklch`) never start with one.
@@ -204,19 +304,7 @@ export function parseGradient(input: string): ParsedGradient {
204304

205305
function extractPosition(src: string): { namedPosition?: string|null; position?: {x:string|null;y:string|null} } {
206306
const posMatch = src.match(/\bat\s+(.+)$/i)
207-
if (!posMatch) return {}
208-
const rhs = posMatch[1].trim()
209-
// try named positions
210-
const named = ['center','top left','top','top right','right','bottom right','bottom','bottom left','left','top center','bottom center','left center','right center']
211-
for (const n of named) {
212-
if (rhs.toLowerCase().startsWith(n)) return { namedPosition: n }
213-
}
214-
// split into two tokens for x/y
215-
const parts = rhs.split(/\s+/)
216-
if (parts.length >= 2) {
217-
return { position: { x: parts[0], y: parts[1] } }
218-
}
219-
return {}
307+
return posMatch ? parsePosition(posMatch[1]) : {}
220308
}
221309

222310
if (type === 'linear') {
@@ -267,15 +355,18 @@ export function parseGradient(input: string): ParsedGradient {
267355
}
268356

269357
// Build stops/hints from remaining segments
358+
// (a repeating gradient keeps its raw units: its tile *is* the stop positions)
359+
const turnStops = type === 'conic' && !repeating
270360
const stops: ParsedGradient['stops'] = []
271361
for (let i = firstColorIndex; i < segments.length; i++) {
272362
const seg = segments[i].trim()
273363
if (!seg) continue
274364

275365
// hint: a bare percentage value
276-
if (PCT_RE.test(seg) || (repeating && POSITION_RE.test(seg))) {
366+
const segTurnPct = turnStops ? angleToTurnPct(seg) : null
367+
if (segTurnPct || PCT_RE.test(seg) || (repeating && POSITION_RE.test(seg))) {
277368
// percentages are stored unitless, lengths keep their unit (`10px`)
278-
const pct = seg.trim().replace(/%$/,'')
369+
const pct = (segTurnPct ?? seg.trim()).replace(/%$/,'')
279370
stops.push({ kind: 'hint', auto: null, percentage: pct })
280371
continue
281372
}
@@ -325,7 +416,10 @@ export function parseGradient(input: string): ParsedGradient {
325416
// Percentages and unitless numbers. Lengths/angles (px, em, deg...) are left unset for
326417
// normal gradients so the UI can auto-distribute them, but a repeating gradient's tile
327418
// *is* its stop positions (`#000 0 10px, #fff 10px 20px`): drop them and it stops repeating.
328-
if (PCT_RE.test(t) || (repeating && POSITION_RE.test(t))) {
419+
const turnPct = turnStops ? angleToTurnPct(t) : null
420+
if (turnPct) {
421+
posTokens.push(turnPct)
422+
} else if (PCT_RE.test(t) || (repeating && POSITION_RE.test(t))) {
329423
posTokens.push(t)
330424
}
331425
}

0 commit comments

Comments
 (0)