Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion packages/ui/src/components/va-carousel/VaCarousel.vue
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ export default defineComponent({
emits: [...useStatefulEmits],

setup (props, { emit }) {
const { valueComputed: currentSlide } = useStateful(props, emit, 'modelValue', { defaultValue: 0 })
const { valueComputed: currentSlide } = useStateful(props, emit, 'modelValue')

const {
goTo, next, prev,
Expand Down
64 changes: 64 additions & 0 deletions packages/ui/src/components/va-form/VaForm.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
VaRadio,
} from '../'
import { sleep } from '../../utils/sleep'
import { useForm } from '../../composables'

export default {
title: 'VaForm',
Expand Down Expand Up @@ -475,3 +476,66 @@ addText(
'This is old demo resqued to have visual tests, but we want to rewrite it eventually.',
'stale',
)

export const FormDataInitialValue = () => ({
components: {
VaForm,
VaInput,
VaSelect,
VaDateInput,
VaTimeInput,
VaOptionList,
VaButton,
},
data: () => ({
input: 'value',
checkbox: true,
date: new Date(0),
time: new Date(0),
options: OPTIONS,
select: OPTIONS[0],
validationRules: [false],
}),
setup () {
const form = useForm('formEl')

return {
form,
}
},
template: `
[form data]: <pre>{{ form.formData }}</pre>

<va-form ref="formEl" stateful>
<va-checkbox
v-model="checkbox"
:rules="validationRules"
name="checkbox"
/>
<va-date-input
v-model="date"
:rules="validationRules"
name="date"
/>
<va-input
v-model="input"
:rules="validationRules"
name="text"
/>
<va-select
v-model="select"
:options="options"
:rules="validationRules"
name="select"
/>
<va-time-input
v-model="time"
:rules="validationRules"
name="time"
/>
</va-form>
<va-button @click="$refs.form.reset()">
Reset form
</va-button>
`,
})
6 changes: 6 additions & 0 deletions packages/ui/src/components/va-input/VaInput.stories.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { ref } from 'vue'
import VaInputDemo from './VaInput.demo.vue'
import VaInput from './VaInput.vue'
import { expect } from '@storybook/jest'
Expand All @@ -19,6 +20,11 @@ export const Loading = () => ({
template: '<VaInput loading />',
})

export const Stateful = () => ({
components: { VaInput },
template: '<VaInput stateful />',
})

export const Clearable = () => ({
components: { VaInput },
data () {
Expand Down
4 changes: 2 additions & 2 deletions packages/ui/src/components/va-input/VaInput.vue
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ export default defineComponent({
// input
placeholder: { type: String, default: '' },
tabindex: { type: [String, Number], default: 0 },
modelValue: { type: [String, Number] },
modelValue: { type: [Number, String], default: '' },
type: { type: String as AnyStringPropType<'text' | 'password'>, default: 'text' },
inputClass: { type: String, default: '' },
pattern: { type: String },
Expand Down Expand Up @@ -132,7 +132,7 @@ export default defineComponent({

const input = shallowRef<HTMLInputElement>()

const { valueComputed } = useStateful(props, emit, 'modelValue', { defaultValue: '' })
const { valueComputed } = useStateful(props, emit, 'modelValue')

const reset = () => withoutValidation(() => {
emit('update:modelValue', props.clearValue)
Expand Down
29 changes: 25 additions & 4 deletions packages/ui/src/components/va-select/VaSelect.stories.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export const Validation: StoryFn = () => ({
components: { VaSelect },

data () {
return { value: '', options: ['one', 'two', 'tree'], rules: [(v: string) => (v && v === 'one') || 'Must be one'] }
return { value: '', options: ['one', 'two', 'three'], rules: [(v: string) => (v && v === 'one') || 'Must be one'] }
},

template: '<VaSelect v-model="value" :options="options" :rules="rules" />',
Expand All @@ -46,7 +46,7 @@ export const ImmediateValidation: StoryFn = () => ({
components: { VaSelect },

data () {
return { value: '', options: ['one', 'two', 'tree'], rules: [(v: string) => (v && v === 'one') || 'Must be one'] }
return { value: '', options: ['one', 'two', 'three'], rules: [(v: string) => (v && v === 'one') || 'Must be one'] }
},

template: '<VaSelect v-model="value" :options="options" :rules="rules" immediate-validation />',
Expand All @@ -63,7 +63,7 @@ export const DirtyValidation: StoryFn = () => ({
components: { Component: VaSelect },

data () {
return { value: '', dirty: false, haveError: false, options: ['one', 'two', 'tree'], rules: [(v: string) => (v && v === 'one') || 'Must be one'] }
return { value: '', dirty: false, haveError: false, options: ['one', 'two', 'three'], rules: [(v: string) => (v && v === 'one') || 'Must be one'] }
},

template: `
Expand Down Expand Up @@ -104,7 +104,7 @@ export const DirtyImmediateValidation: StoryFn = () => ({
components: { Component: VaSelect },

data () {
return { value: '', dirty: false, haveError: false, options: ['one', 'two', 'tree'], rules: [(v: string) => (v && v === 'one') || 'Must be one'] }
return { value: '', dirty: false, haveError: false, options: ['one', 'two', 'three'], rules: [(v: string) => (v && v === 'one') || 'Must be one'] }
},

template: `
Expand All @@ -124,3 +124,24 @@ DirtyImmediateValidation.play = async ({ canvasElement, step }) => {
expect(error).not.toBeNull()
})
}

export const Autocomplete: StoryFn = () => ({
components: { VaSelect },

data () {
// Test if initial value is correctly set
return { value: 'one', options: ['one', 'two', 'three'] }
},

template: '<VaSelect v-model="value" :options="options" autocomplete />',
})

export const AutocompleteMultiple: StoryFn = () => ({
components: { VaSelect },

data () {
return { value: ['one', 'two'], options: ['one', 'two', 'three'] }
},

template: '<VaSelect v-model="value" :options="options" autocomplete multiple />',
})
5 changes: 5 additions & 0 deletions packages/ui/src/components/va-select/hooks/useAutocomplete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ export const useAutocomplete = (
) => {
const getLastOptionText = (v: SelectOption[]) => v?.length ? getText(v.at(-1)!) : ''

if (props.autocomplete && !props.multiple) {
// Set current value as autocomplete value text
autocompleteValue.value = getLastOptionText(value.value)
}

watch(value, (newValue, oldValue) => {
if (!props.autocomplete) { return }

Expand Down
2 changes: 1 addition & 1 deletion packages/ui/src/components/va-stepper/VaStepper.vue
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ export default defineComponent({
emits: ['update:modelValue', 'finish', 'update:steps'],
setup (props, { emit }) {
const stepperNavigation = shallowRef<HTMLElement>()
const { valueComputed: modelValue }: { valueComputed: Ref<number> } = useStateful(props, emit, 'modelValue', { defaultValue: 0 })
const { valueComputed: modelValue }: { valueComputed: Ref<number> } = useStateful(props, emit, 'modelValue')

const focusedStep = ref({ trigger: false, stepIndex: props.navigationDisabled ? -1 : props.modelValue })

Expand Down
9 changes: 7 additions & 2 deletions packages/ui/src/composables/tests/useStateful.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,13 +30,18 @@ describe('useStateful', () => {
[ true, true, true ],
[ false, true, undefined ],
/* eslint-enable */
])('stateful %s', async (stateful: boolean, valueToSet: boolean, internalValue?: true) => {
const wrapper = mount(TestComponentRich, { props: { stateful } })
])('stateful %s', async (stateful: boolean, valueToSet: boolean, internalValue?: boolean) => {
const wrapper = mount(TestComponentRich, { props: { stateful } as any })
wrapper.vm.valueComputed = valueToSet
expect(wrapper.emitted()['update:modelValue']).toBeTruthy()
expect(wrapper.vm.valueComputed).toBe(internalValue)

await wrapper.setProps({ modelValue: false })
expect(wrapper.vm.valueComputed).toBe(false)
})

it('should react to prop change', async () => {
const wrapper = mount(TestComponentRich, { props: { stateful: true, modelValue: 'Hello!' } })
expect(wrapper.vm.valueComputed).toBe('Hello!')
})
})
27 changes: 27 additions & 0 deletions packages/ui/src/composables/tests/useUserProvidedProp.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import { mount } from '@vue/test-utils'
import { describe, it, expect } from 'vitest'
import { defineComponent } from 'vue'
import { NOT_PROVIDED, useUserProvidedProp } from '../useUserProvidedProp'

const TestComponentRich = defineComponent({
template: '<p></p>',
props: { modelValue: { type: String } },
setup (props) {
const providedProp = useUserProvidedProp('modelValue', props)

return {
providedProp,
}
},
emits: ['update:modelValue'],
})

describe('useUserProvidedProp', () => {
it('should react to prop change', async () => {
const wrapper = mount(TestComponentRich, { props: { stateful: true } } as any)
expect(wrapper.vm.providedProp).toBe(NOT_PROVIDED)

await wrapper.setProps({ modelValue: 'Hello' })
expect(wrapper.vm.providedProp).toBe('Hello')
})
})
1 change: 1 addition & 0 deletions packages/ui/src/composables/useSelectable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ export type SelectableProps<V = any> = StatefulProps & LoadingProps & ExtractPro
indeterminateValue: V | null,
disabled: boolean,
readonly: boolean,
modelValue: unknown
}

export type Elements = {
Expand Down
18 changes: 11 additions & 7 deletions packages/ui/src/composables/useStateful.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { ref, computed, watch, PropType, Ref } from 'vue'
import { ref, computed, watch, PropType, Ref, getCurrentInstance, watchEffect } from 'vue'
import { NOT_PROVIDED, useUserProvidedProp } from './useUserProvidedProp'

export type StatefulProps = {
stateful: boolean
}

export type StatefulOptions<T> = {
eventName?: string
/** @deprecated set default value for prop, not here */
/** Prefer to set default value for prop, not here. */
defaultValue?: T
}

Expand Down Expand Up @@ -41,18 +42,21 @@ export const useStateful = <
D extends any,
O extends StatefulOptions<D>,
Key extends string = 'modelValue',
P extends StatefulProps & { [key in Key]?: T } = StatefulProps & { [key in Key]?: T },
P extends StatefulProps & Record<Key, T> = StatefulProps & Record<Key, T>
>(
props: P,
emit: (name: `update:${Key}`, ...args: any[]) => void,
key: Key = 'modelValue' as Key,
options: O = {} as O,
) => {
const { defaultValue, eventName } = options
const { eventName, defaultValue } = options
const event = (eventName || `update:${key.toString()}`) as `update:${Key}`
const valueState = ref(defaultValue === undefined ? props[key] : defaultValue) as Ref
let unwatchModelValue: Function

const passedProp = useUserProvidedProp(key, props)

const valueState = ref(passedProp.value === NOT_PROVIDED ? defaultValue || props[key] : passedProp) as Ref<P[Key]>

let unwatchModelValue: ReturnType<typeof watch>
const watchModelValue = () => {
unwatchModelValue = watch(() => props[key], (modelValue) => {
valueState.value = modelValue
Expand All @@ -63,7 +67,7 @@ export const useStateful = <
stateful ? watchModelValue() : unwatchModelValue?.()
}, { immediate: true })

const valueComputed = computed<unknown extends O['defaultValue'] ? P[Key] : NonUndefined<P[Key]>>({
const valueComputed = computed({
get: () => {
if (props.stateful) { return valueState.value }

Expand Down
14 changes: 14 additions & 0 deletions packages/ui/src/composables/useUserProvidedProp.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { computed, getCurrentInstance } from 'vue'

export const NOT_PROVIDED = Symbol('NOT_PROVIDED')

export const useUserProvidedProp = <Name extends string, Props extends Record<Name, any>>(propName: Name, props: Props) => {
const vm = getCurrentInstance()!

return computed(() => {
if (!vm?.vnode.props) { return null }
const originalProp = props[propName]
// If vnode doesn't have this prop it mean default value is used
return propName in vm.vnode.props ? originalProp as Props[Name] : NOT_PROVIDED
})
}