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
7 changes: 7 additions & 0 deletions .changeset/tags-input-hidden-input-stale-value.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"@zag-js/tags-input": patch
---

Fix native form submit so `FormData` reflects the current tags (#3193).

The hidden input kept its initial value after tags were added, removed, or cleared. With `defaultValue={["a"]}`, adding `"b"` and submitting sent `"a"` instead of `"a, b"`.
8 changes: 8 additions & 0 deletions e2e/models/model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,14 @@ export class Model {
return this.page.getByText(text).click()
}

clickButton(name: string, options?: { modifiers?: Array<"Alt" | "Control" | "Meta" | "Shift"> }) {
return this.page.getByRole("button", { name }).first().click(options)
}

seeTextValue(selector: string, value: string) {
return expect(this.page.locator(selector)).toHaveText(value)
}

see(text: string, context?: string) {
const locator = context ? this.page.locator(context).getByText(text) : this.page.getByText(text)
return expect(locator).toBeVisible()
Expand Down
4 changes: 2 additions & 2 deletions e2e/models/tags-input.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@ export class TagsInputModel extends Model {
super(page)
}

goto() {
return this.page.goto("/tags-input/basic")
goto(url = "/tags-input/basic") {
return this.page.goto(url)
}

private get input() {
Expand Down
4 changes: 0 additions & 4 deletions e2e/models/tree-view.model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,10 +42,6 @@ export class TreeViewModel extends Model {
return this.branchTrigger(name).click(options)
}

clickButton(name: string, options?: ClickOptions) {
return this.button(name).click(options)
}

focusItem(name: string) {
return this.item(name).focus()
}
Expand Down
27 changes: 27 additions & 0 deletions e2e/tags-input.e2e.ts
Original file line number Diff line number Diff line change
Expand Up @@ -313,3 +313,30 @@ test.describe("tags-input", () => {
await I.seeInputIsFocused()
})
})

test.describe("tags-input / form", () => {
test.beforeEach(async ({ page }) => {
I = new TagsInputModel(page)
await I.goto("/tags-input/form")
})

test("native submit reflects tags added after mount", async () => {
await I.addTag("Svelte")
await I.clickButton("Submit")
await I.seeTextValue("[data-testid=last-submit]", "React, Vue, Svelte")
})

test("native submit reflects tags removed after mount", async () => {
await I.clickTagClose("Vue")
await I.dontSeeTag("Vue")
await I.clickButton("Submit")
await I.seeTextValue("[data-testid=last-submit]", "React")
})

test("native submit reflects cleared tags", async () => {
await I.clickClearTrigger()
await I.seeNoTags()
await I.clickButton("Submit")
await I.seeTextValue("[data-testid=last-submit]", "")
})
})
84 changes: 84 additions & 0 deletions examples/next-ts/pages/tags-input/form.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
import { normalizeProps, useMachine } from "@zag-js/react"
import { tagsInputControls } from "@zag-js/shared"
import * as tagsInput from "@zag-js/tags-input"
import { useId, useState } from "react"
import { StateVisualizer } from "../../components/state-visualizer"
import { Toolbar } from "../../components/toolbar"
import { useControls } from "../../hooks/use-controls"

function toDashCase(str: string) {
return str.replace(/\s+/g, "-").toLowerCase()
}

export default function Page() {
const controls = useControls(tagsInputControls)

const [submitCount, setSubmitCount] = useState(0)
const [lastSubmit, setLastSubmit] = useState<string | null>(null)

const service = useMachine(tagsInput.machine, {
id: useId(),
name: "tags",
defaultValue: ["React", "Vue"],
...controls.context,
})

const api = tagsInput.connect(service, normalizeProps)

return (
<>
<main className="tags-input">
<form
onSubmit={(e) => {
e.preventDefault()
const data = new FormData(e.currentTarget)
const value = String(data.get("tags") ?? "")
setSubmitCount((c) => c + 1)
setLastSubmit(value)
}}
>
<div {...api.getRootProps()}>
<label {...api.getLabelProps()}>Enter frameworks:</label>
<div {...api.getControlProps()}>
{api.value.map((value, index) => (
<span key={`${toDashCase(value)}-tag-${index}`} {...api.getItemProps({ index, value })}>
<div data-testid={`${toDashCase(value)}-tag`} {...api.getItemPreviewProps({ index, value })}>
<span data-testid={`${toDashCase(value)}-valuetext`} {...api.getItemTextProps({ index, value })}>
{value}{" "}
</span>
<button
data-testid={`${toDashCase(value)}-close-button`}
{...api.getItemDeleteTriggerProps({ index, value })}
>
&#x2715;
</button>
</div>
<input data-testid={`${toDashCase(value)}-input`} {...api.getItemInputProps({ index, value })} />
</span>
))}
<input data-testid="input" placeholder="add tag" {...api.getInputProps()} />
<button type="button" {...api.getClearTriggerProps()}>
X
</button>
</div>
<input {...api.getHiddenInputProps()} />
</div>

<div style={{ marginTop: 16 }}>
<button type="submit">Submit</button>
</div>
</form>

<section style={{ marginTop: 16 }}>
<strong>submit count:</strong> <span data-testid="submit-count">{submitCount}</span>
<br />
<strong>last submitted value:</strong> <span data-testid="last-submit">{lastSubmit ?? "—"}</span>
</section>
</main>

<Toolbar controls={controls.ui}>
<StateVisualizer state={service} />
</Toolbar>
</>
)
}
7 changes: 6 additions & 1 deletion packages/machines/tags-input/src/tags-input.machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,9 @@ export const machine = createMachine<TagsInputSchema>({
},

watch({ track, context, action, computed, refs }) {
track([() => computed("valueAsString")], () => {
action(["dispatchChangeEvent"])
})
track([() => context.get("editedTagValue")], () => {
action(["syncEditedTagInputValue"])
})
Expand Down Expand Up @@ -438,7 +441,9 @@ export const machine = createMachine<TagsInputSchema>({
send({ type: "EXTERNAL_BLUR", id: event.id })
},
dispatchChangeEvent({ scope, computed }) {
dom.dispatchInputEvent(scope, computed("valueAsString"))
queueMicrotask(() => {
dom.dispatchInputEvent(scope, computed("valueAsString"))
})
},
highlightNextTag({ context, scope }) {
const highlightedTagId = context.get("highlightedTagId")
Expand Down
1 change: 1 addition & 0 deletions shared/src/routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,7 @@ export const componentRoutes: ComponentRoute[] = [
label: "Tags Input",
examples: [
{ slug: "basic", title: "Basic" },
{ slug: "form", title: "Form" },
{ slug: "validate", title: "Validate" },
{ slug: "allow-duplicates", title: "Allow Duplicates" },
{ slug: "sentence-builder", title: "Builder" },
Expand Down
Loading