Skip to content

Commit befed8e

Browse files
committed
better click outside
1 parent 5d6967c commit befed8e

1 file changed

Lines changed: 29 additions & 8 deletions

File tree

src/lib/elements/forms/inputSelectSearch.svelte

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
<script lang="ts">
22
import { clickOnEnter } from '$lib/helpers/a11y';
33
import { createCombobox, melt } from '@melt-ui/svelte';
4+
45
import { createEventDispatcher, onMount } from 'svelte';
56
import { Label } from '.';
67
@@ -46,7 +47,8 @@
4647
}
4748
return next;
4849
},
49-
preventScroll: false
50+
preventScroll: false,
51+
closeOnOutsideClick: false
5052
});
5153
5254
$: {
@@ -59,14 +61,16 @@
5961
$: selectedOption = options.find((option) => option.value === value);
6062
$: selectedOption && innerSelected.set(selectedOption);
6163
62-
let element: HTMLInputElement;
64+
let inputEl: HTMLInputElement;
65+
let menuEl: HTMLElement;
66+
let wrapperEl: HTMLElement;
6367
let hasFocus = false;
6468
6569
const dispatch = createEventDispatcher();
6670
6771
onMount(() => {
68-
if (element && autofocus) {
69-
element.focus();
72+
if (inputEl && autofocus) {
73+
inputEl.focus();
7074
}
7175
});
7276
@@ -85,10 +89,27 @@
8589
$: console.log(disabled);
8690
</script>
8791

92+
<svelte:window
93+
on:click={function clickOutside(e) {
94+
const el = e.target;
95+
if (!(el instanceof HTMLElement || el instanceof SVGElement)) {
96+
open.set(false);
97+
return;
98+
}
99+
100+
if (!menuEl || !wrapperEl) return;
101+
102+
if (!wrapperEl.contains(el) && !menuEl.contains(el)) {
103+
hasFocus = false;
104+
$open = false;
105+
}
106+
}} />
107+
88108
<div
89109
class="u-position-relative form-item"
90110
class:u-width-full-line={fullWidth}
91-
class:u-stretch={stretch}>
111+
class:u-stretch={stretch}
112+
bind:this={wrapperEl}>
92113
<Label {required} {hideRequired} {optionalText} hide={!showLabel} for={id} {tooltip}>
93114
{label}
94115
</Label>
@@ -112,7 +133,7 @@
112133
{placeholder}
113134
{required}
114135
on:input={handleInput}
115-
bind:this={element}
136+
bind:this={inputEl}
116137
use:melt={$input} />
117138
{/if}
118139

@@ -133,14 +154,14 @@
133154
disabled={!interactiveOutput}
134155
on:click={() => {
135156
hasFocus = !hasFocus;
136-
open.set(true);
157+
$open = !$open;
137158
}}>
138159
<span class="icon-cheveron-down" aria-hidden="true" />
139160
</button>
140161
</div>
141162
</div>
142163

143-
<div class="drop-wrapper" use:melt={$menu}>
164+
<div class="drop-wrapper" use:melt={$menu} bind:this={menuEl}>
144165
<div class="drop is-no-arrow">
145166
<section class="drop-section">
146167
<ul class="drop-list">

0 commit comments

Comments
 (0)