Skip to content

Commit 149cfa8

Browse files
committed
fix(form): Fix streams not working
1 parent bef162d commit 149cfa8

File tree

1 file changed

+21
-15
lines changed

1 file changed

+21
-15
lines changed

src/Form.tsx

Lines changed: 21 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@ import m, {
66
} from 'mithril';
77
import Stream from 'mithril/stream';
88

9-
import {isVnode} from './helpers';
109
import Component from './Component';
10+
import Mithril from 'mithril';
1111

1212
export type FormSubmitEvent = SubmitEvent & {data: FormData};
1313
export interface FormAttributes extends Partial<Omit<HTMLElementTagNameMap['form'], 'style' | 'onsubmit'>> {
@@ -53,26 +53,17 @@ export default class Form<A extends FormAttributes = FormAttributes> extends Com
5353

5454
oninput(event: InputEvent) {
5555
const input = event.target as HTMLInputElement & FormInputAttributes;
56-
// Check if child is a Vnode
57-
let stream = input.dataset.state as any;
58-
if (typeof stream !== 'function') {
59-
stream = this.getState(input.name ?? input.id);
60-
}
56+
const stream = this.getState(input.name ?? input.id);
6157
if (stream) {
62-
/**
63-
* Handle updated state.
64-
*/
65-
const newValue = stream();
66-
// Equality check is not strict since it wouldn't be safe.
67-
// Example: an int value can be set to an input with type="number"
68-
if (newValue != input.value) {
69-
input.value = newValue;
70-
}
58+
stream(input.value);
7159
}
7260
}
7361

7462
oncreate(vnode: VnodeDOM<A, this>) {
7563
super.oncreate(vnode);
64+
const formElements = [...this.element.elements] as HTMLFormElement[];
65+
66+
this.setStreamValueToInputs(formElements);
7667

7768
if (![...this.element.elements].some((element) => element.getAttribute('type') === 'submit')) {
7869
const submitter = this.element.querySelector<HTMLElement>('[type="submit"]');
@@ -88,6 +79,21 @@ export default class Form<A extends FormAttributes = FormAttributes> extends Com
8879
}
8980
}
9081

82+
onupdate(vnode: Mithril.VnodeDOM<A, this>) {
83+
super.onupdate(vnode);
84+
this.setStreamValueToInputs([...this.element.elements] as HTMLFormElement[])
85+
}
86+
87+
setStreamValueToInputs(inputs: HTMLInputElement[] | HTMLFormElement[]) {
88+
// Attach streams to inputs
89+
for (const element of inputs) {
90+
const stream = this.getState(element.name ?? element.id);
91+
if (stream) {
92+
element.value = stream();
93+
}
94+
}
95+
}
96+
9197
onsubmit(e: FormSubmitEvent) {
9298
e.preventDefault();
9399
e.data = new FormData(e.target as HTMLFormElement);

0 commit comments

Comments
 (0)