Line data Source code
1 : import type { Layer, RGB, VectorContent } from 'ag-psd'
2 :
3 : import type { FillSpec, GradientStop } from '#/fill'
4 : import type { BlendFn } from '#/mode'
5 :
6 2 : export const PSD_BLEND_MODES: Partial<
7 : Record<BlendFn, NonNullable<Layer['blendMode']>>
8 : > = {
9 : normal: 'normal',
10 : multiply: 'multiply',
11 : screen: 'screen',
12 : overlay: 'overlay',
13 : darken: 'darken',
14 : lighten: 'lighten',
15 : 'color-dodge': 'color dodge',
16 : 'color-burn': 'color burn',
17 : 'hard-light': 'hard light',
18 : 'soft-light': 'soft light',
19 : difference: 'difference',
20 : exclusion: 'exclusion',
21 : 'linear-dodge': 'linear dodge',
22 : 'linear-burn': 'linear burn',
23 : 'vivid-light': 'vivid light',
24 : 'pin-light': 'pin light',
25 : 'linear-light': 'linear light',
26 : 'hard-mix': 'hard mix',
27 : subtract: 'subtract',
28 : divide: 'divide',
29 : 'grain-extract': 'normal',
30 : 'grain-merge': 'normal',
31 : hue: 'hue',
32 : saturation: 'saturation',
33 : color: 'color',
34 : luminosity: 'luminosity'
35 : }
36 :
37 0 : export function hexToPsdColor(hex: string): RGB {
38 0 : const raw = hex.replace('#', '')
39 0 : const full =
40 : raw.length === 3
41 : ? raw
42 : .split('')
43 : .map((c) => c + c)
44 : .join('')
45 : : raw.padEnd(6, '0')
46 0 : return {
47 : r: parseInt(full.slice(0, 2), 16) || 0,
48 : g: parseInt(full.slice(2, 4), 16) || 0,
49 : b: parseInt(full.slice(4, 6), 16) || 0
50 : }
51 : }
52 :
53 2 : const clamp = (v: number, lo: number, hi: number): number =>
54 : Math.max(lo, Math.min(hi, v))
55 :
56 0 : function toColorStops(stops: GradientStop[]) {
57 0 : return stops.map((s) => ({
58 : color: hexToPsdColor(s.color),
59 : location: clamp(s.offset, 0, 1),
60 : midpoint: 0.5
61 : }))
62 : }
63 :
64 0 : function toOpacityStops(stops: GradientStop[]) {
65 0 : return stops.map((s) => ({
66 : opacity: s.alpha === undefined ? 1 : clamp(s.alpha, 0, 1),
67 : location: clamp(s.offset, 0, 1),
68 : midpoint: 0.5
69 : }))
70 : }
71 :
72 0 : export function fillToVectorContent(spec: FillSpec): VectorContent {
73 0 : if (spec.type === 'solid') {
74 0 : return { type: 'color', color: hexToPsdColor(spec.color) }
75 : }
76 0 : const base = {
77 : name: 'Gradient',
78 : type: 'solid' as const,
79 : smoothness: 1,
80 : colorStops: toColorStops(spec.stops),
81 : opacityStops: toOpacityStops(spec.stops)
82 : }
83 0 : if (spec.type === 'linear') {
84 0 : const angle = ((-spec.angle % 360) + 360) % 360
85 0 : return {
86 : ...base,
87 : style: 'linear',
88 : angle: angle > 180 ? angle - 360 : angle,
89 : scale: 100
90 : }
91 : }
92 0 : return {
93 : ...base,
94 : style: 'radial',
95 : angle: 0,
96 : scale: clamp(spec.radius * 100, 1, 400),
97 : offset: { x: clamp(spec.cx - 0.5, -1, 1), y: clamp(spec.cy - 0.5, -1, 1) }
98 : }
99 : }
|