Skip to content

Commit

Permalink
Focus the search box in the popup more reliably
Browse files Browse the repository at this point in the history
If the search-input component's `focus()` method is called before the
component is actually mounted, the search box never gets the focus
because it doesn't exist yet.
  • Loading branch information
josh-berry committed Aug 11, 2024
1 parent 633f847 commit c7f7e3f
Showing 1 changed file with 11 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/components/search-input.vue
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@
</template>

<script lang="ts">
import {ref, watch} from "vue";
import {ref, watch, watchEffect, type WatchStopHandle} from "vue";
</script>

<script setup lang="ts">
Expand Down Expand Up @@ -68,7 +68,16 @@ const $search = ref(undefined! as HTMLInputElement);
defineExpose({
focus() {
$search.value.focus();
// The watchEffect() is needed to avoid a race between the parent component
// being mounted and asking us to focus ourselves, and the actual mounting
// of this component.
let cancel: WatchStopHandle | undefined = undefined;
cancel = watchEffect(() => {
if ($search.value) {
$search.value.focus();
setTimeout(() => cancel!());
}
});
},
});
Expand Down

0 comments on commit c7f7e3f

Please sign in to comment.