Debian Codegraph @

resources/src/mediawiki.special.block/components/ValidatingTextInput.js

raw symbols SCIP
1 const { defineComponent, h, ref } = require( 'vue' );
2 const { CdxTextInput } = require( '@wikimedia/codex' );
3
4 /**
5 * A wrapper for a TextInput that uses HTMLInputElement's `checkValidity()` to validate
6 * the input against any constraints given via HTML attributes (i.e. `required`, or `min=1`).
7 *
8 * @todo replace with Codex useNativeValidation composable once available (T373872#10175988)
9 */
10 module.exports = exports = defineComponent( {
11 name: 'ValidatingTextInput',
12 components: {
13 CdxTextInput
14 },
15 emits: [ 'update:status' ],
16 setup( props, { emit } ) {
17 const status = ref( 'default' );
18 const messages = ref( {} );
19
20 /**
21 * Clear error status when input is valid and emit the `update:messages` event.
22 *
23 * @param {Event} e
24 */
25 const onInput = ( e ) => {
26 if ( e.target.checkValidity() ) {
27 status.value = 'default';
28 messages.value = {};
29 emit( 'update:status', status.value, messages.value );
30 }
31 };
32
33 /**
34 * Set error status when input is invalid and emit the `update:messages` event.
35 *
36 * @param {Event} e
37 */
38 const onInvalid = ( e ) => {
39 status.value = 'error';
40 messages.value = {
41 error: e.target.validationMessage
42 };
43 emit( 'update:status', status.value, messages.value );
44 };
45
46 return {
47 status,
48 messages,
49 onInput,
50 onInvalid
51 };
52 },
53 render() {
54 return h( CdxTextInput, Object.assign( {}, this.$props, {
55 status: this.status,
56 onInput: this.onInput,
57 onInvalid: this.onInvalid
58 } ) );
59 }
60 } );