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
This commit is contained in:
2026-11-17 20:50:21 +01:00
co-authored by Claude Opus 5.5
parent 7786c2cf71
commit b73057f453
15 changed files with 77 additions and 293 deletions
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
@@ -1,79 +1,21 @@
<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 {
// formhtml: HTML of the former Drupal form, still passed by main.js, no
// longer used: the form is a Vue component (F1).
props: ['blockid', 'formhtml'],
data(){
return {
form: null
}
},
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 (F2).
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">