This is a viewer only at the moment see the article on how this works.
To update the preview hit Ctrl-Alt-R (or ⌘-Alt-R on Mac) or Enter to refresh. The Save icon lets you save the markdown file to disk
This is a preview from the server running through my markdig pipeline
Розумніший пошуковий Dropdown з HTMX
Monday, 16 September 2024
Введение
У попередньому пості я показував вам, як створити пошук за допомогою Alpine.js та HTMX тоді я показав, як ми можемо ввімкнути захист від фальсифікації за допомогою AntiforgeryRequestToken в ASP.NET Корі з JavaScript використовуючи HTMX для втілення Cache Donut Hole. Однією із головних проблем було те, як він завантажував сторінки
Проблема
Проблема в тому, що я використовував HTMX AJAX для завантаження page requested після того, як ви вибрали результат зі спусканої сторінки.
selectResult(result) {
htmx.ajax('get', result.url, {
target: '#contentcontainer', // The container to update
swap: 'innerHTML', // Replace the content inside the target
}).then(function() {
history.pushState(null, '', result.url);
window.scrollTo({
top: 0,
behavior: 'smooth'
});
});
Проблема була в тому, що, поки це завантажувало правильну сторінку і відновило відображену URL з новою, це зруйнувало зворотній кнопок.
Як і у моєму випадку останній artykuł про чорні ключі . це те, що я хотів виправити
Рішення
Як і раніше, рішенням було дозволити HTMX керувати цим напряму. Для цього я обновила шаблон, який я використовую для результатів пошуку.
_typeahead.cshtml
<div x-data="window.mostlylucid.typeahead()" class="relative" id="searchelement" x-on:click.outside="results = []">
@Html.AntiForgeryToken()
<label class="input input-sm bg-neutral-500 bg-opacity-10 input-bordered flex items-center gap-2">
<input
type="text"
x-model="query"
x-on:input.debounce.200ms="search"
x-on:keydown.down.prevent="moveDown"
x-on:keydown.up.prevent="moveUp"
x-on:keydown.enter.prevent="selectHighlighted"
placeholder="Search..."
class="border-0 grow input-sm text-black dark:text-white bg-transparent w-full"/>
<i class="bx bx-search"></i>
</label>
<!-- Dropdown -->
<ul x-show="results.length > 0"
id="searchresults"
class="absolute z-100 my-2 w-full bg-white dark:bg-custom-dark-bg border border-1 text-black dark:text-white border-neutral-600 rounded-lg shadow-lg">
<template x-for="(result, index) in results" :key="result.slug">
<li :class="{
'dark:bg-blue-dark bg-blue-light': index === highlightedIndex,
'dark:hover:bg-blue-dark hover:bg-blue-light': true
}"
class="cursor-pointer text-sm p-2 m-2">
<!-- These are the key changes.-->
<a
x-on:click="selectResult(index)"
@* :href="result.url" *@
:hx-get="result.url"
hx-target="#contentcontainer"
hx-swap="innerHTML"
hx-push-url="true"
x-text="result.title"
>
</a>
<-- End of changes -->
</li>
</template>
</ul>
</div>
Ви побачите, що я зараз генерую належним Ссылки HTMX в цьому блокі коду. Дозволять нам використовувати правильне поведінку HT MX.
typeahead.js
Для того, щоб це зробити в моєму програмному коді JavaScript, я додав до мого способу пошуку ось що: (отображається нижчеM SK1 this.$nextTick це конструкція Alpine.js, яка затримує процес доки Alpine не закінчить обробку шаблону, який я показав раніше
Тоді я використовую htmx.process() на elemenті пошуку, який гарантує, що атрибути HTMX працюватимуть як очікувалося.
.then(data => {
this.results = data;
this.highlightedIndex = -1; // Reset index on new search
this.$nextTick(() => {
htmx.process(document.getElementById('searchresults'));
});
})
typeahead.js search
search() {
if (this.query.length < 2) {
this.results = [];
this.highlightedIndex = -1;
return;
}
let token = document.querySelector('#searchelement input[name="__RequestVerificationToken"]').value;
console.log(token);
fetch(`/api/search/${encodeURIComponent(this.query)}`, { // Fixed the backtick and closing bracket
method: 'GET', // or 'POST' depending on your needs
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': token // Attach the AntiForgery token in the headers
}
})
.then(response => {
if(response.ok){
return response.json();
}
return Promise.reject(response);
})
.then(data => {
this.results = data;
this.highlightedIndex = -1; // Reset index on new search
this.$nextTick(() => {
htmx.process(document.getElementById('searchresults'));
});
})
.catch((response) => {
console.log(response.status, response.statusText);
if(response.status === 400)
{
console.log('Bad request, reloading page to try to fix it.');
window.location.reload();
}
response.json().then((json) => {
console.log(json);
})
console.log("Error fetching search results");
});
}
selectHighlighted() {
if (this.highlightedIndex >= 0 && this.highlightedIndex < this.results.length) {
this.selectResult(this.highlightedIndex);
}
},
selectResult(selectedIndex) {
let links = document.querySelectorAll('#searchresults a');
links[selectedIndex].click();
this.$nextTick(() => {
this.results = []; // Clear the results
this.highlightedIndex = -1; // Reset the highlighted index
this.query = ''; // Clear the query
});
}
Це відображається на щебці на посилання в результатах пошуку.
<a
x-on:click="selectResult(index)"
:hx-get="result.url"
hx-target="#contentcontainer"
hx-swap="innerHTML"
hx-push-url="true"
x-text="result.title"
>
</a>
який загрузить сторінку і відновить URL правильно.
Я також маю код у батьківській коробці, який дозволяє вам використовувати стрілкові ключі і ввести.
<label class="input input-sm bg-neutral-500 bg-opacity-10 input-bordered flex items-center gap-2">
<input
type="text"
x-model="query"
x-on:input.debounce.200ms="search"
x-on:keydown.down.prevent="moveDown"
x-on:keydown.up.prevent="moveUp"
x-on:keydown.enter.prevent="selectHighlighted"
placeholder="Search..."
class="border-0 grow input-sm text-black dark:text-white bg-transparent w-full"/>
<i class="bx bx-search"></i>
</label>
Ви побачите, що тут є весь код, який необхідний для того, щоб ви могли просто натиснути на кнопку ввести і перейти до сторінки, обраної
На завершення
Просто швидке поновлення статті до існуючого пошукового Dropdown, щоб покращити досвід користувача при використанні пошуку. Знову ж таки, це MINIМальний пользователь, що стикається з зміною, але лише покращує досвід користувачаM SK1 хто як веб-індустр є вашою головною проблемою | ( | окрім того, щоб отримати зарплату | МSK3 |