Scaling text to fit within Textbox when changing text value programmatically

I am using a Textbox in my canvas application to allow users to edit text. This is working fantastically for me, as I want text to wrap during editing, and wrap/unwrap as the width of the box is shrunken and expanded.

However, I have a secondary use case that I need some guidance on.

Occasionally, I need to replace the text in the textbox programmatically. In this scenario, I do not want the textbox to wrap text or expand when the text is too long for the width. Instead, I would like to reduce the fontSize so that the text fits on one line.

Note: I only do this text replacement once when the canvas is loaded (or just before in the JSON).

I currently handle this with IText using the following code, but I cannot seem to modify it in a way that works reliably with Textbox. I also lose out on the fantastic text wrapping if I use IText, which is why I’m evaluating this.

const handleTextChanged = ({ target }: { target: fabric.Object }) => {
  const { fixedWidth, width, fontSize } = target

  if (width > fixedWidth) {
    // Shrink the font size to stay within the max width
    target.fontSize = Math.round((fontSize * fixedWidth) / (width + 1))
  }

  target.width = fixedWidth
}

Is there a way to achieve something like this using just Textbox? That is, I would like to keep text wrapping and unwrapping functionality during normal editing, but I would also like to load text in programmatically and have the font size scale to fit the box when I load the canvas.