Skip to content

wrap() is duplicated by every custom TextMeasurer #3

Description

@smnandre

Expected

Writing a measurer for a new font means saying how wide a glyph is. I wrote a monospace one for JetBrains Mono and expected a single method.

Actual

The interface asks for two, and wrap() is about fifty lines of greedy word wrapping that only ever calls measureLine(). Nothing in it is font-specific, so each implementation copies it.

final readonly class MonospaceMeasurer implements TextMeasurerInterface
{
    public function measureLine(...): TextMetrics { /* 5 lines, the real work */ }
    public function wrap(...): TextBlockMetrics  { /* 40 lines, copied */ }
}

CharWidthTextMeasurer is final, so overriding just measureLine() on it is closed too.

Suggestion

Move wrap() into a trait so an implementation writes only measureLine():

trait WrapsText
{
    public function wrap(...): TextBlockMetrics { /* the current body */ }
}

One detail to carry over: the body reads $this->ascentFactor for the baseline, which a trait cannot see. $this->measureLine('', $fontSize, $weight)->ascent gives the same value from the interface itself, since ascent does not depend on la string.

CharWidthTextMeasurer uses the trait, custom measurers use the trait, and the interface keeps both methods.

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions