Search texts and states, help tooltip, wider field (F4)

materio_sapi: result messages with real plurals; without any exact
match the results are called close (the neighbour search always finds
some). Former help sentence of the base page kept, French corrected.
Messages in SearchMessage, unit tested; French added by update 11002.

materiotheme: placeholder "Describe the material you are looking for",
wider search field, "?" button with a help tooltip and clickable
examples, "Loading…", "End of results"; texts in vuejs/i18n/search.js.
Page title "Base" restored without a search (keys is an array, test its
length).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
This commit is contained in:
2026-11-23 16:44:28 +01:00
co-authored by Claude Opus 5.5
parent f7eb6518e7
commit 1e882d5bda
25 changed files with 372 additions and 48 deletions
@@ -7,6 +7,8 @@
declare(strict_types=1); declare(strict_types=1);
use Drupal\Component\Gettext\PoItem;
/** /**
* Source of the search message (H6) and its French translation. * Source of the search message (H6) and its French translation.
* *
@@ -42,3 +44,52 @@ function materio_sapi_update_11001(): string {
_locale_refresh_translations(['fr'], [$source->lid]); _locale_refresh_translations(['fr'], [$source->lid]);
return 'French translation of the search message added.'; return 'French translation of the search message added.';
} }
/**
* Sources of the search messages of F4 and their French translation.
*
* A plural is stored as singular and plural joined by PoItem::DELIMITER, for
* the source and for the translation.
*/
function materio_sapi_search_messages_strings(): array {
$plural = fn (string $one, string $many): string => $one . PoItem::DELIMITER . $many;
return [
'No results for “@keys”. Try other words or a broader description.'
=> 'Aucun résultat pour « @keys ». Essayez d’autres mots ou une description plus générale.',
$plural('No exact result, @n close result for “@keys”', 'No exact result, @n close results for “@keys”')
=> $plural('Aucun résultat exact, @n résultat proche pour « @keys »', 'Aucun résultat exact, @n résultats proches pour « @keys »'),
'1 exact result for “@keys”'
=> '1 résultat exact pour « @keys »',
$plural('@n exact result out of @total relevant results for “@keys”', '@n exact results out of @total relevant results for “@keys”')
=> $plural('@n résultat exact sur @total résultats pertinents pour « @keys »', '@n résultats exacts sur @total résultats pertinents pour « @keys »'),
// Former text, French corrected ("le champs").
'Please use the search form to search from our @count materials.'
=> 'Utilisez le champ de recherche pour naviguer dans nos @count matériaux référencés.',
];
}
/**
* Adds the French translation of the search messages (F4).
*/
function materio_sapi_update_11002(): string {
if (!\Drupal::moduleHandler()->moduleExists('locale')) {
return 'locale is off: nothing to translate.';
}
$storage = \Drupal::service('locale.storage');
$lids = [];
foreach (materio_sapi_search_messages_strings() as $source_text => $fr) {
$source = $storage->findString(['source' => $source_text, 'context' => '']);
if (!$source) {
$source = $storage->createString(['source' => $source_text, 'context' => ''])->save();
}
$storage->createTranslation([
'lid' => $source->lid,
'language' => 'fr',
'translation' => $fr,
'customized' => LOCALE_CUSTOMIZED,
])->save();
$lids[] = $source->lid;
}
_locale_refresh_translations(['fr'], $lids);
return 'French translation of the search messages added.';
}
@@ -11,6 +11,7 @@ use Drupal\materio_ai\Exception\ModelPausedException;
use Drupal\materio_sapi\KeywordText; use Drupal\materio_sapi\KeywordText;
use Drupal\materio_sapi\RankFusion; use Drupal\materio_sapi\RankFusion;
use Drupal\materio_sapi\ScoreCut; use Drupal\materio_sapi\ScoreCut;
use Drupal\materio_sapi\SearchMessage;
use Drupal\search_api\Entity\Index; use Drupal\search_api\Entity\Index;
// https://drupal.stackexchange.com/questions/225008/programatically-use-search-api // https://drupal.stackexchange.com/questions/225008/programatically-use-search-api
@@ -484,13 +485,10 @@ class Base extends ControllerBase {
$resp['count'] = count($this->results['nids']); $resp['count'] = count($this->results['nids']);
$resp['exactematch_count'] = $this->exactematch_count; $resp['exactematch_count'] = $this->exactematch_count;
// Relevant: exact matches and neighbours that stand out (H6); the // Relevant: exact matches and neighbours that stand out (H6); the
// count no longer depends on an arbitrary limit. French text added by // count no longer depends on an arbitrary limit. Plurals and "close"
// materio_sapi_update_11001(). // results without any exact match (F4).
$resp['infos'] = t('@exactmatchcount exact result(s) out of @count relevant result(s) for “@keys”', [ $resp['infos'] = (new SearchMessage($this->getStringTranslation()))
'@exactmatchcount' => $resp['exactematch_count'], ->results($resp['exactematch_count'], $resp['count'], $this->phrase, $lang);
'@count' => $resp['count'],
'@keys' => $this->phrase,
]);
// $resp['options'] = $this->query->getOptions(); // $resp['options'] = $this->query->getOptions();
// $uuids = []; // $uuids = [];
@@ -525,9 +523,10 @@ class Base extends ControllerBase {
// $resp['uuids'] = $uuids; // $resp['uuids'] = $uuids;
$resp['nids'] = $nids; $resp['nids'] = $nids;
$resp['count'] = $this->count; $resp['count'] = $this->count;
$resp['infos'] = t('Please use the search form to search from our @count materials.', array( // Help of the page before any search (F4).
"@count" => $resp['count'] $lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
)); $resp['infos'] = (new SearchMessage($this->getStringTranslation()))
->help((int) $resp['count'], $lang);
} }
return new JsonResponse($resp); return new JsonResponse($resp);
@@ -0,0 +1,71 @@
<?php
declare(strict_types=1);
namespace Drupal\materio_sapi;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\StringTranslation\TranslationInterface;
/**
* Messages shown above the search results (F4).
*
* Real plurals instead of "result(s)". Without any exact match, the other
* results are called close, not relevant: the neighbour search always finds
* some, even for a word that means nothing.
*
* Numbers go in @n and @total, formatted for the language; @count is kept by
* formatPlural() to choose the plural form only (help() is no plural).
*
* French texts added by materio_sapi_update_11002().
*/
final class SearchMessage {
public function __construct(
private readonly TranslationInterface $translation,
) {}
/**
* Message of a search: exact matches out of all the results shown.
*/
public function results(int $exact, int $total, string $keys, string $lang): TranslatableMarkup {
$args = [
'@n' => self::number($exact, $lang),
'@total' => self::number($total, $lang),
'@keys' => $keys,
];
if ($total === 0) {
return $this->translation->translate('No results for “@keys”. Try other words or a broader description.', $args);
}
if ($exact === 0) {
$args['@n'] = $args['@total'];
return $this->translation->formatPlural($total, 'No exact result, @n close result for “@keys”', 'No exact result, @n close results for “@keys”', $args);
}
if ($total === 1) {
return $this->translation->translate('1 exact result for “@keys”', $args);
}
return $this->translation->formatPlural($exact, '@n exact result out of @total relevant results for “@keys”', '@n exact results out of @total relevant results for “@keys”', $args);
}
/**
* Message of the search page before any search.
*
* The former text, kept; its French translation is corrected by
* materio_sapi_update_11002() ("le champ").
*/
public function help(int $materials, string $lang): TranslatableMarkup {
return $this->translation->translate('Please use the search form to search from our @count materials.', [
'@count' => self::number($materials, $lang),
]);
}
/**
* A number with the thousands separator of the language.
*
* French: narrow no-break space (8 073); otherwise a comma (8,073).
*/
public static function number(int $value, string $lang): string {
return number_format($value, 0, '', $lang === 'fr' ? "\u{202F}" : ',');
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\materio_sapi\Unit;
use Drupal\materio_sapi\SearchMessage;
use Drupal\Tests\UnitTestCase;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\Attributes\Group;
/**
* Tests the messages above the search results (F4), in English.
*/
#[CoversClass(SearchMessage::class)]
#[Group('materio_sapi')]
final class SearchMessageTest extends UnitTestCase {
/**
* Cases of a search: exact matches, all results, expected message.
*/
public static function resultsProvider(): array {
return [
'nothing' => [0, 0, 'No results for “bois”. Try other words or a broader description.'],
'one close' => [0, 1, 'No exact result, 1 close result for “bois”'],
'close only' => [0, 266, 'No exact result, 266 close results for “bois”'],
'one exact alone' => [1, 1, '1 exact result for “bois”'],
'one exact' => [1, 283, '1 exact result out of 283 relevant results for “bois”'],
'exacts' => [7, 283, '7 exact results out of 283 relevant results for “bois”'],
'thousands' => [35, 1475, '35 exact results out of 1,475 relevant results for “bois”'],
];
}
/**
* Plurals, and "close" results without any exact match.
*/
#[DataProvider('resultsProvider')]
public function testResults(int $exact, int $total, string $expected): void {
$message = new SearchMessage($this->getStringTranslationStub());
$this->assertSame($expected, (string) $message->results($exact, $total, 'bois', 'en'));
}
/**
* The help before any search gives the size of the catalogue.
*/
public function testHelp(): void {
$message = new SearchMessage($this->getStringTranslationStub());
$this->assertSame('Please use the search form to search from our 8,073 materials.', (string) $message->help(8073, 'en'));
}
/**
* French numbers use a narrow no-break space.
*/
public function testNumber(): void {
$this->assertSame("8\u{202F}073", SearchMessage::number(8073, 'fr'));
$this->assertSame('8,073', SearchMessage::number(8073, 'en'));
$this->assertSame('283', SearchMessage::number(283, 'fr'));
}
}
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because one or more lines are too long
Binary file not shown.
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -515,6 +515,9 @@ header[role="banner"]{
#block-pagetitle{} #block-pagetitle{}
#block-materiosapisearchblock{ #block-materiosapisearchblock{
align-self: flex-end; align-self: flex-end;
// Long enough for a phrase and for the placeholder (F4).
width: 30em;
max-width: 50%;
} }
@include col-mediaquery-max(3){ @include col-mediaquery-max(3){
flex-direction: column; flex-direction: column;
@@ -526,6 +529,7 @@ header[role="banner"]{
#block-materiosapisearchblock{ #block-materiosapisearchblock{
box-sizing: border-box; box-sizing: border-box;
width:100%; width:100%;
max-width: none;
} }
} }
@@ -614,7 +618,9 @@ header[role="banner"]{
#materio-sapi-search-form{ #materio-sapi-search-form{
display: grid; display: grid;
grid-template-columns: auto 25px; // Field, search button, help button (F4).
grid-template-columns: auto 25px 22px;
position: relative;
grid-template-rows: auto auto; grid-template-rows: auto auto;
row-gap: 0.2em; row-gap: 0.2em;
justify-items: stretch; justify-items: stretch;
@@ -655,6 +661,58 @@ header[role="banner"]{
background-color: transparent background-color: transparent
} }
// Help "?" and its tooltip (F4).
.search-help-button{
grid-row: 1 / 1;
grid-column: 3 / 3;
justify-self: end;
align-self: center;
width: 18px; height: 18px;
padding: 0;
border: 1px solid #999;
border-radius: 50%;
background: transparent;
color: #666;
font-size: 12px;
line-height: 16px;
text-align: center;
cursor: pointer;
&[aria-expanded="true"], &:hover{
background-color: #333;
border-color: #333;
color: #fff;
}
}
.search-help{
position: absolute;
z-index: 101;
top: 100%;
right: 0;
width: 22em;
max-width: 90vw;
box-sizing: border-box;
margin-top: 0.4em;
padding: 0.6em 0.8em;
border-radius: 5px;
background-color: rgba(0, 0, 0, 0.85);
color: #fff;
font-size: 0.85em;
line-height: 1.4;
p{ margin: 0 0 0.4em; }
ul{ margin: 0; padding: 0; }
li{ list-style: none; }
li button{
padding: 0.15em 0;
border: 0;
background: none;
color: #fff;
font: inherit;
text-align: left;
text-decoration: underline;
cursor: pointer;
}
}
} }
@include col-mediaquery-max(3){ @include col-mediaquery-max(3){
body:not(.path-base) &{ body:not(.path-base) &{
@@ -1427,7 +1485,6 @@ article.node--type-frontpage{
display:none; display:none;
} }
} }
&>ul{ &>ul{
// outline: 1px green solid; // outline: 1px green solid;
margin:0; padding:0; margin:0; padding:0;
@@ -8,6 +8,7 @@
class="materio-sapi-search-form" class="materio-sapi-search-form"
role="search" role="search"
@submit.prevent="submit" @submit.prevent="submit"
@keydown.esc="closeHelp"
> >
<div class="form-item form-item-search"> <div class="form-item form-item-search">
<input <input
@@ -23,7 +24,7 @@
:aria-controls="listId" :aria-controls="listId"
:aria-activedescendant="active >= 0 ? optionId(active) : null" :aria-activedescendant="active >= 0 ? optionId(active) : null"
:maxlength="maxLength" :maxlength="maxLength"
:placeholder="$t('default.Search')" :placeholder="text.placeholder"
:aria-label="$t('default.Search')" :aria-label="$t('default.Search')"
enterkeyhint="search" enterkeyhint="search"
autocomplete="off" autocomplete="off"
@@ -38,7 +39,7 @@
:id="listId" :id="listId"
class="search-suggestions" class="search-suggestions"
role="listbox" role="listbox"
:aria-label="text.list" :aria-label="text.suggestionsLabel"
> >
<li <li
v-for="(item, i) in suggestions" v-for="(item, i) in suggestions"
@@ -60,6 +61,34 @@
:value="$t('default.Search')" :value="$t('default.Search')"
:title="$t('default.Search')" :title="$t('default.Search')"
> >
<!-- Help: a "?" button opens a tooltip with examples (F4). Disclosure
pattern: aria-expanded on the button, Escape or a click outside
closes it. -->
<button
ref="helpButton"
type="button"
class="search-help-button"
:aria-expanded="helpOpen ? 'true' : 'false'"
aria-controls="search-help"
:title="text.helpLabel"
@click="helpOpen = !helpOpen"
><span aria-hidden="true">?</span><span class="visually-hidden">{{ text.helpLabel }}</span></button>
<div
v-show="helpOpen"
id="search-help"
ref="help"
class="search-help"
role="region"
:aria-label="text.helpLabel"
>
<p>{{ text.help }}</p>
<p>{{ text.examplesIntro }}</p>
<ul>
<li v-for="example in text.examples" :key="example">
<button type="button" @click="searchExample(example)">{{ example }}</button>
</li>
</ul>
</div>
</form> </form>
</template> </template>
@@ -68,23 +97,7 @@ import router from 'vuejs/route'
import { mapState } from 'vuex' import { mapState } from 'vuex'
import MA from 'vuejs/api/ma-axios' import MA from 'vuejs/api/ma-axios'
import qs from 'querystring-es3' import qs from 'querystring-es3'
import { searchTexts } from 'vuejs/i18n/search'
// Texts of the suggestion list, for screen readers. Kept here: the Vue
// translation files are generated outside the repository.
const TEXTS = {
fr: {
list: 'Suggestions',
none: '',
one: '1 suggestion, flèches haut et bas pour choisir',
many: n => `${n} suggestions, flèches haut et bas pour choisir`
},
en: {
list: 'Suggestions',
none: '',
one: '1 suggestion, use up and down arrows to choose',
many: n => `${n} suggestions, use up and down arrows to choose`
}
}
export default { export default {
router, router,
@@ -99,6 +112,7 @@ export default {
announce: '', announce: '',
listId: 'search-suggestions', listId: 'search-suggestions',
timer: null, timer: null,
helpOpen: false,
// Answers of older requests are dropped. // Answers of older requests are dropped.
requestId: 0 requestId: 0
} }
@@ -107,10 +121,7 @@ export default {
...mapState({ ...mapState({
keys: state => state.Search.keys keys: state => state.Search.keys
}), }),
text () { text: searchTexts
const lang = (window.drupalDecoupled && drupalDecoupled.lang_code) || 'en'
return TEXTS[lang] || TEXTS.en
}
}, },
methods: { methods: {
phraseFromKeys (keys) { phraseFromKeys (keys) {
@@ -145,7 +156,7 @@ export default {
this.active = -1 this.active = -1
this.open = this.suggestions.length > 0 this.open = this.suggestions.length > 0
const n = this.suggestions.length const n = this.suggestions.length
this.announce = n === 0 ? this.text.none : (n === 1 ? this.text.one : this.text.many(n)) this.announce = n === 0 ? '' : (n === 1 ? this.text.suggestionsOne : this.text.suggestionsMany(n))
}) })
.catch(error => { .catch(error => {
console.warn('Issue with search suggestions', error) console.warn('Issue with search suggestions', error)
@@ -204,6 +215,24 @@ export default {
// Only the phrase, no terms. // Only the phrase, no terms.
this.go(phrase ? { keys: phrase } : {}) this.go(phrase ? { keys: phrase } : {})
}, },
// An example of the help runs as a typed phrase.
searchExample (example) {
this.helpOpen = false
this.typed = example
this.submit()
},
closeHelp () {
if (this.helpOpen) {
this.helpOpen = false
this.$refs.helpButton.focus()
}
},
// A click outside the tooltip and its button closes it.
onDocumentClick (e) {
if (this.helpOpen && !this.$refs.help.contains(e.target) && !this.$refs.helpButton.contains(e.target)) {
this.helpOpen = false
}
},
go (query) { go (query) {
// Hide the keyboard on mobile devices. // Hide the keyboard on mobile devices.
this.$refs.input.blur() this.$refs.input.blur()
@@ -221,8 +250,12 @@ export default {
// Direct page load: the store already holds the keys of the URL. // Direct page load: the store already holds the keys of the URL.
this.typed = this.phraseFromKeys(this.keys) this.typed = this.phraseFromKeys(this.keys)
}, },
mounted () {
document.addEventListener('click', this.onDocumentClick)
},
beforeDestroy () { beforeDestroy () {
clearTimeout(this.timer) clearTimeout(this.timer)
document.removeEventListener('click', this.onDocumentClick)
} }
} }
</script> </script>
@@ -1,7 +1,7 @@
<template> <template>
<div id="Base"> <div id="Base">
<div class="loading" v-if="!searchinfos"> <div class="loading" v-if="!searchinfos">
<span>{{ $t('default.Loading…') }}</span> <span>{{ text.loading }}</span>
</div> </div>
<div class="cards-list" v-else> <div class="cards-list" v-else>
<!-- aria-live: screen readers announce the result message of each search (F1). --> <!-- aria-live: screen readers announce the result message of each search (F1). -->
@@ -9,7 +9,7 @@
{{ searchinfos }} {{ searchinfos }}
</aside> </aside>
<div class="loading" v-if="!items.length & !noresults"> <div class="loading" v-if="!items.length & !noresults">
<span>{{ $t('default.Loading…') }}</span> <span>{{ text.loading }}</span>
</div> </div>
<ul v-else> <ul v-else>
<li v-for="item in displayedItems" v-bind:key="item.id"> <li v-for="item in displayedItems" v-bind:key="item.id">
@@ -22,7 +22,7 @@
:identifier="searchId" :identifier="searchId"
@infinite="nextPage" @infinite="nextPage"
> >
<div slot="no-more">No more results</div> <div slot="no-more">{{ text.end }}</div>
</infinite-loading> </infinite-loading>
</div> </div>
</div> </div>
@@ -35,6 +35,7 @@ import Card from 'vuejs/components/Content/Card'
import CardThematique from 'vuejs/components/Content/CardThematique' import CardThematique from 'vuejs/components/Content/CardThematique'
import { mapState, mapActions } from 'vuex' import { mapState, mapActions } from 'vuex'
import { searchTexts } from 'vuejs/i18n/search'
export default { export default {
name: "Base", name: "Base",
@@ -54,6 +55,7 @@ export default {
searchId: state => state.Search.searchId, searchId: state => state.Search.searchId,
keys: state => state.Search.keys keys: state => state.Search.keys
}), }),
text: searchTexts,
// items is a sparse array (pages placed by offset); drop the holes left by // items is a sparse array (pages placed by offset); drop the holes left by
// pages that returned fewer results than the limit before rendering. // pages that returned fewer results than the limit before rendering.
displayedItems () { displayedItems () {
@@ -0,0 +1,48 @@
// Texts of the search field and of the results page (F4, F7), in French and
// English. Kept in the repository: the Vue translation files
// (sites/default/files/lang/*.json) are generated outside of it. The result
// messages come from the server (materio_sapi SearchMessage).
const TEXTS = {
fr: {
placeholder: 'Décrivez le matériau recherché',
loading: 'Chargement…',
end: 'Fin des résultats',
helpLabel: 'Aide à la recherche',
help: 'Décrivez en quelques mots le matériau, son usage ou l’effet recherché.',
examplesIntro: 'Par exemple :',
// Checked on 23/11: the first results answer the phrase.
examples: [
'isolant à base de champignon',
'textile qui change de couleur',
'verre qui devient opaque',
'alternative au plastique pour emballage'
],
suggestionsLabel: 'Suggestions',
suggestionsOne: '1 suggestion, flèches haut et bas pour choisir',
suggestionsMany: n => `${n} suggestions, flèches haut et bas pour choisir`
},
en: {
placeholder: 'Describe the material you are looking for',
loading: 'Loading…',
end: 'End of results',
helpLabel: 'Search help',
help: 'Describe in a few words the material, its use or the effect you are looking for.',
examplesIntro: 'For example:',
examples: [
'mushroom-based insulation',
'colour-changing textile',
'glass that turns opaque',
'plastic alternative for packaging'
],
suggestionsLabel: 'Suggestions',
suggestionsOne: '1 suggestion, use up and down arrows to choose',
suggestionsMany: n => `${n} suggestions, use up and down arrows to choose`
}
}
// Texts of the page language, English by default.
export function searchTexts () {
const lang = (window.drupalDecoupled && window.drupalDecoupled.lang_code) || 'en'
return TEXTS[lang] || TEXTS.en
}
@@ -135,7 +135,9 @@ export default {
commit('resetInfos') commit('resetInfos')
// Invalidate any in-flight response from a previous search. // Invalidate any in-flight response from a previous search.
commit('incrementSearchId') commit('incrementSearchId')
if (state.keys || state.terms.length) { // keys is an array, always truthy: test its length, otherwise the
// title of the page was empty without a search (F4).
if (state.keys.length) {
this.commit('Common/setPagetitle', state.keys.join(', ')) this.commit('Common/setPagetitle', state.keys.join(', '))
} else { } else {
this.commit('Common/setPagetitle', 'Base') this.commit('Common/setPagetitle', 'Base')