psd 4.1.0 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. package/README.md +139 -5
  2. package/dist/descriptor.js +6 -2
  3. package/dist/descriptor.js.map +1 -1
  4. package/dist/image.d.ts +22 -2
  5. package/dist/image.d.ts.map +1 -1
  6. package/dist/image.js +28 -10
  7. package/dist/image.js.map +1 -1
  8. package/dist/index.d.ts +9 -6
  9. package/dist/index.d.ts.map +1 -1
  10. package/dist/index.js +3 -1
  11. package/dist/index.js.map +1 -1
  12. package/dist/layer-info.d.ts +52 -5
  13. package/dist/layer-info.d.ts.map +1 -1
  14. package/dist/layer-info.js +32 -5
  15. package/dist/layer-info.js.map +1 -1
  16. package/dist/layer-styles.d.ts +10 -0
  17. package/dist/layer-styles.d.ts.map +1 -1
  18. package/dist/layer-styles.js +5 -5
  19. package/dist/layer-styles.js.map +1 -1
  20. package/dist/layer.d.ts +32 -0
  21. package/dist/layer.d.ts.map +1 -1
  22. package/dist/layer.js +55 -4
  23. package/dist/layer.js.map +1 -1
  24. package/dist/linked-files.d.ts +32 -0
  25. package/dist/linked-files.d.ts.map +1 -0
  26. package/dist/linked-files.js +45 -0
  27. package/dist/linked-files.js.map +1 -0
  28. package/dist/nodes.d.ts +11 -1
  29. package/dist/nodes.d.ts.map +1 -1
  30. package/dist/nodes.js +10 -0
  31. package/dist/nodes.js.map +1 -1
  32. package/dist/path-record.d.ts +28 -0
  33. package/dist/path-record.d.ts.map +1 -1
  34. package/dist/path-record.js +54 -1
  35. package/dist/path-record.js.map +1 -1
  36. package/dist/patterns.d.ts +24 -0
  37. package/dist/patterns.d.ts.map +1 -0
  38. package/dist/patterns.js +108 -0
  39. package/dist/patterns.js.map +1 -0
  40. package/dist/png.d.ts +11 -2
  41. package/dist/png.d.ts.map +1 -1
  42. package/dist/png.js +11 -2
  43. package/dist/png.js.map +1 -1
  44. package/dist/psd.d.ts +13 -2
  45. package/dist/psd.d.ts.map +1 -1
  46. package/dist/psd.js +23 -1
  47. package/dist/psd.js.map +1 -1
  48. package/dist/resources.d.ts +6 -0
  49. package/dist/resources.d.ts.map +1 -1
  50. package/dist/resources.js +18 -0
  51. package/dist/resources.js.map +1 -1
  52. package/dist/shapes.d.ts +94 -0
  53. package/dist/shapes.d.ts.map +1 -0
  54. package/dist/shapes.js +76 -0
  55. package/dist/shapes.js.map +1 -0
  56. package/dist/type-tool.d.ts +27 -2
  57. package/dist/type-tool.d.ts.map +1 -1
  58. package/dist/type-tool.js +29 -2
  59. package/dist/type-tool.js.map +1 -1
  60. package/package.json +3 -2
  61. package/src/descriptor.ts +6 -2
  62. package/src/image.ts +48 -12
  63. package/src/index.ts +17 -5
  64. package/src/layer-info.ts +74 -5
  65. package/src/layer-styles.ts +7 -5
  66. package/src/layer.ts +66 -4
  67. package/src/linked-files.ts +66 -0
  68. package/src/nodes.ts +14 -1
  69. package/src/path-record.ts +63 -2
  70. package/src/patterns.ts +113 -0
  71. package/src/png.ts +21 -2
  72. package/src/psd.ts +25 -1
  73. package/src/resources.ts +20 -0
  74. package/src/shapes.ts +156 -0
  75. package/src/type-tool.ts +45 -2
