Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix textbound invalid input #6302

Closed
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions src/typography/p5.Font.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,10 @@ p5.Font = class {
// Check cache for existing bounds. Take into consideration the text alignment
// settings. Default alignment should match opentype's origin: left-aligned &
// alphabetic baseline.
if (typeof str !== 'string') {
console.error('Error: Text parameter must be a string.');
return null;
}
Comment on lines +79 to +82
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't usually handle incorrect parameter types this way as the FES is usually the one to take care of it. In terms of logic it should either do type coersion or return sensible default values, null is probably not useful in this case and can cause a property access error on the user's end.

const p = (opts && opts.renderer && opts.renderer._pInst) || this.parent;

const ctx = p._renderer.drawingContext;
Expand Down
29 changes: 29 additions & 0 deletions test/unit/typography/p5.Font.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,35 @@ suite('p5.Font', function() {
assert.property(bbox, 'w');
assert.property(bbox, 'h');
});

test('returns null and logs an error when a number is passed instead of text', async function() {
const errorLog = await promisedSketch(function(sketch, resolve, reject){
let _font;
let invalidText = 10;
sketch.preload = function() {
_font = sketch.loadFont('path/to/valid/font.ttf', function() {}, reject);
};
sketch.setup = function() {
console.error = function(message) {
// Check if the error message contains the expected substring
if (message.includes('Error: Text parameter must be a string.')) {
resolve(true);
} else {
resolve(false);
}
};

let _bbox = _font.textBounds(invalidText, 0, 0, 12);
if (_bbox === null) {
resolve(false);
} else {
resolve(false);
}
};
});

assert.isTrue(errorLog, 'Error was logged for invalid text parameter');
});
});

suite('p5.Font.prototype.textToPoints', function() {
Expand Down