-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathKInput.vue
More file actions
476 lines (396 loc) · 12.7 KB
/
KInput.vue
File metadata and controls
476 lines (396 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
<template>
<div
class="k-input"
:class="[$attrs.class, { 'input-error' : charLimitExceeded || error || hasError }]"
>
<KLabel
v-if="label"
:for="inputId"
v-bind="labelAttributes"
:required="isRequired"
>
{{ strippedLabel }}
<template
v-if="hasLabelTooltip"
#tooltip
>
<slot name="label-tooltip" />
</template>
</KLabel>
<div
class="input-element-wrapper"
:class="{ 'has-before-content': $slots.before, 'has-after-content': $slots.after || (type === 'password' && showPasswordMaskToggle) }"
>
<div
v-if="$slots.before"
ref="beforeSlotElement"
class="before-content-wrapper"
>
<slot name="before" />
</div>
<input
:id="inputId"
ref="inputRef"
:aria-describedby="helpText ? helpTextId : undefined"
:aria-invalid="error || hasError || charLimitExceeded ? 'true' : undefined"
class="input"
:type="inputType"
v-bind="modifiedAttrs"
:value="getValue()"
@input="handleInput"
>
<div
v-if="$slots.after || (type === 'password' && showPasswordMaskToggle)"
ref="afterSlotElement"
class="after-content-wrapper"
>
<button
v-if="type === 'password' && showPasswordMaskToggle"
:aria-label="`${maskValue ? 'Hide' : 'Show'} value`"
class="mask-value-toggle-button"
type="button"
@click.stop="maskValue = !maskValue"
@mousedown.prevent
@mouseup.prevent
>
<VisibilityOffIcon
v-if="maskValue"
decorative
/>
<VisibilityIcon
v-else
decorative
/>
</button>
<slot
v-else
name="after"
/>
</div>
</div>
<Transition
mode="out-in"
name="kongponents-fade-transition"
>
<p
v-if="helpText"
:id="helpTextId"
:key="String(helpTextKey)"
class="help-text"
>
{{ helpText }}
</p>
</Transition>
</div>
</template>
<script setup lang="ts">
import { computed, ref, watch, useSlots, useAttrs, onMounted, nextTick, useId, useTemplateRef } from 'vue'
import type { InputProps, InputEmits, InputSlots } from '@/types'
import useUtilities from '@/composables/useUtilities'
import KLabel from '@/components/KLabel/KLabel.vue'
import { KUI_ICON_SIZE_40 } from '@kong/design-tokens'
import { VisibilityIcon, VisibilityOffIcon } from '@kong/icons'
const {
modelValue = '',
label = '',
labelAttributes = {},
help = '',
error,
errorMessage = '',
characterLimit = null,
hasError,
type = 'text',
showPasswordMaskToggle,
} = defineProps<InputProps>()
watch(() => hasError, (val) => {
if (val) {
console.warn('KInput: `hasError` prop is deprecated. Please use `error` prop instead. See the migration guide for more details: https://kongponents.konghq.com/guide/migrating-to-version-9.html#kinput')
}
}, { immediate: true })
watch(() => labelAttributes.help, (help) => {
if (help) {
console.warn('KInput: `help` property of `labelAttributes` prop is deprecated. Please use `info` prop instead. See the migration guide for more details: https://kongponents.konghq.com/guide/migrating-to-version-9.html#klabel')
}
})
const emit = defineEmits<InputEmits>()
defineSlots<InputSlots>()
const currValue = ref<string>('') // We need this so that we don't lose the updated value on hover/blur event with label
const modelValueChanged = ref<boolean>(false) // Determine if the original value was modified by the user
const helpTextKey = ref<number>(0)
const { stripRequiredLabel } = useUtilities()
const slots = useSlots()
const attrs = useAttrs()
const isRequired = computed((): boolean => attrs?.required !== undefined && String(attrs?.required) !== 'false')
const defaultId = useId()
const inputId = computed((): string => attrs.id ? String(attrs.id) : defaultId)
const helpTextId = useId()
const strippedLabel = computed((): string => stripRequiredLabel(label, isRequired.value))
const hasLabelTooltip = computed((): boolean => !!(labelAttributes?.info || slots['label-tooltip']))
const input$ = useTemplateRef('inputRef')
// we need this so we can create a watcher for programmatic changes to the modelValue
const value = computed({
get(): string | number {
return modelValue
},
set(newValue: string | number): void {
// @ts-ignore: allow typing as Event
handleInput({ target: { value: newValue } } as Event)
},
})
const modifiedAttrs = computed((): Record<string, any> => {
const $attrs = { ...attrs }
// delete classes because we bind them to the parent
delete $attrs.class
// use @input in template for v-model support
delete $attrs.input
delete $attrs.onInput
return $attrs
})
const charLimitExceeded = computed((): boolean => {
const currValLength = currValue.value?.toString().length || 0
const modelValLength = modelValue?.toString().length || 0
// default to length of currVal
let length = currValLength
// if there is a model value and it hasn't been modified yet, use that instead
if (!modelValueChanged.value && modelValLength) {
length = modelValLength
}
return !!characterLimit && length > characterLimit
})
const charLimitExceededErrorMessage = computed((): string => {
if (!charLimitExceeded.value) {
return ''
}
return modelValueChanged.value
? `${currValue.value?.toString().length} / ${characterLimit}`
: `${modelValue?.toString().length} / ${characterLimit}`
})
const helpText = computed((): string => {
// if character limit exceeded, return that error message
if (charLimitExceeded.value) {
return charLimitExceededErrorMessage.value
}
// if error prop is true and there is an error message, return that
if ((error || hasError) && errorMessage) {
return errorMessage
}
// otherwise return the help text
// if error prop is true it danger styles will be applied
return help
})
watch(charLimitExceeded, (newVal, oldVal) => {
if (newVal !== oldVal) {
emit('char-limit-exceeded', {
value: currValue.value,
length: currValue.value.length,
characterLimit: characterLimit!,
limitExceeded: newVal,
})
// bump the key to trigger the transition
helpTextKey.value += 1
}
})
watch(value, (newVal, oldVal) => {
if (newVal !== oldVal) {
// @ts-ignore: allow typing as Event
handleInput({ target: { value: newVal } } as Event)
}
})
const handleInput = (event: Event): void => {
// avoid pass by ref
const value = JSON.parse(JSON.stringify((event?.target as HTMLInputElement)?.value))
updateInputValue(value)
}
const updateInputValue = (value: string): void => {
currValue.value = value
modelValueChanged.value = true
emit('input', value)
emit('update:modelValue', value)
}
const getValue = (): string | number => {
// Use the modelValue only if it was initialized to something and the value hasn't been changed
return currValue.value || modelValueChanged.value ? currValue.value : modelValue
}
const focus = () => {
input$.value?.focus?.()
}
const blur = () => {
input$.value?.blur?.()
}
defineExpose({
focus,
blur,
})
watch(() => error, (newVal, oldVal) => {
if (newVal !== oldVal) {
// bump the key to trigger the transition
helpTextKey.value += 1
}
})
const beforeSlotElement = ref<HTMLElement | null>(null)
const afterSlotElement = ref<HTMLElement | null>(null)
const beforeSlotElementWidth = ref<string>(KUI_ICON_SIZE_40) // default to slot icon size
const afterSlotElementWidth = ref<string>(KUI_ICON_SIZE_40) // default to slot icon size
const maskValue = ref<boolean>(false)
const inputType = computed((): string => {
return type === 'password' && maskValue.value ? 'text' : type
})
onMounted(async () => {
await nextTick() // wait for the slots content to render
if (beforeSlotElement.value?.offsetWidth) {
beforeSlotElementWidth.value = beforeSlotElement.value.offsetWidth + 'px'
}
if (afterSlotElement.value?.offsetWidth) {
afterSlotElementWidth.value = afterSlotElement.value.offsetWidth + 'px'
}
})
</script>
<script lang="ts">
export default {
inheritAttrs: false,
}
</script>
<style lang="scss" scoped>
/* Component variables */
// Only add variables here sparingly for ease of use when the same value needs to be referenced for display logic.
$kInputPaddingX: var(--kui-space-50, $kui-space-50); // corresponds to mixin, search for variable name in mixins
$kInputIconSize: var(--kui-icon-size-40, $kui-icon-size-40); // $kSelectInputIconSize
$kInputSlotSpacing: var(--kui-space-40, $kui-space-40); // $kSelectInputSlotSpacing
/* Component styles */
.k-input {
display: flex;
flex-direction: column;
width: 100%;
// error styles
&.input-error {
.input, .input[type="file"] {
@include inputError;
&:hover {
@include inputErrorHover;
}
&:focus {
@include inputErrorFocus;
}
}
.help-text {
color: var(--kui-color-text-danger, $kui-color-text-danger);
}
}
.help-text {
@include inputHelpText;
// fixing mixed-decls deprecation: https://sass-lang.com/d/mixed-decls
// stylelint-disable-next-line no-duplicate-selectors
& {
// reset default margin from browser
margin: 0;
margin-top: var(--kui-space-40, $kui-space-40) !important; // need important to override some overrides of default p margin in other components
}
}
// slots styles
.input-element-wrapper {
position: relative;
.before-content-wrapper,
.after-content-wrapper {
color: var(--kui-color-text-neutral, $kui-color-text-neutral);
display: inline-flex;
gap: var(--kui-space-10, $kui-space-10);
position: absolute;
top: 50%;
transform: translateY(-50%);
// enforce icon size exported by @kong/icons because it's defined by the design system
:deep(#{$kongponentsKongIconSelector}) {
height: $kInputIconSize !important;
width: $kInputIconSize !important;
}
// enhance the experience for most common cases that icon only slots should not
// prevent the input from being focused by click on the icon
&:has(> #{$kongponentsKongIconSelector}:not(button):not([role="button"]):only-child) {
pointer-events: none;
}
:deep([role="button"]:not(.k-button)), :deep(button:not(.k-button)),
.mask-value-toggle-button {
@include defaultButtonReset;
// fixing mixed-decls deprecation: https://sass-lang.com/d/mixed-decls
// stylelint-disable-next-line no-duplicate-selectors
& {
color: var(--kui-color-text-neutral, $kui-color-text-neutral);
}
&:not([disabled]) {
border-radius: var(--kui-border-radius-20, $kui-border-radius-20);
cursor: pointer;
outline: none;
&:hover, &:focus, &:focus-visible {
color: var(--kui-color-text, $kui-color-text) !important;
}
&:focus-visible {
box-shadow: var(--kui-shadow-focus, $kui-shadow-focus);
}
}
&[disabled] {
color: var(--kui-color-text-disabled, $kui-color-text-disabled) !important;
pointer-events: none;
}
}
}
.before-content-wrapper {
left: 0;
margin-left: $kInputPaddingX;
}
.after-content-wrapper {
margin-right: $kInputPaddingX;
right: 0;
}
&.has-before-content {
.input {
// if there is a before slot, add padding to the left of the input
// standard padding + slot with + space between icon and input
padding-left: calc($kInputPaddingX + v-bind('beforeSlotElementWidth') + $kInputSlotSpacing);
}
}
&.has-after-content {
.input {
// if there is a after slot, add padding to the right of the input
// standard padding + slot with + space between icon and input
padding-right: calc($kInputPaddingX + v-bind('afterSlotElementWidth') + $kInputSlotSpacing);
}
}
}
}
.input {
@include inputDefaults;
&:hover {
@include inputHover;
}
&:focus {
@include inputFocus;
}
&:disabled {
@include inputDisabled;
}
&:read-only {
@include inputReadOnly;
// by default type="file" is read-only so we need to apply default input styles to override read-only styles
&[type="file"] {
@include inputDefaults;
// fixing mixed-decls deprecation: https://sass-lang.com/d/mixed-decls
// stylelint-disable-next-line no-duplicate-selectors
& {
cursor: pointer;
}
&:hover {
@include inputHover;
}
&:focus {
@include inputFocus;
}
&:disabled {
@include inputDisabled;
}
}
}
// hide default password reveal icon in Edge
&::-ms-reveal {
display: none;
}
}
</style>