@@ -0,0 +1,113 @@
1
+ import { decodePlanes, type Plane, type RGBAImage } from './image.ts';
2
+ import { encodePng } from './png.ts';
3
+ import { MODES, type Header } from './psd.ts';
4
+ import type { Reader } from './reader.ts';
5
+
6
+ interface PatternPlane extends Plane {
7
+ depth: number;
8
+ width: number;
9
+ height: number;
10
+ }
11
+
12
+ /**
13
+ * A pattern from the document's `Patt`, `Pat2` or `Pat3` blocks. Pattern fills and overlays refer
14
+ * to it by `id`. The pixels are decoded on demand.
15
+ */
16
+ export class Pattern {
17
+ /** The unique ID that pattern fills (`info.patternFill.Ptrn.Idnt`) and layer styles (`pattern.id`) refer to. */
18
+ readonly id: string;
19
+ /** The name. Photoshop's presets have localizable names like `$$$/Presets/Patterns/Water=Water`. */
20
+ readonly name: string;
21
+ readonly width: number;
22
+ readonly height: number;
23
+ /** Color mode ID, as in `psd.header.mode`. */
24
+ readonly mode: number;
25
+ readonly #reader: Reader;
26
+ readonly #colorTable: Uint8Array = new Uint8Array(0);
27
+ readonly #planes: PatternPlane[] = [];
28
+
29
+ constructor(r: Reader) {
30
+ this.#reader = r;
31
+ const version = r.uint32();
32
+ if (version !== 1) throw new Error(`Unsupported pattern version ${version}`);
33
+ this.mode = r.uint32();
34
+ r.skip(4); // height and width (2 bytes each), also in the rectangle below
35
+ this.name = r.unicode();
36
+ this.id = r.pascal();
37
+
38
+ // An indexed pattern's color table is 256 RGB triplets. The 4 bytes after it are undocumented
39
+ // and skipped as in psd-tools. The decoder wants the reds, then the greens, then the blues.
40
+ if (this.mode === 2) {
41
+ const table = r.bytesView(768);
42
+ this.#colorTable = new Uint8Array(768);
43
+ for (let i = 0; i < 768; i++) this.#colorTable[(i % 3) * 256 + Math.floor(i / 3)] = table[i]!;
44
+ r.skip(4);
45
+ }
46
+
47
+ // The pixels are a "virtual memory array list": a rectangle and a slot for each channel, and
48
+ // two more slots for a user mask and the transparency.
49
+ const listVersion = r.uint32();
50
+ if (listVersion !== 3) throw new Error(`Unsupported pattern data version ${listVersion}`);
51
+ r.skip(4); // length
52
+ const [top, left, bottom, right] = [r.uint32(), r.uint32(), r.uint32(), r.uint32()];
53
+ this.width = right - left;
54
+ this.height = bottom - top;
55
+ const colorSlots = r.uint32();
56
+ for (let slot = 0; slot < colorSlots + 2; slot++) {
57
+ if (r.uint32() === 0) continue; // not written
58
+ const length = r.uint32();
59
+ if (length === 0) continue;
60
+ const end = r.pos + length;
61
+ const depth = r.uint32();
62
+ const [planeTop, planeLeft, planeBottom, planeRight] = [r.uint32(), r.uint32(), r.uint32(), r.uint32()];
63
+ r.skip(2); // pixel depth again
64
+ const compression = r.uint8();
65
+ // Written color slots are the color channels in order; the last slot is the transparency.
66
+ const id = slot < colorSlots ? this.#planes.length : slot === colorSlots + 1 ? -1 : undefined;
67
+ const [width, height] = [planeRight - planeLeft, planeBottom - planeTop];
68
+ if (id !== undefined) this.#planes.push({ id, compression, offset: r.pos, end, depth, width, height });
69
+ r.seek(end);
70
+ }
71
+ }
72
+
73
+ /** Decodes the pixels. Each call decodes again. */
74
+ async decode(): Promise<RGBAImage> {
75
+ const planes = this.#planes;
76
+ const depth = planes[0]?.depth;
77
+ if (depth === undefined) throw new Error(`Pattern '${this.name}' has no pixel data`);
78
+ for (const p of planes) {
79
+ if (p.depth !== depth || p.width !== this.width || p.height !== this.height) {
80
+ throw new Error(`Pattern '${this.name}' has channels of different sizes or depths`);
81
+ }
82
+ }
83
+ const header: Header = {
84
+ version: 1,
85
+ isBig: false, // RLE row lengths are 2 bytes even in PSB files
86
+ channels: planes.filter((p) => p.id >= 0).length,
87
+ width: this.width,
88
+ height: this.height,
89
+ depth,
90
+ mode: this.mode,
91
+ modeName: MODES[this.mode] ?? 'Unknown',
92
+ colorModeData: this.#colorTable,
93
+ };
94
+ return decodePlanes(this.#reader, header, planes);
95
+ }
96
+
97
+ async toPng(): Promise<Uint8Array> {
98
+ return encodePng(await this.decode());
99
+ }
100
+ }
101
+
102
+ /** Reads the patterns in a `Patt`, `Pat2` or `Pat3` block. */
103
+ export function readPatterns(r: Reader, end: number): Pattern[] {
104
+ const patterns: Pattern[] = [];
105
+ // Each pattern is a length-prefixed record padded to 4 bytes.
106
+ while (r.pos + 4 <= end) {
107
+ const length = r.uint32();
108
+ if (r.pos + length > end) throw new Error(`Pattern of ${length} bytes overruns its block`);
109
+ patterns.push(new Pattern(r.at(r.pos)));
110
+ r.skip((length + 3) & ~3);
111
+ }
112
+ return patterns;
113
+ }
package/src/png.ts CHANGED
@@ -54,11 +54,29 @@ function chunk(type: string, data: Uint8Array[]): Uint8Array[] {
54
54
  return [head, ...data, crc];
55
55
  }
56
56
 
57
- /** Encodes 8-bit grayscale or RGBA pixels as a PNG file. */
58
- export async function encodePng({ width, height, data }: Pixels): Promise<Uint8Array> {
57
+ export interface PngOptions {
58
+ /**
59
+ * An ICC profile to embed, such as `psd.resources.iccProfile`. Its color space must match the
60
+ * pixels: RGB for RGBA pixels and grayscale for grayscale pixels.
61
+ */
62
+ iccProfile?: Uint8Array;
63
+ }
64
+
65
+ /** The color space signature of an ICC profile, such as `'RGB '`, `'GRAY'` or `'CMYK'`. */
66
+ export const iccColorSpace = (profile: Uint8Array) => String.fromCharCode(...profile.subarray(16, 20));
67
+
68
+ /** The iCCP chunk's profile name, its NUL terminator and compression method 0 (zlib). */
69
+ const ICCP_NAME = new TextEncoder().encode('ICC profile\0\0');
70
+
71
+ /** Encodes 8-bit grayscale or RGBA pixels as a PNG file, optionally with an ICC profile. */
72
+ export async function encodePng({ width, height, data }: Pixels, { iccProfile }: PngOptions = {}): Promise<Uint8Array> {
59
73
  if (width === 0 || height === 0) throw new Error('Cannot encode an empty image as PNG');
60
74
  const channels = data.length / (width * height);
61
75
  if (channels !== 1 && channels !== 4) throw new Error(`Expected 1 or 4 bytes per pixel, got ${channels}`);
76
+ const space = iccProfile && iccColorSpace(iccProfile);
77
+ if (space !== undefined && space !== (channels === 4 ? 'RGB ' : 'GRAY')) {
78
+ throw new Error(`Cannot embed a '${space}' ICC profile in a ${channels === 4 ? 'RGBA' : 'grayscale'} PNG`);
79
+ }
62
80
 
63
81
  const header = new Uint8Array(13);
64
82
  const view = new DataView(header.buffer);
@@ -86,6 +104,7 @@ export async function encodePng({ width, height, data }: Pixels): Promise<Uint8A
86
104
  return concat([
87
105
  new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]),
88
106
  ...chunk('IHDR', [header]),
107
+ ...(iccProfile ? chunk('iCCP', [ICCP_NAME, ...(await transform([iccProfile], new CompressionStream('deflate')))]) : []),
89
108
  ...chunk('IDAT', await transform(rows(), new CompressionStream('deflate'))),
90
109
  ...chunk('IEND', []),
91
110
  ]);
package/src/psd.ts CHANGED
@@ -1,10 +1,12 @@
1
1
  import { CompositeImage } from './image.ts';
2
2
  import { readLayerSection, type GlobalMask, type Layer, type LayerSection } from './layer.ts';
3
+ import { readLinkedFiles, type LinkedFile } from './linked-files.ts';
3
4
  import { RootNode } from './nodes.ts';
5
+ import { readPatterns, type Pattern } from './patterns.ts';
4
6
  import { Reader } from './reader.ts';
5
7
  import { Resources } from './resources.ts';
6
8
 
7
- const MODES = [
9
+ export const MODES = [
8
10
  'Bitmap',
9
11
  'GrayScale',
10
12
  'IndexedColor',
@@ -75,6 +77,8 @@ export class PSD {
75
77
  #layerSection: LayerSection | undefined;
76
78
  #image: CompositeImage | undefined;
77
79
  #tree: RootNode | undefined;
80
+ #patterns: Pattern[] | undefined;
81
+ #linkedFiles: LinkedFile[] | undefined;
78
82
 
79
83
  constructor(data: ArrayBuffer | ArrayBufferView) {
80
84
  const bytes = ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
@@ -121,6 +125,26 @@ export class PSD {
121
125
  return this.#layers.globalMask;
122
126
  }
123
127
 
128
+ /**
129
+ * The patterns used by pattern fills, overlays and strokes, which refer to them by `id`.
130
+ * Pixels are decoded on demand with `pattern.decode()`.
131
+ */
132
+ get patterns(): Pattern[] {
133
+ return (this.#patterns ??= this.#layers.infoBlocks
134
+ .filter((b) => ['Patt', 'Pat2', 'Pat3'].includes(b.key))
135
+ .flatMap((b) => readPatterns(this.#reader.at(b.offset), b.offset + b.length)));
136
+ }
137
+
138
+ /**
139
+ * Files placed as smart objects, embedded or linked. A smart object layer's file is
140
+ * `node.linkedFile`. File contents aren't copied out of the document.
141
+ */
142
+ get linkedFiles(): LinkedFile[] {
143
+ return (this.#linkedFiles ??= this.#layers.infoBlocks
144
+ .filter((b) => ['lnk2', 'lnk3', 'lnkD', 'lnkE'].includes(b.key))
145
+ .flatMap((b) => readLinkedFiles(this.#reader.at(b.offset), b.offset + b.length)));
146
+ }
147
+
124
148
  /** The flattened composite image. */
125
149
  get image(): CompositeImage {
126
150
  return (this.#image ??= new CompositeImage(this.#reader.at(this.#imageOffset), this.header, () => this.resources));
package/src/resources.ts CHANGED
@@ -203,6 +203,26 @@ export class Resources {
203
203
  return this.#parse(1047, (r) => r.uint16());
204
204
  }
205
205
 
206
+ /** Resource 1039: the document's ICC color profile. */
207
+ get iccProfile(): Uint8Array | undefined {
208
+ return this.#parse(1039, (r, block) => {
209
+ // The block is padded to an even length; the profile header has the exact size.
210
+ const size = r.view.getUint32(r.pos);
211
+ if (size < 128 || size > block.size) throw new Error(`Invalid ICC profile size ${size} in a ${block.size} byte resource`);
212
+ return r.bytesView(size);
213
+ });
214
+ }
215
+
216
+ /** Resource 1037: the global light angle in degrees, used by layer styles with `useGlobalLight`. */
217
+ get globalAngle(): number | undefined {
218
+ return this.#parse(1037, (r) => r.int32());
219
+ }
220
+
221
+ /** Resource 1049: the global light altitude in degrees, used by bevels with `useGlobalLight`. */
222
+ get globalAltitude(): number | undefined {
223
+ return this.#parse(1049, (r) => r.int32());
224
+ }
225
+
206
226
  /** Resource 1026: the group ID of each layer, ordered top to bottom like `psd.layers`. */
207
227
  get layerGroups(): number[] | undefined {
208
228
  return this.#parse(1026, (r, block) => Array.from({ length: block.size / 2 }, () => r.uint16()).reverse());
package/src/shapes.ts ADDED
@@ -0,0 +1,156 @@
1
+ import type { Descriptor, UnitValue } from './descriptor.ts';
2
+ import type { BlendMode } from './layer.ts';
3
+ import { blendMode, descriptorColor, enumValue, gradient, pattern, percent, type Gradient, type RGB } from './layer-styles.ts';
4
+ import type { Bounds } from './resources.ts';
5
+
6
+ /** A shape's fill or stroke content. One of these is set, depending on its type. */
7
+ export interface ShapeContent {
8
+ /** Undefined for colors that can't be converted, such as book colors. */
9
+ color: RGB | undefined;
10
+ gradient: Gradient | undefined;
11
+ pattern: { name: string; id: string } | undefined;
12
+ }
13
+
14
+ /** The live shape properties Photoshop keeps for each shape tool shape in a layer. */
15
+ export interface VectorShape {
16
+ /** Undefined if the shape was edited into a plain path, or for shape types this library doesn't know. */
17
+ type: 'rectangle' | 'roundedRectangle' | 'line' | 'ellipse' | undefined;
18
+ /** The shape was edited with the path tools, so it only has `index` and `data`. */
19
+ invalidated: boolean;
20
+ /** The shape's path component in the vector mask (`info.vectorMask`). */
21
+ index: number;
22
+ /**
23
+ * The shape's bounds in pixels, as shown in Photoshop's Properties panel. The layer's bounds are
24
+ * larger: they're whole pixels, and include antialiasing and the stroke.
25
+ */
26
+ bounds: Bounds | undefined;
27
+ /** Rounded rectangle corner radii, in pixels. */
28
+ radii: { topLeft: number; topRight: number; bottomRight: number; bottomLeft: number } | undefined;
29
+ /** Line endpoints in pixels, and the line's weight. */
30
+ line: { start: { x: number; y: number }; end: { x: number; y: number }; weight: number } | undefined;
31
+ /** The raw descriptor, for anything not covered above (rotated corners, arrowheads...). */
32
+ data: Descriptor;
33
+ }
34
+
35
+ /** A shape layer's stroke settings, and whether its fill and stroke are shown. */
36
+ export interface VectorStroke extends ShapeContent {
37
+ /** Whether the stroke is shown. */
38
+ enabled: boolean;
39
+ /**
40
+ * Whether the fill is shown. The fill's content is in `vectorStrokeContent`, or `solidColor`,
41
+ * `gradientFill` or `patternFill` for older shapes.
42
+ */
43
+ fillEnabled: boolean;
44
+ /** In pixels. */
45
+ width: number;
46
+ alignment: 'inside' | 'center' | 'outside' | undefined;
47
+ cap: 'butt' | 'round' | 'square' | undefined;
48
+ join: 'miter' | 'round' | 'bevel' | undefined;
49
+ miterLimit: number;
50
+ /** Alternating dash and gap lengths, as multiples of the width. Empty for a solid line. */
51
+ dashes: number[];
52
+ /** In pixels. */
53
+ dashOffset: number;
54
+ /** 0 to 1. */
55
+ opacity: number;
56
+ blendMode: BlendMode | string | undefined;
57
+ /** The raw descriptor, for anything not covered above. */
58
+ data: Descriptor;
59
+ }
60
+
61
+ /** The live shape properties Photoshop keeps for a shape layer (`vogk`). */
62
+ export interface VectorOrigination {
63
+ /** One entry per shape tool shape in the layer. */
64
+ shapes: VectorShape[];
65
+ /** The raw descriptor, for anything not covered above. */
66
+ data: Descriptor;
67
+ }
68
+
69
+ /** A newer shape layer's fill (`vscg`). */
70
+ export interface VectorFill extends ShapeContent {
71
+ /** The raw descriptor, for anything not covered above. */
72
+ data: Descriptor;
73
+ }
74
+
75
+ const SHAPE_TYPES = { 1: 'rectangle', 2: 'roundedRectangle', 4: 'line', 5: 'ellipse' } as const;
76
+ const ALIGNMENTS = { strokeStyleAlignInside: 'inside', strokeStyleAlignCenter: 'center', strokeStyleAlignOutside: 'outside' } as const;
77
+ const CAPS = { strokeStyleButtCap: 'butt', strokeStyleRoundCap: 'round', strokeStyleSquareCap: 'square' } as const;
78
+ const JOINS = { strokeStyleMiterJoin: 'miter', strokeStyleRoundJoin: 'round', strokeStyleBevelJoin: 'bevel' } as const;
79
+
80
+ const lookup = <T extends Record<string, string>>(table: T, v: unknown): T[keyof T] | undefined =>
81
+ table[enumValue(v) as keyof T];
82
+
83
+ /** Converts a unit value to pixels at the given resolution (pixels per inch). */
84
+ function pixels(v: UnitValue, resolution: number): number {
85
+ switch (v.id) {
86
+ case '#Pxl':
87
+ return v.value;
88
+ case '#Pnt':
89
+ return (v.value * resolution) / 72;
90
+ case '#Mlm':
91
+ return (v.value * resolution) / 25.4;
92
+ default:
93
+ throw new Error(`Unsupported shape unit '${v.id}'`);
94
+ }
95
+ }
96
+
97
+ export const shapeContent = (d: Descriptor | undefined): ShapeContent => ({
98
+ color: descriptorColor(d?.['Clr ']),
99
+ gradient: gradient(d?.Grad),
100
+ pattern: pattern(d?.Ptrn),
101
+ });
102
+
103
+ function vectorShape(d: Descriptor): VectorShape {
104
+ const res: number = d.keyOriginResolution;
105
+ const px = (v: UnitValue) => pixels(v, res);
106
+ const box = d.keyOriginShapeBBox;
107
+ const radii = d.keyOriginRRectRadii;
108
+ const point = (p: Descriptor) => ({ x: p.Hrzn as number, y: p.Vrtc as number });
109
+ return {
110
+ type: SHAPE_TYPES[d.keyOriginType as keyof typeof SHAPE_TYPES],
111
+ invalidated: d.keyShapeInvalidated ?? false,
112
+ index: d.keyOriginIndex,
113
+ bounds: box && { top: px(box['Top ']), left: px(box.Left), bottom: px(box.Btom), right: px(box.Rght) },
114
+ radii: radii && {
115
+ topLeft: px(radii.topLeft),
116
+ topRight: px(radii.topRight),
117
+ bottomRight: px(radii.bottomRight),
118
+ bottomLeft: px(radii.bottomLeft),
119
+ },
120
+ line: d.keyOriginLineStart && {
121
+ start: point(d.keyOriginLineStart),
122
+ end: point(d.keyOriginLineEnd),
123
+ weight: d.keyOriginLineWeight,
124
+ },
125
+ data: d,
126
+ };
127
+ }
128
+
129
+ /** Normalizes the vector origination (`vogk`) descriptor. */
130
+ export const readVectorOrigination = (d: Descriptor): VectorOrigination => ({
131
+ shapes: (d.keyDescriptorList ?? []).map(vectorShape),
132
+ data: d,
133
+ });
134
+
135
+ /** Normalizes the vector fill (`vscg`) descriptor. */
136
+ export const readVectorFill = (d: Descriptor): VectorFill => ({ ...shapeContent(d), data: d });
137
+
138
+ /** Normalizes the vector stroke (`vstk`) descriptor. */
139
+ export function readVectorStroke(d: Descriptor): VectorStroke {
140
+ const res: number = d.strokeStyleResolution;
141
+ return {
142
+ ...shapeContent(d.strokeStyleContent),
143
+ enabled: d.strokeEnabled,
144
+ fillEnabled: d.fillEnabled,
145
+ width: pixels(d.strokeStyleLineWidth, res),
146
+ alignment: lookup(ALIGNMENTS, d.strokeStyleLineAlignment),
147
+ cap: lookup(CAPS, d.strokeStyleLineCapType),
148
+ join: lookup(JOINS, d.strokeStyleLineJoinType),
149
+ miterLimit: d.strokeStyleMiterLimit,
150
+ dashes: d.strokeStyleLineDashSet.map((v: UnitValue) => v.value),
151
+ dashOffset: pixels(d.strokeStyleLineDashOffset, res),
152
+ opacity: percent(d.strokeStyleOpacity),
153
+ blendMode: blendMode(d.strokeStyleBlendMode),
154
+ data: d,
155
+ };
156
+ }
package/src/type-tool.ts CHANGED
@@ -26,8 +26,32 @@ export interface TextRun {
26
26
  fauxItalic: boolean;
27
27
  underline: boolean;
28
28
  strikethrough: boolean;
29
+ /** Tracking (letter spacing) in 1/1000 em, as in the Character panel. Multiply by `size / 1000` for pixels. */
30
+ tracking: number;
31
+ /**
32
+ * `'auto'` when the font's kerning is used (Metrics in the Character panel), otherwise manual kerning
33
+ * in 1/1000 em. Photoshop often stores the first character as its own run with a kerning of 0.
34
+ */
35
+ kerning: number | 'auto';
36
+ /** Baseline shift in pixels before `transform` scales the text, like `size`. Positive values raise the text. */
37
+ baselineShift: number;
38
+ /** Small Caps or All Caps from the Character panel. `text` keeps the case it was typed in. */
39
+ caps: TextCaps;
40
+ /** Superscript or subscript from the Character panel. */
41
+ baseline: TextBaseline;
29
42
  }
30
43
 
44
+ const CAPS = ['normal', 'small-caps', 'all-caps'] as const;
45
+ export type TextCaps = (typeof CAPS)[number];
46
+ const BASELINES = ['normal', 'superscript', 'subscript'] as const;
47
+ export type TextBaseline = (typeof BASELINES)[number];
48
+
49
+ const lookup = <T>(values: readonly T[], key: string, index: number): T => {
50
+ const value = values[index];
51
+ if (value === undefined) throw new Error(`Unknown ${key} value: ${index}`);
52
+ return value;
53
+ };
54
+
31
55
  const ALIGNMENTS = ['left', 'right', 'center', 'justify'] as const;
32
56
  export type TextAlignment = (typeof ALIGNMENTS)[number];
33
57
 
@@ -70,8 +94,8 @@ export class TypeTool {
70
94
  /**
71
95
  * The left edge of the text's frame, in pixels relative to the transform origin (`tx`, `ty`) and
72
96
  * before the transform. The frame spans the lines around the anchor point for point text, or the box
73
- * for paragraph text (its top can reach above the box to fit the first line). Undefined in files
74
- * from older Photoshop versions.
97
+ * for paragraph text (it can reach beyond the box to fit the first line; see `boxBounds`).
98
+ * Undefined in files from older Photoshop versions.
75
99
  */
76
100
  get left(): number | undefined {
77
101
  return this.textData.bounds?.Left.value;
@@ -95,6 +119,19 @@ export class TypeTool {
95
119
  return box && { left: box.Left.value, top: box['Top '].value, right: box.Rght.value, bottom: box.Btom.value };
96
120
  }
97
121
 
122
+ /**
123
+ * The box of paragraph (box) text, exactly as Photoshop draws it, relative to the transform origin and
124
+ * before the transform like `left`/`top`/`right`/`bottom`. Undefined for text without a box, such as
125
+ * point text. Unlike the frame, it doesn't grow to fit the first line, and older Photoshop versions
126
+ * store it too.
127
+ */
128
+ get boxBounds(): Bounds | undefined {
129
+ const shape = this.engineData.EngineDict.Rendered.Shapes.Children[0].Cookie.Photoshop;
130
+ if (shape.ShapeType !== 1) return undefined;
131
+ const [left, top, right, bottom] = shape.BoxBounds;
132
+ return { left, top, right, bottom };
133
+ }
134
+
98
135
  /**
99
136
  * The text content. Paragraphs are separated by `\r`, and line breaks within a paragraph
100
137
  * (Shift+Enter) are `\u0003`; neither displays as a new line in HTML or a terminal.
@@ -138,6 +175,11 @@ export class TypeTool {
138
175
  fauxItalic: s.FauxItalic ?? false,
139
176
  underline: s.Underline ?? false,
140
177
  strikethrough: s.Strikethrough ?? false,
178
+ tracking: s.Tracking ?? 0,
179
+ kerning: s.AutoKerning === false ? (s.Kerning ?? 0) : 'auto',
180
+ baselineShift: s.BaselineShift ?? 0,
181
+ caps: lookup(CAPS, 'FontCaps', s.FontCaps ?? 0),
182
+ baseline: lookup(BASELINES, 'FontBaseline', s.FontBaseline ?? 0),
141
183
  };
142
184
  });
143
185
  }
@@ -212,6 +254,7 @@ export class TypeTool {
212
254
  right: this.right,
213
255
  bottom: this.bottom,
214
256
  boundingBox: this.boundingBox,
257
+ boxBounds: this.boxBounds,
215
258
  transform: this.transform,
216
259
  };
217
260
  }