4 Commits
Author SHA1 Message Date
bachirandClaude Opus 5.5 54e7e28046 materiotheme: tab title from the search, safe terms of old URLs (F3)
- Base.vue: the browser tab shows the phrase searched (vue-meta), « Base »
  without a search.
- terms of an old or edited URL parsed without throwing: malformed JSON
  is ignored.
- Production build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
2026-11-17 21:14:09 +01:00
bachirandClaude Opus 5.5 fca4be3155 Remove the former search form, filters and SlimSelect (F2)
- materio_sapi: MaterioSapiSearchForm, AjaxSearchForm and the
  /materio_sapi/search_form route removed, with the fieldset legend hook
  they needed. The search block is only the place where the Vue field
  mounts (placement and access unchanged).
- materiotheme: filters removed from the search store and Base.vue (the
  parameter of former URLs is ignored), formhtml removed from main.js and
  SearchBlock.vue, filter styles and SlimSelect import removed.
- slim-select uninstalled, with its postinstall patch step.
- Production build.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
2026-11-17 21:11:18 +01:00
bachirandClaude Opus 5.5 b73057f453 materiotheme: search field as a Vue form, one phrase (F1)
- SearchForm.vue: one search field (150 characters, like the backend) and
  a button; Enter and button submit the same way; route base with keys
  only (no more terms nor filters). Same ids and classes as the former
  Drupal form, so main.scss applies.
- SearchBlock.vue: no more fetching nor Vue.compile of the Drupal form.
- Base.vue: aria-live on the result message, announced by screen readers.
- Production build (npm run prod).

Suggestions in the field come back in F7 (they came from the jQuery UI
autocomplete of the Drupal form).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
2026-11-17 20:50:21 +01:00
bachirandClaude Opus 5.5 7786c2cf71 materio_sapi: neighbours cut relative to the search, OR query as fallback (H6)
- ScoreCut: the kNN search scores every visible node; keep the ones above
  the mean of this search by more than 2 standard deviations. A fixed
  threshold meant nothing (at 0.7, « bois » 664 nodes, « wood » 4 671);
  with k = 2, 373 and 382. Exact matches stay first.
- OR query off (OR_WITH_KNN), kept as the fallback when there are no
  neighbours: model stopped, slow or switched off, term chosen in the
  autocomplete.
- S4: 355 results (1 104), same exact matches; S5: 248 (3 338), better
  top results, 0.27 s instead of 1.3 s.
- Message « X exact result(s) out of N relevant result(s) for "…" », French
  text added by materio_sapi_update_11001 (translations live in the DB).
