VTextarea.mjs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. import { vModelText as _vModelText, withDirectives as _withDirectives, mergeProps as _mergeProps, resolveDirective as _resolveDirective, createVNode as _createVNode, Fragment as _Fragment } from "vue";
  2. // Styles
  3. import "./VTextarea.css";
  4. import "../VTextField/VTextField.css";
  5. // Components
  6. import { VCounter } from "../VCounter/VCounter.mjs";
  7. import { VField } from "../VField/index.mjs";
  8. import { filterFieldProps, makeVFieldProps } from "../VField/VField.mjs";
  9. import { makeVInputProps, VInput } from "../VInput/VInput.mjs"; // Composables
  10. import { useFocus } from "../../composables/focus.mjs";
  11. import { forwardRefs } from "../../composables/forwardRefs.mjs";
  12. import { useProxiedModel } from "../../composables/proxiedModel.mjs"; // Directives
  13. import Intersect from "../../directives/intersect/index.mjs"; // Utilities
  14. import { computed, nextTick, onBeforeUnmount, onMounted, ref, shallowRef, watch, watchEffect } from 'vue';
  15. import { callEvent, clamp, convertToUnit, filterInputAttrs, genericComponent, propsFactory, useRender } from "../../util/index.mjs"; // Types
  16. export const makeVTextareaProps = propsFactory({
  17. autoGrow: Boolean,
  18. autofocus: Boolean,
  19. counter: [Boolean, Number, String],
  20. counterValue: Function,
  21. prefix: String,
  22. placeholder: String,
  23. persistentPlaceholder: Boolean,
  24. persistentCounter: Boolean,
  25. noResize: Boolean,
  26. rows: {
  27. type: [Number, String],
  28. default: 5,
  29. validator: v => !isNaN(parseFloat(v))
  30. },
  31. maxRows: {
  32. type: [Number, String],
  33. validator: v => !isNaN(parseFloat(v))
  34. },
  35. suffix: String,
  36. modelModifiers: Object,
  37. ...makeVInputProps(),
  38. ...makeVFieldProps()
  39. }, 'VTextarea');
  40. export const VTextarea = genericComponent()({
  41. name: 'VTextarea',
  42. directives: {
  43. Intersect
  44. },
  45. inheritAttrs: false,
  46. props: makeVTextareaProps(),
  47. emits: {
  48. 'click:control': e => true,
  49. 'mousedown:control': e => true,
  50. 'update:focused': focused => true,
  51. 'update:modelValue': val => true
  52. },
  53. setup(props, _ref) {
  54. let {
  55. attrs,
  56. emit,
  57. slots
  58. } = _ref;
  59. const model = useProxiedModel(props, 'modelValue');
  60. const {
  61. isFocused,
  62. focus,
  63. blur
  64. } = useFocus(props);
  65. const counterValue = computed(() => {
  66. return typeof props.counterValue === 'function' ? props.counterValue(model.value) : (model.value || '').toString().length;
  67. });
  68. const max = computed(() => {
  69. if (attrs.maxlength) return attrs.maxlength;
  70. if (!props.counter || typeof props.counter !== 'number' && typeof props.counter !== 'string') return undefined;
  71. return props.counter;
  72. });
  73. function onIntersect(isIntersecting, entries) {
  74. if (!props.autofocus || !isIntersecting) return;
  75. entries[0].target?.focus?.();
  76. }
  77. const vInputRef = ref();
  78. const vFieldRef = ref();
  79. const controlHeight = shallowRef('');
  80. const textareaRef = ref();
  81. const isActive = computed(() => props.persistentPlaceholder || isFocused.value || props.active);
  82. function onFocus() {
  83. if (textareaRef.value !== document.activeElement) {
  84. textareaRef.value?.focus();
  85. }
  86. if (!isFocused.value) focus();
  87. }
  88. function onControlClick(e) {
  89. onFocus();
  90. emit('click:control', e);
  91. }
  92. function onControlMousedown(e) {
  93. emit('mousedown:control', e);
  94. }
  95. function onClear(e) {
  96. e.stopPropagation();
  97. onFocus();
  98. nextTick(() => {
  99. model.value = '';
  100. callEvent(props['onClick:clear'], e);
  101. });
  102. }
  103. function onInput(e) {
  104. const el = e.target;
  105. model.value = el.value;
  106. if (props.modelModifiers?.trim) {
  107. const caretPosition = [el.selectionStart, el.selectionEnd];
  108. nextTick(() => {
  109. el.selectionStart = caretPosition[0];
  110. el.selectionEnd = caretPosition[1];
  111. });
  112. }
  113. }
  114. const sizerRef = ref();
  115. const rows = ref(+props.rows);
  116. const isPlainOrUnderlined = computed(() => ['plain', 'underlined'].includes(props.variant));
  117. watchEffect(() => {
  118. if (!props.autoGrow) rows.value = +props.rows;
  119. });
  120. function calculateInputHeight() {
  121. if (!props.autoGrow) return;
  122. nextTick(() => {
  123. if (!sizerRef.value || !vFieldRef.value) return;
  124. const style = getComputedStyle(sizerRef.value);
  125. const fieldStyle = getComputedStyle(vFieldRef.value.$el);
  126. const padding = parseFloat(style.getPropertyValue('--v-field-padding-top')) + parseFloat(style.getPropertyValue('--v-input-padding-top')) + parseFloat(style.getPropertyValue('--v-field-padding-bottom'));
  127. const height = sizerRef.value.scrollHeight;
  128. const lineHeight = parseFloat(style.lineHeight);
  129. const minHeight = Math.max(parseFloat(props.rows) * lineHeight + padding, parseFloat(fieldStyle.getPropertyValue('--v-input-control-height')));
  130. const maxHeight = parseFloat(props.maxRows) * lineHeight + padding || Infinity;
  131. const newHeight = clamp(height ?? 0, minHeight, maxHeight);
  132. rows.value = Math.floor((newHeight - padding) / lineHeight);
  133. controlHeight.value = convertToUnit(newHeight);
  134. });
  135. }
  136. onMounted(calculateInputHeight);
  137. watch(model, calculateInputHeight);
  138. watch(() => props.rows, calculateInputHeight);
  139. watch(() => props.maxRows, calculateInputHeight);
  140. watch(() => props.density, calculateInputHeight);
  141. let observer;
  142. watch(sizerRef, val => {
  143. if (val) {
  144. observer = new ResizeObserver(calculateInputHeight);
  145. observer.observe(sizerRef.value);
  146. } else {
  147. observer?.disconnect();
  148. }
  149. });
  150. onBeforeUnmount(() => {
  151. observer?.disconnect();
  152. });
  153. useRender(() => {
  154. const hasCounter = !!(slots.counter || props.counter || props.counterValue);
  155. const hasDetails = !!(hasCounter || slots.details);
  156. const [rootAttrs, inputAttrs] = filterInputAttrs(attrs);
  157. const {
  158. modelValue: _,
  159. ...inputProps
  160. } = VInput.filterProps(props);
  161. const fieldProps = filterFieldProps(props);
  162. return _createVNode(VInput, _mergeProps({
  163. "ref": vInputRef,
  164. "modelValue": model.value,
  165. "onUpdate:modelValue": $event => model.value = $event,
  166. "class": ['v-textarea v-text-field', {
  167. 'v-textarea--prefixed': props.prefix,
  168. 'v-textarea--suffixed': props.suffix,
  169. 'v-text-field--prefixed': props.prefix,
  170. 'v-text-field--suffixed': props.suffix,
  171. 'v-textarea--auto-grow': props.autoGrow,
  172. 'v-textarea--no-resize': props.noResize || props.autoGrow,
  173. 'v-input--plain-underlined': isPlainOrUnderlined.value
  174. }, props.class],
  175. "style": props.style
  176. }, rootAttrs, inputProps, {
  177. "centerAffix": rows.value === 1 && !isPlainOrUnderlined.value,
  178. "focused": isFocused.value
  179. }), {
  180. ...slots,
  181. default: _ref2 => {
  182. let {
  183. id,
  184. isDisabled,
  185. isDirty,
  186. isReadonly,
  187. isValid
  188. } = _ref2;
  189. return _createVNode(VField, _mergeProps({
  190. "ref": vFieldRef,
  191. "style": {
  192. '--v-textarea-control-height': controlHeight.value
  193. },
  194. "onClick": onControlClick,
  195. "onMousedown": onControlMousedown,
  196. "onClick:clear": onClear,
  197. "onClick:prependInner": props['onClick:prependInner'],
  198. "onClick:appendInner": props['onClick:appendInner']
  199. }, fieldProps, {
  200. "id": id.value,
  201. "active": isActive.value || isDirty.value,
  202. "centerAffix": rows.value === 1 && !isPlainOrUnderlined.value,
  203. "dirty": isDirty.value || props.dirty,
  204. "disabled": isDisabled.value,
  205. "focused": isFocused.value,
  206. "error": isValid.value === false
  207. }), {
  208. ...slots,
  209. default: _ref3 => {
  210. let {
  211. props: {
  212. class: fieldClass,
  213. ...slotProps
  214. }
  215. } = _ref3;
  216. return _createVNode(_Fragment, null, [props.prefix && _createVNode("span", {
  217. "class": "v-text-field__prefix"
  218. }, [props.prefix]), _withDirectives(_createVNode("textarea", _mergeProps({
  219. "ref": textareaRef,
  220. "class": fieldClass,
  221. "value": model.value,
  222. "onInput": onInput,
  223. "autofocus": props.autofocus,
  224. "readonly": isReadonly.value,
  225. "disabled": isDisabled.value,
  226. "placeholder": props.placeholder,
  227. "rows": props.rows,
  228. "name": props.name,
  229. "onFocus": onFocus,
  230. "onBlur": blur
  231. }, slotProps, inputAttrs), null), [[_resolveDirective("intersect"), {
  232. handler: onIntersect
  233. }, null, {
  234. once: true
  235. }]]), props.autoGrow && _withDirectives(_createVNode("textarea", {
  236. "class": [fieldClass, 'v-textarea__sizer'],
  237. "id": `${slotProps.id}-sizer`,
  238. "onUpdate:modelValue": $event => model.value = $event,
  239. "ref": sizerRef,
  240. "readonly": true,
  241. "aria-hidden": "true"
  242. }, null), [[_vModelText, model.value]]), props.suffix && _createVNode("span", {
  243. "class": "v-text-field__suffix"
  244. }, [props.suffix])]);
  245. }
  246. });
  247. },
  248. details: hasDetails ? slotProps => _createVNode(_Fragment, null, [slots.details?.(slotProps), hasCounter && _createVNode(_Fragment, null, [_createVNode("span", null, null), _createVNode(VCounter, {
  249. "active": props.persistentCounter || isFocused.value,
  250. "value": counterValue.value,
  251. "max": max.value,
  252. "disabled": props.disabled
  253. }, slots.counter)])]) : undefined
  254. });
  255. });
  256. return forwardRefs({}, vInputRef, vFieldRef, textareaRef);
  257. }
  258. });
  259. //# sourceMappingURL=VTextarea.mjs.map