Skip to content

Commit

Permalink
πŸ› Fix TypeError for color on nested blocks
Browse files Browse the repository at this point in the history
Reading a `color` property on a row or column block with a nested text
block lead to a TypeError:

> TypeError: Invalid value for "definition/content/0/rows/0/color":
> Expected valid color, got: {type: 'RGB', red: 0, green: 0.3, blue:
> 0.5}

This happened because the `readColor()` function transforms the input
and did not accept its own result type as input. For nested blocks, the
inherited `color` property is parsed twice if not overwritten.

As a quick fix, this commit changes the `readColor()` function to accept
its own result type, i.e. an object with type `RGB`.

Fixes #95
  • Loading branch information
ralfstx committed Dec 16, 2024
1 parent 87ef775 commit 07fe0c3
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
5 changes: 5 additions & 0 deletions src/read-colors.test.ts β†’ src/read-color.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ describe('readColor', () => {
expect(readColor('blue')).toEqual({ type: 'RGB', red: 0, green: 0, blue: 1 });
});

it('accepts its own output', () => {
// See https://github.com/eclipsesource/pdf-maker/issues/95
expect(readColor(readColor('red'))).toEqual({ type: 'RGB', red: 1, green: 0, blue: 0 });
});

it('throws on unsupported named color', () => {
expect(() => readColor('' as any)).toThrowError("Expected valid color name, got: ''");
expect(() => readColor('salmon' as any)).toThrowError(
Expand Down
5 changes: 4 additions & 1 deletion src/read-color.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import { type Color, rgb } from 'pdf-lib';

import { namedColors } from './api/colors.ts';
import { typeError } from './types.ts';
import { isObject, typeError } from './types.ts';

export { type Color };

export function readColor(input: unknown): Color {
if (isObject(input) && input.type === 'RGB') {
return input as unknown as Color;
}
if (typeof input === 'string') {
if (/^#[0-9a-f]{6}$/.test(input)) {
const r = parseInt(input.slice(1, 3), 16) / 255;
Expand Down

0 comments on commit 07fe0c3

Please sign in to comment.