- ScoreCutTest.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01ShDspHaZGwHoRZCsPBJzsM
2026-11-17 19:56:53 +01:00
33 changed files with 295 additions and 715 deletions
-9
View File
@@ -7,7 +7,6 @@
"": {
"name": "materio.com",
"version": "1.1.0",
"hasInstallScript": true,
"license": "MIT",
"dependencies": {
"axios": "^0.21.0",
@@ -59,7 +58,6 @@
"mini-css-extract-plugin": "^1.3.1",
"querystring-es3": "^0.2.1",
"sass-loader": "^10.1.0",
"slim-select": "^2.11.0",
"style-loader": "^2.0.0",
"uglify-es": "^3.3.9",
"url-loader": "^4.1.1",
@@ -11061,13 +11059,6 @@
"url": "https://github.com/chalk/slice-ansi?sponsor=1"
}
},
"node_modules/slim-select": {
"version": "2.11.0",
"resolved": "https://registry.npmjs.org/slim-select/-/slim-select-2.11.0.tgz",
"integrity": "sha512-Y0FEJKIPBy8ax7jArUxICxtKAnhX8GH7ydaFhcrYH7OznfpvxCe8uU2etyuRPKhE23c2LhT2GROFvZzGVplA0g==",
"dev": true,
"license": "MIT"
},
"node_modules/snapdragon": {
"version": "0.8.2",
"resolved": "https://registry.npmjs.org/snapdragon/-/snapdragon-0.8.2.tgz",
+1 -3
View File
@@ -9,8 +9,7 @@
"lint": "eslint --ext .js,.vue src",
"lint:fix": "eslint --ext .js,.vue src --fix",
"test": "jest --config test/jest.config.js",
"test:debug": "node --inspect node_modules/.bin/jest --runInBand --config test/jest.config.js",
"postinstall": "patch --forward node_modules/slim-select/package.json < patches/slimselect-export-css.patch"
"test:debug": "node --inspect node_modules/.bin/jest --runInBand --config test/jest.config.js"
},
"keywords": [
"Vue",
@@ -68,7 +67,6 @@
"mini-css-extract-plugin": "^1.3.1",
"querystring-es3": "^0.2.1",
"sass-loader": "^10.1.0",
"slim-select": "^2.11.0",
"style-loader": "^2.0.0",
"uglify-es": "^3.3.9",
"url-loader": "^4.1.1",
@@ -0,0 +1,44 @@
<?php
/**
* @file
* Install, update and uninstall functions for materio_sapi.
*/
declare(strict_types=1);
/**
* Source of the search message (H6) and its French translation.
*
* Interface translations live in the database, not in the repository: the
* update brings the French text to every site.
*/
function materio_sapi_search_infos_strings(): array {
return [
'source' => '@exactmatchcount exact result(s) out of @count relevant result(s) for “@keys”',
'fr' => '@exactmatchcount résultat(s) exact(s) sur @count résultat(s) pertinent(s) pour « @keys »',
];
}
/**
* Adds the French translation of the new search message (H6).
*/
function materio_sapi_update_11001(): string {
if (!\Drupal::moduleHandler()->moduleExists('locale')) {
return 'locale is off: nothing to translate.';
}
$strings = materio_sapi_search_infos_strings();
$storage = \Drupal::service('locale.storage');
$source = $storage->findString(['source' => $strings['source'], 'context' => '']);
if (!$source) {
$source = $storage->createString(['source' => $strings['source'], 'context' => ''])->save();
}
$storage->createTranslation([
'lid' => $source->lid,
'language' => 'fr',
'translation' => $strings['fr'],
'customized' => LOCALE_CUSTOMIZED,
])->save();
_locale_refresh_translations(['fr'], [$source->lid]);
return 'French translation of the search message added.';
}
@@ -8,7 +8,6 @@
use Drupal\Core\Routing\RouteMatchInterface;
use Solarium\QueryType\Select\Query\Query;
use Drupal\search_api\Query\QueryInterface;
use Drupal\Core\Template\Attribute;
/**
* Implements hook_help().
@@ -51,24 +50,6 @@ function materio_sapi_search_api_solr_query_alter(Query $solarium_query, QueryI
}
/**
* Prepares variables for fieldset element templates.
*
* Default template: fieldset.html.twig.
*
* @param array $variables
* An associative array containing:
* - element: An associative array containing the properties of the element.
* Properties used: #attributes, #children, #description, #id, #title,
* #value.
*/
function materio_sapi_preprocess_fieldset(&$variables) {
if (isset($variables['element']['#legend_attributes'])) {
$variables['legend']['attributes'] = new Attribute($variables['element']['#legend_attributes']);
}
}
// ? https://happyculture.coop/blog/drupal-8-declarer-un-champ-extrafield-calcule-computed-field
// ? https://fivejars.com/blog/entity-basefielddefinitions-fields-examples-drupal-8
/**
@@ -6,22 +6,6 @@ materio_sapi.search_autocomplete:
requirements:
_permission: 'access materio search'
materio_sapi.search_form:
path: '/materio_sapi/search_form'
defaults:
_controller: '\Drupal\materio_sapi\Controller\AjaxSearchForm::getForm'
_format: json
requirements:
_permission: 'access materio search'
# materio_sapi.materio_sapi_search_form:
# path: '/materio_sapi/form/materio_sapi_search'
# defaults:
# _form: '\Drupal\materio_sapi\Form\MaterioSapiSearchForm'
# _title: 'MaterioSapiSearchForm'
# requirements:
# _access: 'TRUE'
materio_sapi.getresults:
path: '/materio_sapi/getresults'
defaults:
@@ -1,92 +0,0 @@
<?php
// https://www.qed42.com/blog/autocomplete-drupal-8
// https://www.drupal.org/docs/8/modules/search-api/developer-documentation/executing-a-search-in-code
namespace Drupal\materio_sapi\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormBuilder;
use Drupal\Core\Form\FormState;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\core\render\RenderContext;
/**
* Defines a route controller for entity autocomplete form elements.
*/
class AjaxSearchForm extends ControllerBase {
/**
* The built form array.
*
* @var array
*/
protected $form_builded;
/**
* The form builder.
*
* @var \Drupal\Core\Form\FormBuilder
*/
protected $formBuilder;
/**
* Construct.
*/
public function __construct(FormBuilder $formBuilder) {
$this->formBuilder = $formBuilder;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('form_builder')
);
}
private function getFormDefinition(){
$language = \Drupal::languageManager()->getCurrentLanguage()->getId();
\Drupal::logger('materio_sapi')->notice($language);
// $form_state = new FormState();
$this->form_builded = $this->formBuilder->getForm('Drupal\materio_sapi\Form\MaterioSapiSearchForm', $language);
}
/**
* Handler for getform request.
*/
public function getForm(Request $request) {
$this->getFormDefinition();
// $rendered = render($this->form_builded);
$rendered = \Drupal::service('renderer')->render($this->form_builded);
// $form_builded = $this->form_builded;
// $rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($form_builded) {
// return render($form_builded);
// });
$data = [
'rendered' => $rendered,
// '#cache' => [
// 'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
// 'tags' => [
// 'materio_sapi-search_form-cache',
// ]
// ]
];
$response = new JsonResponse();
$response->setData($data);
// $response = new CacheableJsonResponse($data);
// $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
return $response;
}
}
@@ -10,6 +10,7 @@ use Drupal\Component\Utility\Unicode;
use Drupal\materio_ai\Exception\ModelPausedException;
use Drupal\materio_sapi\KeywordText;
use Drupal\materio_sapi\RankFusion;
use Drupal\materio_sapi\ScoreCut;
use Drupal\search_api\Entity\Index;
// https://drupal.stackexchange.com/questions/225008/programatically-use-search-api
@@ -91,9 +92,27 @@ class Base extends ControllerBase {
public const REFERENCE_PATTERN = '/\\b[WTRPCMFGSO]\\d{4}\\b/iu';
/**
* Most neighbours asked to Solr (kNN topK), H5. Tail cut in H6.
* Neighbours asked to Solr (kNN topK): every visible node (8 073 for an
* anonymous visitor in 2026), so that ScoreCut sees the whole distribution
* of the scores (H6). 0.3 to 0.6 s measured locally.
*/
public const KNN_LIMIT = 200;
public const KNN_LIMIT = 20000;
/**
* Standard deviations above the mean kept by ScoreCut (H6, option f, k = 2
* on trial since 17/11).
*/
public const KNN_SIGMA = 2.0;
/**
* Whether the OR query is merged with the neighbours (H3, H5).
*
* Off on trial since 17/11 (H6): on a phrase it matched about 40 % of the
* catalogue. Kept: it still runs when there are no neighbours (model
* stopped, slow or switched off, term chosen in the autocomplete), so that
* the search answers as before.
*/
public const OR_WITH_KNN = FALSE;
/**
* Number of neighbours found, for the response tuning of H6.
@@ -178,12 +197,14 @@ class Base extends ControllerBase {
$exact += $this->andQuery($keys, $lang);
}
$this->exactematch_count = count($exact);
$or = $this->orQuery($keys, $lang);
// Exact matches first, then the OR query and the neighbours merged (H5).
// Exact matches first, then the neighbours that stand out (H6), merged
// with the OR query when it is on (H5). No neighbours: the OR query alone.
$neighbours = $this->neighbours($lang);
$or = ($neighbours === NULL || self::OR_WITH_KNN) ? $this->orQuery($keys, $lang) : [];
$neighbours = $neighbours === NULL ? [] : ScoreCut::aboveMean($neighbours, self::KNN_SIGMA);
$this->knn_count = count($neighbours);
$nids = RankFusion::fuse(array_keys($exact), [array_keys($or), array_keys($neighbours)]);
$nids = RankFusion::fuse(array_keys($exact), array_filter([array_keys($or), array_keys($neighbours)]));
$uuids = array_column($exact + $or, 1, 0) + $this->uuids(array_diff(array_keys($neighbours), array_keys($exact + $or)));
$this->results = [
@@ -196,31 +217,33 @@ class Base extends ControllerBase {
* Nodes closest in meaning to the phrase (materio_ai, Solr kNN).
*
* Not for a term chosen in the autocomplete (direct search) nor without
* the materio_ai service. On a model or Solr error, or past the delay of
* QueryEmbedder (1 s), the keyword results stand alone, with no message:
* the search answers as before H5.
* the materio_ai service. On a model or Solr error, past the delay of
* QueryEmbedder (1 s), or with materio_ai switched off, the keyword
* results stand alone, with no message: the search answers as before H5.
*
* @return array<int, float>
* Scores keyed by nid, best first.
* @return array<int, float>|null
* Scores of every visible node keyed by nid, best first; NULL when there
* are no neighbours to use.
*/
private function neighbours(string $lang): array {
private function neighbours(string $lang): ?array {
if ($this->terms || !\Drupal::hasService('materio_ai.neighbour_search')) {
return [];
return NULL;
}
// References are keywords: they mean nothing to the model.
$phrase = trim(preg_replace(self::REFERENCE_PATTERN, ' ', $this->phrase) ?? '');
if ($phrase === '') {
return [];
return NULL;
}
try {
return \Drupal::service('materio_ai.neighbour_search')->search($phrase, $lang, self::KNN_LIMIT);
// Empty when materio_ai is switched off.
return \Drupal::service('materio_ai.neighbour_search')->search($phrase, $lang, self::KNN_LIMIT) ?: NULL;
}
catch (\Throwable $e) {
// Paused model: its failure was logged when it happened.
if (!$e instanceof ModelPausedException) {
\Drupal::logger('materio_sapi')->warning('Neighbour search failed, keyword results only: @message', ['@message' => $e->getMessage()]);
}
return [];
return NULL;
}
}
@@ -460,13 +483,14 @@ class Base extends ControllerBase {
// $resp['count'] = $this->results->getResultCount();
$resp['count'] = count($this->results['nids']);
$resp['exactematch_count'] = $this->exactematch_count;
$resp['infos'] = t('The search found @exactmatchcount exact match result(s) for @count total result(s) with', array(
"@exactmatchcount" => $resp['exactematch_count'],
"@count" => $resp['count']
));
$resp['infos'] .= t(' keywords @keys', array(
"@keys" => $this->phrase
));
// Relevant: exact matches and neighbours that stand out (H6); the
// count no longer depends on an arbitrary limit. French text added by
// materio_sapi_update_11001().
$resp['infos'] = t('@exactmatchcount exact result(s) out of @count relevant result(s) for “@keys”', [
'@exactmatchcount' => $resp['exactematch_count'],
'@count' => $resp['count'],
'@keys' => $this->phrase,
]);
// $resp['options'] = $this->query->getOptions();
// $uuids = [];
@@ -1,151 +0,0 @@
<?php
namespace Drupal\materio_sapi\Form;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Class MaterioSapiSearchForm.
*/
class MaterioSapiSearchForm extends FormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'materio_sapi_search_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$lang = \Drupal::languageManager()->getCurrentLanguage()->getId();
$keys = \Drupal::request()->get('keys');
$term = \Drupal::request()->get('term');
$filters = \Drupal::request()->get('filters');
$form['#cache'] = array(
'contexts' => array(
'url.query_args:keys',
'url.query_args:term',
'url.query_args:filters',
),
);
$form['search'] = [
'#type' => 'textfield',
// '#title' => $this->t('Search'),
'#maxlength' => 150,
'#size' => 25,
'#weight' => '0',
'#attributes' => [
"placeholder" => $this->t('Search'),
// "@keyup" => "keyup",
// "@keyup.enter" => "submit",
"v-model" => "typed",
"v-focus" => "",
// "v-on:select" => "typed",
],
'#autocomplete_route_name' => 'materio_sapi.search_autocomplete',
];
$form['searchautocomplete'] = [
'#type' => 'hidden',
'#attributes' => [
"v-model" => "autocomplete"
],
];
// $filters_array = [];
$filters_classes = [];
if($filters){
$filters_array = explode(',',$filters);
$filters_classes[] = 'open';
}
$form['filters'] = [
'#type' => 'fieldset',
'#title' => t('filters'),
'#legend_attributes' => [
"class" => ["test-attribute"],
'@click.prevent' => "onClickFilters",
],
'#attributes' => [
"class" => $filters_classes
]
];
// $form['filters']['switch'] = [
// '#type' => "label",
//
// ]
$query = \Drupal::entityQuery('taxonomy_term')
->condition('vid', "assisted_research")
->accessCheck(TRUE)
->sort('field_weight', 'ASC');
$tids = $query->execute();
$terms = \Drupal\taxonomy\Entity\Term::loadMultiple($tids);
foreach ($terms as $tid => $term) {
if($term->hasTranslation($lang)){
$term = \Drupal::service('entity.repository')->getTranslationFromContext($term, $lang);
}
$options = array($term->getName());
$childs = $term->get('field_terms')->getValue();
$selected = null;
foreach ($childs as $child) {
$child_term = \Drupal\taxonomy\Entity\Term::load($child['target_id']);
if($child_term->hasTranslation($lang)){
$child_term = \Drupal::service('entity.repository')->getTranslationFromContext($child_term, $lang);
}
$options[$child_term->id()] = $child_term->getName();
if (isset($filters_array) && in_array($child_term->id(), $filters_array)) {
$selected = $child_term->id();
}
}
$form['filters']['filter-'.$tid] = array(
'#type' => 'select',
// '#title' => $term->getName(),
// '#multiple' => true,
'#options' => $options,
'#value' => $selected
);
}
$form['submit'] = array(
'#type' => 'button',
// '#src' => '',//drupal_get_path('module', 'materio_search_api') . '/images/search.png',
'#value' => t('Search'),
// '#prefix' => '<div class="search-btn-wrapper">',
// '#suffix'=> '</div>',
'#attributes' => [
'title' => t('Search'),
'@click.prevent' => "submit",
]
);
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
parent::validateForm($form, $form_state);
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Display result.
foreach ($form_state->getValues() as $key => $value) {
\Drupal::messenger()->addStatus($key . ': ' . $value);
}
}
}
@@ -20,11 +20,16 @@ class MaterioSapiSearchBlock extends BlockBase {
* {@inheritdoc}
*/
public function build() {
$build = [];
// $build['materio_sapi_search_block']['#markup'] = 'Implement MaterioSapiSearchBlock.';
$form = \Drupal::formBuilder()->getForm('Drupal\materio_sapi\Form\MaterioSapiSearchForm');
$build['materio_sapi_search_block'] = $form;
return $build;
// Only a place in the page: the search field is a Vue component
// (materiotheme SearchForm.vue, F1) mounted on this block. Not empty,
// otherwise Drupal would not render the block.
return [
'placeholder' => [
'#type' => 'html_tag',
'#tag' => 'div',
'#attributes' => ['class' => ['materio-sapi-search-placeholder']],
],
];
}
/**
@@ -0,0 +1,44 @@
<?php
declare(strict_types=1);
namespace Drupal\materio_sapi;
/**
* Keeps the neighbours that stand out for this search (H6, option f).
*
* The kNN search scores every visible node, so each search has its own score
* distribution. A fixed threshold means nothing: the scale moves with the
* search and the language (at 0.7, « bois » kept 664 nodes and « wood »
* 4 671). A node is kept when its score is above the mean of this search by
* more than K standard deviations: with K = 2, « bois » 373 and « wood » 382,
* 150 to 500 nodes for one word, about 250 for a phrase (measured 17/11).
*/
final class ScoreCut {
/**
* Scores above mean + $k standard deviations, in their order.
*
* @param array<int, float> $scores
* Scores keyed by nid, best first, ideally of every visible node.
* @param float $k
* Number of standard deviations.
*
* @return array<int, float>
* The kept scores, keyed by nid.
*/
public static function aboveMean(array $scores, float $k): array {
$n = count($scores);
if ($n < 2) {
return $scores;
}
$mean = array_sum($scores) / $n;
$variance = 0.0;
foreach ($scores as $score) {
$variance += ($score - $mean) ** 2;
}
$limit = $mean + $k * sqrt($variance / $n);
return array_filter($scores, static fn ($score) => $score > $limit);
}
}
@@ -0,0 +1,47 @@
<?php
declare(strict_types=1);
namespace Drupal\Tests\materio_sapi\Unit;
use Drupal\materio_sapi\ScoreCut;
use Drupal\Tests\UnitTestCase;
use PHPUnit\Framework\Attributes\CoversClass;
use PHPUnit\Framework\Attributes\Group;
/**
* Tests the cut of the neighbours relative to the search (H6).
*/
#[CoversClass(ScoreCut::class)]
#[Group('materio_sapi')]
final class ScoreCutTest extends UnitTestCase {
/**
* Only the scores above mean + k standard deviations stay, in order.
*/
public function testAboveMean(): void {
// 98 scores at 0.6, then 0.9 and 0.8: mean 0.6045, deviation ≈ 0.0337.
$scores = [7 => 0.9, 3 => 0.8] + array_fill_keys(range(100, 197), 0.6);
$this->assertSame([7 => 0.9, 3 => 0.8], ScoreCut::aboveMean($scores, 2.0));
$this->assertSame([7 => 0.9], ScoreCut::aboveMean($scores, 7.0));
}
/**
* The same distribution shifted keeps the same nodes: no fixed threshold.
*/
public function testShiftedScale(): void {
$scores = [7 => 0.9, 3 => 0.8] + array_fill_keys(range(100, 197), 0.6);
$shifted = array_map(static fn ($s) => $s + 0.15, $scores);
$this->assertSame(array_keys(ScoreCut::aboveMean($scores, 2.0)), array_keys(ScoreCut::aboveMean($shifted, 2.0)));
}
/**
* Equal scores stand out from nothing; fewer than two scores are kept.
*/
public function testEdgeCases(): void {
$this->assertSame([], ScoreCut::aboveMean([1 => 0.7, 2 => 0.7, 3 => 0.7], 2.0));
$this->assertSame([5 => 0.8], ScoreCut::aboveMean([5 => 0.8], 2.0));
$this->assertSame([], ScoreCut::aboveMean([], 2.0));
}
}
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
@@ -381,12 +381,9 @@ export let _v_sitebranding_block, _v_user_block, _v_header_menu, _v_language_swi
// console.log('router beforeEach to ', to)
const id = 'block-materiosapisearchblock'
let $search_block = document.getElementById(id)
let formhtml = null
if ($search_block) {
// get the search form html to pass it as template to the vue
// we gain display speed vs async downloaded data
formhtml = $search_block.innerHTML
} else {
// The block is only a place in the page: the search form is the Vue
// component SearchForm (F1).
if (!$search_block) {
// else create the empty block to fill it later with async data
$search_block = document.createElement('div')
$search_block.setAttribute('id', id)
@@ -399,7 +396,7 @@ export let _v_sitebranding_block, _v_user_block, _v_header_menu, _v_language_swi
_v_search_block = new Vue({
store,
i18n,
render: h => h(VSearchBlock, { props: { blockid: id, formhtml: formhtml } })
render: h => h(VSearchBlock, { props: { blockid: id } })
}).$mount('#' + id)
}
function initVLeftContent () {
@@ -1,10 +1,6 @@
@use "sass:math";
@use "sass:color";
// @import '~slim-select/scss';
@import 'slim-select/styles';
$mdi-font-path: './mdi/fonts/';
@import './mdi/css/materialdesignicons.css';
@import './mdi/scss/variables';
@@ -641,72 +637,6 @@ header[role="banner"]{
}
}
fieldset#edit-filters{
grid-row: 2 / 2;
grid-column: 1 / span 2;
border: none;
padding: 0;
>legend{
line-height: 0.6;
padding-bottom: 0.2em;
width: 100%;
text-align: right;
span{
cursor: pointer;
font-size: 0.756em;
color: #8f8f8f;
}
}
> div.fieldset-wrapper{
height: 0;
overflow: hidden;
}
&.open >div.fieldset-wrapper{
height: auto;
overflow: visible;
}
.ss-main{
font-size: 0.756em;
.ss-single-selected{
border-radius: 0.7em;
&.ss-open-below{
border-radius: 0.7em 0.7em 0 0.7em;
}
height:1.5em;
border: none;
padding: 0 0.5em;
background-color: #eeeaea;
span.placeholder{
color: $color-main-text;
line-height: 1;
span.ss-disabled{
color: #8f8f8f;
}
}
span.ss-arrow span{
border-color: #b1adad;
}
}
.ss-content{
width:auto;
border: none;
border-radius: 0.7em 0 0.7em 0.7em;
&.ss-open{
box-shadow: 0 0 10px #ccc;
}
right: 0;
.ss-list{
max-height: none;
.ss-option{
white-space: nowrap;
text-align: right;
}
}
}
}
}
.button.form-submit{
grid-row: 1 / 1;
grid-column: 2 / 2;
@@ -1,79 +1,19 @@
<template v-slot="default">
<div v-bind:id="blockid">
<SearchForm
v-if="displayform"
v-bind:form="form"></SearchForm>
<SearchForm v-if="canSearch"></SearchForm>
</div>
</template>
<script>
import qs from 'querystring-es3'
import SearchForm from 'vuejs/components/Form/SearchForm'
import { mapState, mapActions } from 'vuex'
import MA from 'vuejs/api/ma-axios'
import { mapState } from 'vuex'
export default {
props: ['blockid', 'formhtml'],
data(){
return {
form: null
}
},
props: ['blockid'],
computed: {
...mapState({
canSearch: state => state.User.canSearch,
keys: state => state.Search.keys,
terms: state => state.Search.terms,
filters: state => state.Search.filters
}),
displayform(){
// console.log('computed displayform')
return this.canSearch && this.form
}
},
beforeMount() {
// console.log('SearchBlock beforeMount')
this.form = this.formhtml
},
watch: {
canSearch(new_value, old_value) {
// console.log('canSearch changed, old: '+old_value+", new: "+new_value)
if (new_value && !this.form) {
this.getSearchForm()
}
if (!new_value && this.form) {
this.form = null
}
}
},
methods: {
getSearchForm(){
console.log('getSearchForm')
// var urlParams = new URLSearchParams(window.location.search);
// var urlParamsKeys = urlParams.keys()
const params = {
keys: this.keys,
terms: this.terms, //JSON.stringify(this.terms),
filters: this.filters
}
console.log('Search getSearchForm params', params)
const q = qs.stringify(params)
MA.get(`/materio_sapi/search_form?`+q)
.then(({data}) => {
// console.log('getSearchForm')
// guard against unexpected response body (truncated / non json)
// which would crash Vue.compile(undefined) in SearchForm
if (typeof data.rendered !== 'string') {
console.warn('SearchBlock getSearchForm unexpected data', data)
return
}
this.form = data.rendered
})
.catch((error) => {
console.warn('Issue with get searchform', error)
})
}
canSearch: state => state.User.canSearch
})
},
components: {
SearchForm
@@ -1,241 +1,82 @@
<template>
<!-- One field for a phrase in natural language, one button (F1).
Same ids and classes as the former Drupal form, so main.scss applies. -->
<form
id="materio-sapi-search-form"
class="materio-sapi-search-form"
role="search"
@submit.prevent="submit"
>
<div class="form-item form-item-search">
<input
id="edit-search"
ref="input"
v-model="typed"
class="form-text"
type="search"
name="search"
:maxlength="maxLength"
:placeholder="$t('default.Search')"
:aria-label="$t('default.Search')"
enterkeyhint="search"
autocomplete="off"
autocapitalize="off"
spellcheck="false"
>
</div>
<input
type="submit"
class="button form-submit"
:value="$t('default.Search')"
:title="$t('default.Search')"
>
</form>
</template>
<script>
import Vue from 'vue'
import router from 'vuejs/route'
import { mapState } from 'vuex'
import SlimSelect from 'slim-select'
export default {
router,
props: ['form'],
data() {
data () {
return {
template: null,
typed: null,
autocomplete: [],
slimFilters: [],
$input: null
// basePath: drupalSettings.path.baseUrl + drupalSettings.path.pathPrefix
typed: '',
// Same limit as the backend (Base::MAX_PHRASE_LENGTH, H1).
maxLength: 150
}
},
computed: {
...mapState({
keys: state => state.Search.keys,
terms: state => state.Search.terms,
filters: state => state.Search.filters
keys: state => state.Search.keys
})
},
methods: {
submit() {
console.log("slim search submited", this.typed, this.autocomplete, this.filters, this.slimFilters)
// unfocus the text input to hide the keyboard on mobile device
this.$input.blur()
// New search is triggered by Base.vue with router (which will also fill the store)
// cleaning slimfilters
let filters = []
this.slimFilters.forEach((filter, index) => {
console.log('onsubmit foreach slimFilters', filter)
if(filter){
filters.push(filter)
}
})
// // this is just in case we landed in the page with filters in url params,
// // this.slimFilters is not filled but store/search filters is
// if(!filters.length){
// filters = this.filters
// }
console.log('Cleaning filters',this.slimFilters, this.filters, filters)
// push router
this.$router.push({name:'base', query:{
keys:this.typed,
// terms:this.autocomplete.join(','),
terms: JSON.stringify(this.autocomplete),
filters:filters.join(',')
}})
phraseFromKeys (keys) {
return keys && keys.length ? keys.join(', ') : ''
},
onAutoCompleteSelect(event, ui){
event.preventDefault();
console.log('autoCompleteSelect begining', this.typed, event, ui)
// split typed into tag list
var tag_list = this.typed.split(', ')
console.log('tag_list', tag_list)
// remove the last item as it is the first letters of autocomplete (like ma for marbre)
tag_list.pop()
// add in typed the label
tag_list.push(ui.item.label)
this.typed = tag_list.join(', ') + ', '
// check if item is not already in autocmplete
let add = true
this.autocomplete.forEach( (term) => {
if (term.value == ui.item.value) {
add = false
return
}
})
if (add) {
this.autocomplete.push(ui.item)
}
// we have to wait for typed watch to reset autocomplete before setting it
// setTimeout(function(){
// console.log('update autocomplete value after settimeout')
// this.autocomplete.push(ui.item)
// if (this.typed !== this.keys || this.autocomplete !== this.term) {
// this.submit()
// }
// }.bind(this), 1)
console.log('autoCompleteSelect end : this.autocomplete', this.autocomplete)
},
onSelectFiltersChange(index, info){
console.log('slim onSelectFiltersChange', index, info, this.slimFilters, this.filters)
this.slimFilters[index] = info.value
console.log(this.slimFilters);
},
onClickFilters(e){
console.log('onClickFilters legend', e)
e.target.closest('fieldset').classList.toggle('open')
// TODO: reset the filters oon close
}
},
directives: {
focus: {
// directive definition
inserted: function (el) {
// do not focus the input as it popup the keyboard on mobile device
// el.focus()
}
}
},
beforeMount() {
// console.log('SearchForm beforeMount')
if (this._props.form) {
// console.log('SearchForm beforeMount if this._props.form ok')
this.template = Vue.compile(this._props.form)
// https://github.com/vuejs/vue/issues/9911
this.$options.staticRenderFns = [];
this._staticTrees = [];
this.template.staticRenderFns.map(fn => (this.$options.staticRenderFns.push(fn)));
submit () {
const phrase = this.typed.replace(/\s+/g, ' ').trim()
// Hide the keyboard on mobile devices.
this.$refs.input.blur()
// Base.vue reacts to the route change and runs the search.
// Only the phrase: no more terms (F7) nor filters.
this.$router.push({ name: 'base', query: phrase ? { keys: phrase } : {} })
.catch(() => {})
}
},
watch: {
typed(n, o){
console.log(`watch typed changed o:(${typeof o})${o} | n:(${typeof n})${n}`, o, n)
// if (typeof n === 'string') {
// // remove terms from autocomplete if removed from typed
// const r = /,\s?$/ // remove last comma space
// let tag_list = n.replace(r,'').split(', ')
// }else{
// let tag_list = n
// }
// remove terms from autocomplete if removed from typed
if (typeof n !== 'string') {
return
}
const r = /,\s?$/ // remove last comma space
let tag_list = n.replace(r,'').split(', ')
console.log('watch typed tag_list', tag_list)
console.log('watch typed autocomplete before', this.autocomplete)
// Keep only the terms whose label is still present in the typed text.
// Filtering into a new array avoids skipping items when splicing during
// iteration (which left stale terms in autocomplete, corrupting `terms`).
this.autocomplete = this.autocomplete.filter(term => tag_list.indexOf(term.label) >= 0)
console.log('watch typed autocomplete after', this.autocomplete)
},
keys(n, o){
console.log('watch keys changed', o, n)
this.typed = n.length ? n.join(', ') + ', ' : ''
},
// terms(n, o){
// // if term change from store
// console.log('watch terms changed', o, n)
// this.autocomplete = n
// }
},
created() {
// fill component values with store values in case of direct page loading
console.log('SearchForm created, this.keys', this.keys)
this.typed = this.keys.length ? this.keys.join(', ') + ', ' : ''
this.autocomplete = this.terms
},
mounted(){
// console.log('SearchForm mounted')
Drupal.attachBehaviors(this.$el);
// Route the native form submission (Enter key) through the same submit()
// method as the button (@click.prevent="submit"). Without this, pressing
// Enter either triggers a native POST reload or only fills the jQuery UI
// autocomplete selection, so keys/terms sent to the backend differ from a
// button click and the search results are inconsistent.
// Note: when the autocomplete menu is open, jQuery UI handles Enter itself
// (selects the highlighted suggestion) and prevents this submit event, which
// is the intended behaviour.
this.$el.addEventListener('submit', (e) => {
e.preventDefault()
this.submit()
})
// get the search input
this.$input = this.$el.querySelector('#edit-search')
// // focus on input
// $input.focus()
// Catch the jquery ui events for autocmplete widget
jQuery(this.$input).on('autocompleteselect', this.onAutoCompleteSelect);
// customize the select filters
// http://slimselectjs.com/options
const selects = this.$el.querySelectorAll('select')
console.log('slim selects', selects);
let slim;
selects.forEach((selectElement, index) => {
console.log('slim selects forEach', selectElement, index);
// get the first option to make the placeholder then empty it
const placeholder_option = selectElement.querySelector('option:first-child')
// console.log('placeholder_option', placeholder_option);
const placeholder = placeholder_option.innerText
placeholder_option.removeAttribute("value")
placeholder_option.setAttribute("data-placeholder", true)
placeholder_option.innerHTML = ''
slim = new SlimSelect({
events:{
afterChange: (newval) => {
console.log('slim slimselect onchange', index, newval, this)
this.onSelectFiltersChange(index, newval[0])
}
},
select: selectElement,
placeholder: placeholder,
allowDeselect: true,
showSearch: false,
closeOnSelect: true
})
console.log('slim', slim);
// console.log('slimselect selected', slim, slim.selected(), index)
this.slimFilters[index] = slim.getSelected()[0];
})
console.log('slimSelect slimFilters after init', this.slimFilters)
},
render(h) {
// console.log('searchForm render')
if (!this.template) {
return h('span', $t('default.Loading…'))
} else {
return this.template.render.call(this)
// The store changes when a search starts from the URL or another link.
keys (n) {
this.typed = this.phraseFromKeys(n)
}
},
created () {
// Direct page load: the store already holds the keys of the URL.
this.typed = this.phraseFromKeys(this.keys)
}
}
</script>
<style lang="scss" scoped>
</style>
@@ -4,7 +4,8 @@
<span>{{ $t('default.Loading…') }}</span>
</div>
<div class="cards-list" v-else>
<aside class="search-info">
<!-- aria-live: screen readers announce the result message of each search (F1). -->
<aside class="search-info" aria-live="polite">
{{ searchinfos }}
</aside>
<div class="loading" v-if="!items.length & !noresults">
@@ -50,7 +51,8 @@ export default {
count: state => state.Search.count,
noresults: state => state.Search.noresults,
limit: state => state.Search.limit,
searchId: state => state.Search.searchId
searchId: state => state.Search.searchId,
keys: state => state.Search.keys
}),
// items is a sparse array (pages placed by offset); drop the holes left by
// pages that returned fewer results than the limit before rendering.
@@ -58,7 +60,23 @@ export default {
return this.items.filter(Boolean)
}
},
// Title of the browser tab: the phrase searched (F3).
metaInfo () {
return {
title: this.keys && this.keys.length ? this.keys.join(', ') : 'Base'
}
},
methods: {
// terms of an URL: a JSON list, possibly malformed in an old or edited
// link; never break the page for it (F3).
parseTerms (value) {
try {
const terms = JSON.parse(value)
return Array.isArray(terms) ? terms : []
} catch (e) {
return []
}
},
...mapActions({
newSearch: 'Search/newSearch',
nextPage: 'Search/nextPage'
@@ -86,16 +104,12 @@ export default {
if (params.has('terms')) {
console.log('Base created, has terms', params.get('terms'))
// this.$store.commit('Search/setTerms', params.get('terms').split(','))
this.$store.commit('Search/setTerms', JSON.parse(params.get('terms')))
this.$store.commit('Search/setTerms', this.parseTerms(params.get('terms')))
} else {
this.$store.commit('Search/reSetTerms')
}
if (params.has('filters')) {
this.$store.commit('Search/setFilters', params.get('filters').split(','))
} else {
this.$store.commit('Search/reSetFilters')
}
// The filters parameter of former URLs is ignored (F2).
this.newSearch()
},
@@ -108,15 +122,10 @@ export default {
// to.query.terms is a raw JSON string (see SearchForm.submit) and must be
// parsed like in created(), otherwise getResults() double-encodes it and
// the backend silently drops the terms (less relevant results).
this.$store.commit('Search/setTerms', JSON.parse(to.query.terms))
this.$store.commit('Search/setTerms', this.parseTerms(to.query.terms))
}else{
this.$store.commit('Search/reSetTerms')
}
if (to.query.hasOwnProperty('filters')) {
this.$store.commit('Search/setFilters', to.query.filters)
}else{
this.$store.commit('Search/reSetFilters')
}
if (to.query.hasOwnProperty('keys')) {
const r = /,\s?$/
let keys = to.query.keys.replace(r,'').split(', ')
@@ -17,7 +17,6 @@ export default {
state: {
keys: [],
terms: [],
filters: [],
uuids: [],
items: [],
offset: 0,
@@ -92,13 +91,6 @@ export default {
reSetTerms (state) {
state.terms = []
},
setFilters (state, filters) {
console.log('store search setFilters', filters)
state.filters = typeof filters === 'string' ? filters.split(',') : filters
},
reSetFilters (state) {
state.filters = []
},
setInfos (state, infos) {
state.infos = infos
},
@@ -169,10 +161,6 @@ export default {
limit: state.limit
}
console.log('search store getResults, params', params)
if (state.filters) {
console.log('getResults filters', state.filters)
params.filters = state.filters.join(',')
}
// console.log('Search getResults params', params)
const q = qs.stringify(params)
// * Qs.Stringify () Arrayformat: 'Repeat' : https://programmerall.com/article/31901061156/