feat: add highlight directive

This commit is contained in:
Flo 2026-11-01 12:00:46 +01:00
parent f99c3c3b9b
commit ed21210a07
4 changed files with 78 additions and 4 deletions

View File

@ -27,6 +27,11 @@ input.search {
inset 0 0 2px rgba(0, 0, 0, 0.19);
}
input.search:disabled {
background: white;
cursor: not-allowed;
}
.suggestions {
margin: 0;
padding: 0;

View File

@ -11,12 +11,12 @@
@if (error) {
<p class="error">{{`HTTP error ${error.message}`}}</p>
} @else {
<ul class="suggestions">
<ul [appHighlight]="searchTerm()" class="suggestions">
@for (disease of filteredDiseases(); track $index) {
<li>
<span class="details">
<span class="name">{{ disease.name }}</span>,
<span class="code">{{ disease.code }}</span>
<span class="name" #highlightTarget>{{ disease.name }}</span>,
<span class="code" #highlightTarget>{{ disease.code }}</span>
</span>
<span class="abbr">{{ disease.abbr }}</span>

View File

@ -1,9 +1,10 @@
import { Component, computed, inject, signal } from '@angular/core';
import { DiseaseService } from './shared/services/disease/disease.service';
import { disabled, form, FormField } from '@angular/forms/signals';
import { HighlightDirective } from './shared/highlight/highlight.directive';
@Component({
imports: [FormField],
imports: [FormField, HighlightDirective],
selector: 'app-root',
styleUrl: './app.component.css',
templateUrl: './app.component.html',

View File

@ -0,0 +1,68 @@
import {
afterRenderEffect,
contentChildren,
DestroyRef,
Directive,
ElementRef,
inject,
input,
} from '@angular/core';
@Directive({
selector: 'ul[appHighlight]',
})
export class HighlightDirective {
readonly query = input('', { alias: 'appHighlight' });
private readonly labels = contentChildren<ElementRef<HTMLElement>>('highlightTarget', {
descendants: true,
});
private readonly destroyRef = inject(DestroyRef);
constructor() {
afterRenderEffect({
earlyRead: () => {
const query = this.query();
const labels = this.labels();
const ranges: Range[] = [];
if (!query) return ranges;
for (const label of labels) {
const textNode = label.nativeElement.firstChild;
if (!textNode || textNode.nodeType !== Node.TEXT_NODE) continue;
const text = textNode.textContent?.toLowerCase() ?? '';
let matchIndex = text.indexOf(query);
while (matchIndex !== -1) {
const range = new Range();
range.setStart(textNode, matchIndex);
range.setEnd(textNode, matchIndex + query.length);
ranges.push(range);
matchIndex = text.indexOf(query, matchIndex + query.length);
}
}
return ranges;
},
write: (ranges) => {
if (!('highlights' in CSS)) return;
CSS.highlights.set('search-match', new Highlight(...ranges()));
},
});
this.destroyRef.onDestroy(() => {
if (typeof CSS !== 'undefined' && 'highlights' in CSS) {
CSS.highlights.delete('search-match');
}
});
}
}