Skip to content

Commit

Permalink
feat(useTextareaAutosize): added styleTarget option to style other …
Browse files Browse the repository at this point in the history
…element (#2312)
  • Loading branch information
jd-solanki committed Mar 14, 2023
1 parent f285c12 commit a3e9547
Showing 1 changed file with 16 additions and 2 deletions.
18 changes: 16 additions & 2 deletions packages/core/useTextareaAutosize/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { MaybeRef } from '@vueuse/shared'
import type { WatchSource } from 'vue-demi'
import { ref, watch } from 'vue-demi'
import { ref, unref, watch } from 'vue-demi'
import { useResizeObserver } from '../useResizeObserver'

export interface UseTextareaAutosizeOptions {
Expand All @@ -12,18 +12,32 @@ export interface UseTextareaAutosizeOptions {
watch?: WatchSource | Array<WatchSource>
/** Function called when the textarea size changes. */
onResize?: () => void
/** Specify style target to apply the height based on textarea content. If not provided it will use textarea it self. */
styleTarget?: MaybeRef<HTMLElement>
}

export function useTextareaAutosize(options?: UseTextareaAutosizeOptions) {
const textarea = ref<HTMLTextAreaElement>(options?.element as any)
const input = ref<string>(options?.input as any)
const textareaScrollHeight = ref(1)

function triggerResize() {
if (!textarea.value)
return

let height = ''

textarea.value!.style.height = '1px'
textarea.value!.style.height = `${textarea.value?.scrollHeight}px`
textareaScrollHeight.value = textarea.value?.scrollHeight

// If style target is provided update its height
if (options?.styleTarget)
unref(options.styleTarget).style.height = `${textareaScrollHeight.value}px`
// else update textarea's height by updating height variable
else
height = `${textareaScrollHeight.value}px`

textarea.value!.style.height = height

options?.onResize?.()
}
Expand Down

0 comments on commit a3e9547

Please sign in to comment.