Skip to content

Commit 3090035

Browse files
committed
Make Form/Contact survive View Transitions
1 parent 521bc84 commit 3090035

1 file changed

Lines changed: 28 additions & 4 deletions

File tree

  • src/components/Forms/Contact/client

src/components/Forms/Contact/client/index.ts

Lines changed: 28 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@ const COMPONENT_TAG_NAME = 'contact-form' as const
2121
export class ContactFormElement extends LitElement {
2222
private labelController: LabelController | null = null
2323
private viewTransitionHandlersRegistered = false
24+
private beforePreparationHandler: (() => void) | null = null
25+
private afterSwapHandler: (() => void) | null = null
2426

2527
private config: ContactFormConfig = {
2628
maxCharacters: 2000,
@@ -38,6 +40,11 @@ export class ContactFormElement extends LitElement {
3840
this.initialize()
3941
}
4042

43+
override disconnectedCallback() {
44+
super.disconnectedCallback()
45+
this.removeViewTransitionsHandlers()
46+
}
47+
4148
private initialize(): void {
4249
const context = { scriptName: 'ContactFormElement', operation: 'initialize' }
4350
addScriptBreadcrumb(context)
@@ -65,17 +72,34 @@ export class ContactFormElement extends LitElement {
6572
return
6673
}
6774

68-
document.addEventListener('astro:before-preparation', () => {
75+
this.beforePreparationHandler = () => {
6976
ContactFormElement.handleBeforePreparation()
70-
})
77+
}
7178

72-
document.addEventListener('astro:after-swap', () => {
79+
this.afterSwapHandler = () => {
7380
this.initialize()
74-
})
81+
}
82+
83+
document.addEventListener('astro:before-preparation', this.beforePreparationHandler)
84+
document.addEventListener('astro:after-swap', this.afterSwapHandler)
7585

7686
this.viewTransitionHandlersRegistered = true
7787
}
7888

89+
private removeViewTransitionsHandlers(): void {
90+
if (this.beforePreparationHandler) {
91+
document.removeEventListener('astro:before-preparation', this.beforePreparationHandler)
92+
this.beforePreparationHandler = null
93+
}
94+
95+
if (this.afterSwapHandler) {
96+
document.removeEventListener('astro:after-swap', this.afterSwapHandler)
97+
this.afterSwapHandler = null
98+
}
99+
100+
this.viewTransitionHandlersRegistered = false
101+
}
102+
79103
private static handleBeforePreparation(): void {
80104
// Reserved for cleanup prior to Astro View Transitions swapping content
81105
}

0 commit comments

Comments
 (0)