From 7598aac6d18b41ae2fb3d33ae94f1c14f373d6da Mon Sep 17 00:00:00 2001 From: Mike Fiedler Date: Sun, 21 Nov 2021 20:21:21 -0500 Subject: [PATCH 1/3] Add controller for search focus for slash keypress While having the search key autofocus is forbidden, having a keypress focus the search field is a desirable feature. Add a new Stumulus Controller that listens to the `/` keypress and focuses the input on the search field. Note: Currently applies only to the home page. Refs: #6099 Signed-off-by: Mike Fiedler --- .../controllers/search_focus_controller.js | 30 +++++++++++++++++++ warehouse/templates/index.html | 4 +-- 2 files changed, 32 insertions(+), 2 deletions(-) create mode 100644 warehouse/static/js/warehouse/controllers/search_focus_controller.js diff --git a/warehouse/static/js/warehouse/controllers/search_focus_controller.js b/warehouse/static/js/warehouse/controllers/search_focus_controller.js new file mode 100644 index 000000000000..047e4595f612 --- /dev/null +++ b/warehouse/static/js/warehouse/controllers/search_focus_controller.js @@ -0,0 +1,30 @@ +/** + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Controller } from "stimulus"; + +export default class extends Controller { + static targets = ["searchField"]; + + connect() { + // Listen for the "/" key pressed + document.addEventListener("keydown", (event) => { + if (event.code === "Slash") { + // Prevent the key from being handled as an actual input + event.preventDefault(); + this.searchFieldTarget.focus(); + } + }); + } +} diff --git a/warehouse/templates/index.html b/warehouse/templates/index.html index c8744082f708..27dc6ed58d9c 100644 --- a/warehouse/templates/index.html +++ b/warehouse/templates/index.html @@ -51,11 +51,11 @@

{{ banner }}

-