]> git.immae.eu Git - github/bastienwirtz/homer.git/blob - src/components/SearchInput.vue
Fix #171: empty search opens first item
[github/bastienwirtz/homer.git] / src / components / SearchInput.vue
1 <template>
2 <div class="search-bar">
3 <label for="search" class="search-label"></label>
4 <input
5 type="text"
6 ref="search"
7 :value="value"
8 @input="search($event.target.value)"
9 @keyup.enter.exact="open()"
10 @keyup.alt.enter="open('_blank')"
11 />
12 </div>
13 </template>
14
15 <script>
16 export default {
17 name: "SearchInput",
18 props: ["value"],
19 mounted() {
20 this._keyListener = function (event) {
21 if (event.key === "/") {
22 event.preventDefault();
23 this.focus();
24 }
25 if (event.key === "Escape") {
26 this.cancel();
27 }
28 };
29 document.addEventListener("keydown", this._keyListener.bind(this));
30
31 // fill seach from get parameter.
32 const search = new URLSearchParams(window.location.search).get("search");
33 if (search) {
34 this.$refs.search.value = search;
35 this.search(search);
36 this.focus();
37 }
38 },
39 methods: {
40 open: function (target = null) {
41 if (!this.$refs.search.value) {
42 return;
43 }
44 this.$emit("search-open", target);
45 },
46 focus: function () {
47 this.$emit("search-focus");
48 this.$nextTick(() => {
49 this.$refs.search.focus();
50 });
51 },
52 setSearchURL: function (value) {
53 const url = new URL(window.location);
54 if (value === "") {
55 url.searchParams.delete("search");
56 } else {
57 url.searchParams.set("search", value);
58 }
59 window.history.replaceState("search", null, url);
60 },
61 cancel: function () {
62 this.setSearchURL("");
63 this.$refs.search.value = "";
64 this.$refs.search.blur();
65 this.$emit("search-cancel");
66 },
67 search: function (value) {
68 this.setSearchURL(value);
69 this.$emit("input", value.toLowerCase());
70 },
71 },
72 beforeDestroy() {
73 document.removeEventListener("keydown", this._keyListener);
74 },
75 };
76 </script>
77
78 <style lang="scss" scoped></style>