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

Refactor Textarea autosize prop to handle when a single line takes up multiple rows #4061

Closed
wants to merge 3 commits into from

Conversation

speedpro
Copy link
Contributor

@speedpro speedpro commented Dec 3, 2023

Description

When using autosize, the previous calculation for rows was based on finding new line characters "\n" in the textbox value. This meant the height didn't adjust when a single line wrapped around to a new line.

This changes the computation to use lineHeight and scrollHeight to determine the number of visible rows for the textbox regardless of new line characters. It still respects min-rows and max-rows props when provided.

Markup:

...
    //removed computedRowsCount

    const textareaHeight = ref('auto')

    const updateTextareaHeight = () => {
      if (!textarea.value) {
        return false
      }

      textarea.value.style.height = '0'

      const totalHeight = textarea.value?.scrollHeight

      const lineHeight = parseInt(
        window.getComputedStyle(textarea.value)?.lineHeight,
        10,
      )
      let rows = totalHeight / lineHeight

      if (props.maxRows) {
        rows = Math.max(props.minRows, Math.min(rows, props.maxRows))
      }

      if (props.minRows) {
        rows = Math.max(props.minRows, rows)
      }

      const height = rows * lineHeight + 'px'

      textareaHeight.value = '' + height
    }

    watch([valueComputed, textarea], updateTextareaHeight, { immediate: true })

Types of changes

  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Improvement/refactoring (non-breaking change that doesn't add any feature but make things better)

@speedpro speedpro marked this pull request as ready for review December 3, 2023 21:24
@speedpro speedpro marked this pull request as draft December 3, 2023 23:14
@speedpro speedpro closed this Jan 25, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant