drafted materio_sapi search block vue integration

This commit is contained in:
2019-05-31 15:01:54 +02:00
parent ea2fd59c63
commit a48b7262eb
29 changed files with 758 additions and 195 deletions

View File

@@ -5,6 +5,14 @@ materio_sapi.search_autocomplete:
_format: json
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'

View File

@@ -0,0 +1,84 @@
<?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 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);
// $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;
}
}

View File

@@ -58,13 +58,8 @@ class FormAutocomplete extends ControllerBase {
// @see hook_search_api_results_TAG_alter()
$query->addTag('materio_sapi_autocomplete');
// Execute the search.
$results = $query->execute();
// echo "Result count: {$results->getResultCount()}\n";
// $ids = implode(', ', array_keys($results->getResultItems()));
// echo "Returned IDs: $ids.\n";
// $items = $results->getResultItems();
// \Drupal::logger('materio_sapi')->notice($results->getResultCount());
// \Drupal::logger('materio_sapi')->notice(implode(', ', array_keys($items)));

View File

@@ -30,12 +30,19 @@ class MaterioSapiSearchForm extends FormBase {
'#weight' => '0',
'#attributes' => [
"placeholder" => $this->t('Search'),
"@keyup" => "keyup",
"@keyup.enter" => "submit",
"v-model" => "typed"
],
'#autocomplete_route_name' => 'materio_sapi.search_autocomplete',
];
$form['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Search'),
'#attributes' => [
'@click.prevent' => "submit",
]
];
return $form;

File diff suppressed because one or more lines are too long

View File

@@ -1,7 +1,10 @@
import Vue from 'vue'
import store from 'vuejs/store'
import VUserBlock from 'vuejs/components/User/UserBlock'
import VUserBlock from 'vuejs/components/Block/UserBlock'
import VMainContent from 'vuejs/components/Content/MainContent'
import VSearchBlock from 'vuejs/components/Block/SearchBlock'
import { mapState } from 'vuex'
@@ -12,9 +15,8 @@ import 'theme/assets/styles/main.scss'
var MaterioTheme = function(){
var v_user_block, v_main_content;
// var _is_front = drupalSettings.path.isFront;
var _v_user_block, _v_main_content, _v_search_block;
var _is_front = drupalSettings.path.isFront;
console.log('drupalSettings', drupalSettings);
@@ -30,15 +32,20 @@ import 'theme/assets/styles/main.scss'
function initVues(){
initUserVBlock()
initVMainContent()
initVSearchBlock()
}
function initUserVBlock(){
let mount_point = drupalSettings.user.uid !== 0 ? '#block-userblock' : '#block-userlogin';
let props = {
title: ""
title: "",
form:""
};
switch (mount_point) {
case '#block-userlogin':
// let $form = document.getElementById('user-login-form');
// console.log('login form html', $form);
// props.form = $form.outerHTML
let $block = document.querySelector(mount_point);
props = {
title: $block.querySelector('h2').textContent,
@@ -63,13 +70,13 @@ import 'theme/assets/styles/main.scss'
}
// console.log(props);
v_user_block = new Vue({
_v_user_block = new Vue({
store,
computed: {
...mapState({
isloggedin: state => state.User.isloggedin
})
},
// computed: {
// ...mapState({
// isloggedin: state => state.User.isloggedin
// })
// },
created () {
if(drupalSettings.user.uid !== 0){
this.$store.commit('User/setUid', drupalSettings.user.uid)
@@ -78,20 +85,44 @@ import 'theme/assets/styles/main.scss'
},
render: h => h(VUserBlock, {props:props})
}).$mount(mount_point)
console.log('initUserVBlock', v_user_block);
// console.log('initUserVBlock', _v_user_block);
}
function initVMainContent(){
let $main_content = document.querySelector('#main-content')
console.log('main-content', $main_content);
// console.log('main-content', $main_content);
let main_html = $main_content.innerHTML
v_main_content = new Vue({
_v_main_content = new Vue({
store,
render: h => h(VMainContent, {props:{html:main_html}})
}).$mount('#main-content')
// console.log('initTestVContent', v_test_content);
}
function initVSearchBlock(){
// console.log('initVSearchBlock');
let id = "block-materiosapisearchblock"
let $search_block = document.getElementById(id)
var 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{
// else create the empty block to fill it later with async data
$search_block = document.createElement('div')
$search_block.setAttribute('id', id)
let $region = document.getElementById('content-top');
$region.appendChild($search_block);
}
// in any case create the vue
_v_search_block = new Vue({
store,
render: h => h(VSearchBlock, {props:{blockid:id, formhtml:formhtml}})
}).$mount('#'+id)
}
init()
} // end MaterioTheme()

View File

@@ -131,6 +131,14 @@ aside.messages{
padding: 0;
}
// content top
#materio-sapi-search-form{
.form-item, input.button{
display: inline-block;
}
}
// front
article.node--type-frontpage{
.node__content{

View File

@@ -0,0 +1,44 @@
{#
/**
* @file
* Theme override to display a block.
*
* Available variables:
* - plugin_id: The ID of the block implementation.
* - label: The configured label of the block if visible.
* - configuration: A list of the block's configuration values.
* - label: The configured label for the block.
* - label_display: The display settings for the label.
* - provider: The module or other provider that provided this block plugin.
* - Block plugin specific settings will also be stored here.
* - content: The content of this block.
* - attributes: array of HTML attributes populated by modules, intended to
* be added to the main container tag of this template.
* - id: A valid HTML ID and guaranteed unique.
* - title_attributes: Same as attributes, except applied to the main title
* tag that appears in the template.
* - title_prefix: Additional output populated by modules, intended to be
* displayed in front of the main title tag that appears in the template.
* - title_suffix: Additional output populated by modules, intended to be
* displayed after the main title tag that appears in the template.
*
* @see template_preprocess_block()
*/
#}
{%
set classes = [
'block',
'block-' ~ configuration.provider|clean_class,
'block-' ~ plugin_id|clean_class,
]
%}
<div{{ attributes.addClass(classes) }}>
{{ title_prefix }}
{% if label %}
<h2{{ title_attributes }}>{{ label }}</h2>
{% endif %}
{{ title_suffix }}
{% block content %}
{{ content }}
{% endblock %}
</div>

View File

@@ -66,11 +66,9 @@
</aside>
{% endif %}
{% if page.content_top %}
<div class="content-top">
{{ page.content_top }}
</div>
{% endif %}
<div id="content-top">
{{ page.content_top }}
</div>
<div id="main-content">
{{ page.content|without('messages') }}

View File

@@ -0,0 +1,13 @@
import axios from 'axios'
// https://github.com/alvar0hurtad0/drupal-vuejs-todo/blob/master/frontend/src/api/axiosInterceptor.js
// console.log('drupalSettings', drupalSettings);
export const MSAPI = axios.create({
baseURL: window.location.origin + '/' + drupalSettings.path.pathPrefix + `materio_sapi`,
withCredentials: true,
headers: {
"Content-Type": "application/json"
}
})

View File

@@ -0,0 +1,65 @@
<template v-slot="default">
<div v-bind:id="blockid">
<SearchForm
v-if="displayform"
v-bind:form="form"></SearchForm>
</div>
</template>
<script>
import SearchForm from 'vuejs/components/Form/SearchForm'
import { mapState, mapActions } from 'vuex'
import { MSAPI } from 'vuejs/api/msapi-axios'
export default {
props: ['blockid', 'formhtml'],
data(){
return {
form: null
}
},
computed: {
...mapState({
canSearch: state => state.User.canSearch
}),
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(){
MSAPI.get(`/search_form`)
.then(({data}) => {
console.log("getSearchForm");
this.form = data.rendered
})
.catch(( error ) => {
console.warn('Issue with get searchform', error)
})
}
},
components: {
SearchForm
}
}
</script>
<style lang="scss" scoped>
</style>

View File

@@ -0,0 +1,88 @@
<script>
import Vue from 'vue'
import { MSAPI } from 'vuejs/api/msapi-axios'
export default {
data() {
return {
template: null,
typed: ""
}
},
props: ['form'],
methods: {
keyup() {
console.log("search typed", this.typed);
},
submit() {
console.log("search clicked");
}
},
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).render
}
},
beforeUpdate() {
console.log('SearchForm beforeUpdate');
if(this._props.form){
console.log('SearchForm beforeUpdate if this._props.form ok');
this.template = Vue.compile(this._props.form).render
}
},
mounted(){
console.log('SearchForm mounted');
// Drupal.attachBehaviors(this.$el);
},
updated(){
console.log('SearchForm updated');
// Drupal.attachBehaviors(this.$el);
},
render(h) {
console.log('searchForm render');
if(!this.template){
return h('span', 'Loading ...')
}else{
return this.template()
}
}
}
// searchform: (resolve, reject) => (
// MSAPI.get(`/search_form`)
// .then(({data}) => {
// // console.log("materiosapisearchform", data);
// resolve({
// data() {
// return {
// typed:""
// }
// },
// methods: {
// keyup() {
// console.log("search typed", this.typed);
// },
// submit() {
// console.log("search clicked");
// }
// },
// mounted() {
// Drupal.attachBehaviors(this.$el);
// },
// template: data.rendered
// })
// })
// .catch(( error ) => {
// console.warn('Issue with get searchform', error)
// Promise.reject(error)
// })
//
// )
</script>
<style lang="scss" scoped>
</style>

View File

@@ -36,6 +36,7 @@ export default {
userLogout: 'User/userLogout'
}),
onLogout () {
console.log('UserTools onLogout');
this.userLogout()
}
}

View File

@@ -13,7 +13,8 @@ export default {
token: null,
logout_token: null,
isloggedin: false,
isAdmin: false
isAdmin: false,
canSearch: false
},
// getters
@@ -38,25 +39,35 @@ export default {
state.uuid = data.uuid[0].value
},
setRoles (state, roles) {
console.log("User setRoles", roles);
state.roles = []
for (var i = 0; i < roles.length; i++) {
state.roles.push(roles[i].target_id)
}
if(state.roles.indexOf('admin') != -1){
console.log('is admin');
// check if admin
if(state.roles.indexOf('admin') != -1 || state.roles.indexOf('root') != -1){
// console.log('is admin');
state.isAdmin = true
}
// check if has access to search
if(state.roles.indexOf('adherent') != -1){
// console.log('is admin');
state.canSearch = true
}
},
setLoggedOut (state) {
console.log("setLoggedOut state", state);
state.uid= null
state.mail = ''
state.token = null
state.isloggedin = false
state.logout_token = null
if (state.isAdmin){
window.location.reload(true);
}
state.asAdmin = false
state.canSearch = false
}
},
@@ -96,34 +107,19 @@ export default {
if(data.roles){
commit('setRoles', data.roles)
}
// JSONAPI.get(`/user/user/${state.uuid}?include=roles`)
// .then(({ data }) => {
// console.log('user JSONAPI getUser data', data)
// })
// .catch(( error ) => {
// console.warn('Issue with getUser', error)
// Promise.reject(error)
// })
})
.catch(( error ) => {
console.warn('Issue with getUser', error)
Promise.reject(error)
})
},
// checkLoginRole ({ commit, state }){
// console.log('checkLoginRole', state.roles, state.roles.indexOf('admin'))
// if(state.roles.indexOf('admin') != -1){
// console.log('is admin')
// window.
// }
// },
userLogout ({ commit, state }) {
let credentials = qs.stringify({
token: state.token
})
REST.post('/user/logout', credentials)
.then((resp) => {
console.log('resp', resp)
console.log('userLogout resp', resp)
commit('setLoggedOut')
})
.catch(( error ) => {