Browse Source

handled home loading if not available in dom (if drupalSettings.path.isFront == false)

Bachir Soussi Chiadmi 5 years ago
parent
commit
082e011fbb

+ 1 - 0
composer.json

@@ -50,6 +50,7 @@
         "drupal/search_api_solr": "^3.0",
         "drupal/select_translation": "1.x-dev",
         "drupal/simplenews": "1.x-dev",
+        "drupal/subrequests": "^2.0",
         "drupal/telephone_formatter": "^1.0@beta",
         "drupal/telephone_validation": "^2.1",
         "drupal/ultimate_cron": "2.x-dev",

+ 101 - 1
composer.lock

@@ -4,7 +4,7 @@
         "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
         "This file is @generated automatically"
     ],
-    "content-hash": "94914ee080097da2be34ee7047311647",
+    "content-hash": "659326ced02c2fe78453f4b0f66d7e4e",
     "packages": [
         {
             "name": "alchemy/zippy",
@@ -9205,6 +9205,58 @@
                 "source": "https://git.drupalcode.org/project/state_machine"
             }
         },
+        {
+            "name": "drupal/subrequests",
+            "version": "2.2.0",
+            "source": {
+                "type": "git",
+                "url": "https://git.drupalcode.org/project/subrequests.git",
+                "reference": "8.x-2.2"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://ftp.drupal.org/files/projects/subrequests-8.x-2.2.zip",
+                "reference": "8.x-2.2",
+                "shasum": "2d1a3240849ab708ff4b1eeb09ec3f67e261a2e3"
+            },
+            "require": {
+                "drupal/core": "*",
+                "galbar/jsonpath": "^1.0"
+            },
+            "require-dev": {
+                "justinrainbow/json-schema": "^5.2"
+            },
+            "type": "drupal-module",
+            "extra": {
+                "branch-alias": {
+                    "dev-2.x": "2.x-dev"
+                },
+                "drupal": {
+                    "version": "8.x-2.2",
+                    "datestamp": "1555921985",
+                    "security-coverage": {
+                        "status": "covered",
+                        "message": "Covered by Drupal's security advisory policy"
+                    }
+                }
+            },
+            "notification-url": "https://packages.drupal.org/8/downloads",
+            "license": [
+                "GPL-2.0+"
+            ],
+            "authors": [
+                {
+                    "name": "Mateu Aguiló Bosch",
+                    "homepage": "https://www.drupal.org/user/550110",
+                    "email": "mateu.aguilo.bosch@gmail.com"
+                }
+            ],
+            "description": "Add a front controller that you can use to make subrequests.",
+            "homepage": "https://www.drupal.org/project/subrequests",
+            "support": {
+                "source": "https://git.drupalcode.org/project/subrequests"
+            }
+        },
         {
             "name": "drupal/synonyms",
             "version": "1.0.0-alpha1",
@@ -10379,6 +10431,54 @@
             ],
             "time": "2019-04-10T11:14:46+00:00"
         },
+        {
+            "name": "galbar/jsonpath",
+            "version": "1.0",
+            "source": {
+                "type": "git",
+                "url": "https://github.com/Galbar/JsonPath-PHP.git",
+                "reference": "d08d1efeadad3345257249e35e8cfd65f21256ae"
+            },
+            "dist": {
+                "type": "zip",
+                "url": "https://api.github.com/repos/Galbar/JsonPath-PHP/zipball/d08d1efeadad3345257249e35e8cfd65f21256ae",
+                "reference": "d08d1efeadad3345257249e35e8cfd65f21256ae",
+                "shasum": ""
+            },
+            "require": {
+                "php": ">=5.4"
+            },
+            "require-dev": {
+                "phpunit/phpunit": "~4.0",
+                "sami/sami": ">=3.3.0",
+                "satooshi/php-coveralls": ">=1.0.1"
+            },
+            "type": "library",
+            "autoload": {
+                "psr-0": {
+                    "JsonPath\\": "src/Skyscanner/",
+                    "Utilities\\": "src/Skyscanner/"
+                }
+            },
+            "notification-url": "https://packagist.org/downloads/",
+            "license": [
+                "Apache 2.0"
+            ],
+            "authors": [
+                {
+                    "name": "Alessio Linares",
+                    "email": "alessio.linares@skyscanner.net",
+                    "role": "Software Engineer"
+                }
+            ],
+            "description": "JSONPath implementation for querying and updating JSON objects",
+            "keywords": [
+                "json",
+                "jsonpath",
+                "path"
+            ],
+            "time": "2017-09-13T09:14:46+00:00"
+        },
         {
             "name": "giggsey/libphonenumber-for-php",
             "version": "8.10.12",

+ 1 - 3
config/sync/core.extension.yml

@@ -77,9 +77,6 @@ module:
   inline_entity_form: 0
   interval: 0
   jsonapi: 0
-  jsonrpc: 0
-  jsonrpc_core: 0
-  jsonrpc_discovery: 0
   kint: 0
   language: 0
   link: 0
@@ -125,6 +122,7 @@ module:
   search_api: 0
   search_api_db: 0
   search_api_solr: 0
+  search_api_solr_admin: 0
   select_translation: 0
   serialization: 0
   simplenews: 0

+ 2 - 2
config/sync/search_api.index.database.yml

@@ -8,8 +8,8 @@ dependencies:
     - taxonomy
     - search_api
   config:
-    - field.storage.node.body
     - field.storage.node.field_famille
+    - field.storage.node.body
     - field.storage.node.field_tags
     - field.storage.taxonomy_term.field_synonyms
     - field.storage.node.field_thesaurus
@@ -20,7 +20,7 @@ third_party_settings:
     commit_before_finalize: false
     commit_after_finalize: false
     multilingual:
-      limit_to_content_language: false
+      limit_to_content_language: true
       include_language_independent: true
     highlighter:
       maxAnalyzedChars: 51200

+ 2 - 0
config/sync/user.role.anonymous.yml

@@ -20,6 +20,8 @@ permissions:
   - 'create generique workflow_transition'
   - 'create migration workflow_transition'
   - 'create workflow workflow_transition'
+  - 'issue subrequests'
+  - 'restful get config_rest_resource'
   - 'subscribe to newsletters'
   - 'use text format wysiwyg'
   - 'view commerce_product'

+ 2 - 0
config/sync/user.role.authenticated.yml

@@ -26,9 +26,11 @@ permissions:
   - 'edit own chutier entities'
   - 'edit own composition entities'
   - 'edit own fil entities'
+  - 'issue subrequests'
   - 'manage own commerce_payment_method'
   - 'materio_jsonapi ownroles'
   - 'opt-in or out of matomo tracking'
+  - 'restful get config_rest_resource'
   - 'subscribe to newsletters'
   - 'use chutier'
   - 'use text format wysiwyg'

+ 7 - 23
web/modules/custom/materio_home/materio_home.routing.yml

@@ -1,23 +1,7 @@
-# materio_home.home:
-#   path: '/home'
-#   defaults:
-#     _controller: '\Drupal\materio_home\Controller\HomeController::home'
-#     _title: 'Home'
-#   requirements:
-#     _permission: 'access content'
-
-# materio_home.home_mobile:
-#   path: '/home_m'
-#   defaults:
-#     _controller: '\Drupal\materio_home\Controller\HomeController::home_mobile'
-#     _title: 'Home'
-#   requirements:
-#     _permission: 'access content'
-#
-# materio_home.home_mobileajax:
-#   path: '/home_m/ajax'
-#   defaults:
-#     _controller: '\Drupal\materio_home\Controller\HomeController::home_mobilejson'
-#     _title: 'Home'
-#   requirements:
-#     _permission: 'access content'
+materio_home.ajax_home:
+  path: 'materio_home/ajax/gethome'
+  defaults:
+    _controller: '\Drupal\materio_home\Controller\AjaxHomeController::getHome'
+    _title: 'ajaxGetHome'
+  requirements:
+    _permission: 'access content'

+ 106 - 0
web/modules/custom/materio_home/src/Controller/AjaxHomeController.php

@@ -0,0 +1,106 @@
+<?php
+
+namespace Drupal\materio_home\Controller;
+
+use Drupal\Core\Controller\ControllerBase;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Drupal\Core\Entity\EntityManagerInterface;
+use Drupal\language\ConfigurableLanguageManagerInterface;
+use Drupal\Core\Render\RendererInterface;
+use Drupal\Core\Entity\EntityTypeManagerInterface;
+use Drupal\Core\Cache\CacheableJsonResponse;
+use Drupal\Core\Cache\CacheableMetadata;
+use Drupal\Core\Url;
+use Drupal\core\render\RenderContext;
+
+/**
+ * Class AjaxHomeController.
+ */
+class AjaxHomeController extends ControllerBase {
+
+  /**
+   * Drupal\Core\Entity\EntityManagerInterface definition.
+   *
+   * @var \Drupal\Core\Entity\EntityManagerInterface
+   */
+  protected $entityManager;
+  /**
+   * Drupal\language\ConfigurableLanguageManagerInterface definition.
+   *
+   * @var \Drupal\language\ConfigurableLanguageManagerInterface
+   */
+  protected $languageManager;
+  /**
+   * Drupal\Core\Render\RendererInterface definition.
+   *
+   * @var \Drupal\Core\Render\RendererInterface
+   */
+  protected $renderer;
+  /**
+   * Drupal\Core\Render\RendererInterface definition.
+   *
+   * @var \Drupal\Core\Entity\EntityTypeManagerInterface
+   */
+  protected $entityTypeManager;
+
+  /**
+   * Constructs a new AjaxHomeController object.
+   */
+  public function __construct(EntityManagerInterface $entity_manager, ConfigurableLanguageManagerInterface $language_manager, RendererInterface $renderer, EntityTypeManagerInterface $entity_type_manager) {
+    $this->entityManager = $entity_manager;
+    $this->languageManager = $language_manager;
+    $this->renderer = $renderer;
+    $this->entityTypeManager = $entity_type_manager;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container) {
+    return new static(
+      $container->get('entity.manager'),
+      $container->get('language_manager'),
+      $container->get('renderer'),
+      $container->get('entity_type.manager')
+    );
+  }
+
+  /**
+   * Hello.
+   *
+   * @return string
+   *   Return Hello string.
+   */
+  public function getHome() {
+
+    $path = \Drupal::config('system.site')->get('page.front');
+
+    $params = Url::fromUri("internal:" . $path)->getRouteParameters();
+    $entity_type = key($params);
+    $entity = $this->entityTypeManager()->getStorage($entity_type)->load($params[$entity_type]);
+
+    $view_builder = $this->entityTypeManager()->getViewBuilder('node');
+    $renderable = $view_builder->view($entity, 'default');
+    $rendered = $this->renderer->executeInRenderContext(new RenderContext(), function () use ($renderable) {
+      return render($renderable);
+    });
+
+    $data['rendered'] = $rendered;
+
+    $data['#cache'] = [
+      'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
+      'tags' => ['edlp-home-cache'],
+      'contexts' => [
+        'languages:language_content'
+      ]
+    ];
+    // $response = new JsonResponse();
+    // $response->setData($data);
+    $response = new CacheableJsonResponse($data);
+    $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
+    $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
+
+    return $response;
+  }
+
+}

+ 6 - 6
web/modules/custom/materio_sapi/materio_sapi.routing.yml

@@ -30,9 +30,9 @@ materio_sapi.getresults:
   requirements:
     _permission: 'access materio search'
 
-# materio_sapi.base:
-#   path: '/base/{keys}/{autocomplete}'
-#   defaults:
-#     _controller: '\Drupal\materio_sapi\Controller\Base::base'
-#   requirements:
-#     _permission: 'access materio search'
+materio_sapi.base:
+  path: '/base'
+  defaults:
+    _controller: '\Drupal\materio_sapi\Controller\Base::pageHandler'
+  requirements:
+    _permission: 'access materio search'

+ 111 - 51
web/modules/custom/materio_sapi/src/Controller/Base.php

@@ -1,5 +1,4 @@
 <?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;
@@ -14,73 +13,88 @@ use Drupal\search_api\Entity\Index;
 // https://drupal.stackexchange.com/questions/225008/programatically-use-search-api
 
 /**
- * Defines a route controller for entity autocomplete form elements.
+ * Defines a route controller for materio sapi search (regular and ajax).
  */
 class Base extends ControllerBase {
 
-  /**
-   * Handler for autocomplete request.
-   */
-  public function getResults(Request $request) {
-    $resp = [
-      'tes' => 'ok',
-      'autocomplete' => $request->query->get('autocomplete'),
-      'keys' => $request->query->get('keys'),
-      'range' => array(
-        'offset' => $request->query->get('offset'),
-        'limit' => $request->query->get('limit'),
-      ),
-    ];
+  private $limit = 15;
+  private $offset = 0;
 
-    // Get the typed string from the URL, if it exists.
-    if ($keys = $resp['keys']) {
-      $typed_string = Tags::explode($keys);
-      $typed_string = Unicode::strtolower($keys);
-      \Drupal::logger('materio_sapi')->notice($typed_string);
+  private function sapiQuery(){
+    $this->index = Index::load('database');
+    $this->query = $this->index->query();
 
-      $index = Index::load('database');
-      $query = $index->query();
+    // Change the parse mode for the search.
+    $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
+      ->createInstance('direct');
+    $parse_mode->setConjunction('OR');
+    $this->query->setParseMode($parse_mode);
 
-      // Change the parse mode for the search.
-      $parse_mode = \Drupal::service('plugin.manager.search_api.parse_mode')
-        ->createInstance('direct');
-      $parse_mode->setConjunction('OR');
-      $query->setParseMode($parse_mode);
+    // Set fulltext search keywords and fields.
+    $this->query->keys($this->keys);
+    // $this->query->setFulltextFields(['name']);
 
-      // Set fulltext search keywords and fields.
-      $query->keys($typed_string);
-      // $query->setFulltextFields(['name']);
+    // Set additional conditions.
+    // $this->query->addCondition('status', 1)
+    //   ->addCondition('author', 1, '<>');
 
-      // Set additional conditions.
-      // $query->addCondition('status', 1)
-      //   ->addCondition('author', 1, '<>');
+    // Restrict the search to specific languages.
+    // $this->query->setLanguages(['de', 'it']);
 
-      // Restrict the search to specific languages.
-      // $query->setLanguages(['de', 'it']);
+    // Do paging.
+    $this->query->range($this->offset, $this->limit);
 
-      // Do paging.
-      $query->range($resp['range']['offset'], $resp['range']['limit']);
+    // Add sorting.
+    $this->query->sort('search_api_relevance', 'DESC');
 
-      // Add sorting.
-      $query->sort('search_api_relevance', 'DESC');
+    // Set one or more tags for the query.
+    // @see hook_search_api_query_TAG_alter()
+    // @see hook_search_api_results_TAG_alter()
+    $this->query->addTag('materio_sapi_search');
 
-      // Set one or more tags for the query.
-      // @see hook_search_api_query_TAG_alter()
-      // @see hook_search_api_results_TAG_alter()
-      $query->addTag('materio_sapi_search');
+    $this->results = $this->query->execute();
 
-      $results = $query->execute();
+  }
+
+  /**
+   * get params from request
+   */
+  private function parseRequest(Request $request){
+    // Get the typed string from the URL, if it exists.
+    $this->keys = $request->query->get('keys');
+    if($this->keys){
+      $this->keys = Unicode::strtolower($this->keys);
+      // $this->keys = Tags::explode($this->keys);
+      \Drupal::logger('materio_sapi')->notice($this->keys);
+    }
+    $this->term = $request->query->get('term');
+    $this->offset = $request->query->get('offset') ?? $this->offset;
+    $this->limit = $request->query->get('limit') ?? $this->limit;
+  }
+
+  /**
+   * Handler for ajax search.
+   */
+  public function getResults(Request $request) {
+    $this->parseRequest($request);
+
+    $resp = [
+      'keys' => $this->keys,
+      'term' => $this->term,
+      'range' => array(
+        'offset' => $this->offset,
+        'limit' => $this->limit
+      ),
+    ];
 
-      $resultitems = $results->getResultItems();
-      $resp['count'] = $results->getResultCount();
-      $resp['resultitems'] = array_keys($resultitems);
-      $resp['options'] = $query->getOptions();
+    if ($this->keys) {
+      $this->sapiQuery();
 
+      $resp['count'] = $this->results->getResultCount();
+      $resp['options'] = $this->query->getOptions();
 
       $items = [];
-      foreach ($results as $result) {
-        // \Drupal::logger('materio_sapi')->notice(print_r($result->getField('tid')->getValues(),true));
-        // \Drupal::logger('materio_sapi')->notice(print_r($result->getField('name')->getValues(),true));
+      foreach ($this->results as $result) {
         $nid = $result->getField('nid')->getValues()[0];
         $title = $result->getField('title')->getValues()[0]->getText();
         $items[] = [
@@ -94,4 +108,50 @@ class Base extends ControllerBase {
     return new JsonResponse($resp);
   }
 
+
+  /**
+   * Handler for regular page search.
+   */
+  function pageHandler(Request $request){
+    // \Drupal::logger('materio_sapi')->notice(print_r($request, true));
+
+    $this->parseRequest($request);
+
+    $resp = [
+      "#title" => 'Base'
+    ];
+
+    if ($this->keys) {
+      $resp['#title'] = $this->keys;
+
+      $this->sapiQuery();
+
+      $node_view_builder = \Drupal::entityTypeManager()->getViewBuilder('node');
+
+      $items = $this->results->getResultItems();
+
+      $this->items = [];
+      foreach ($items as $item) {
+        try {
+          /** @var \Drupal\Core\Entity\EntityInterface $entity */
+          $entity = $item->getOriginalObject()->getValue();
+        }
+        catch (SearchApiException $e) {
+          continue;
+        }
+        if (!$entity) {
+          continue;
+        }
+        // TODO: define dynamicly viewmode
+        $this->items[] = $node_view_builder->view($entity, 'teaser');
+
+      }
+
+      $resp['items'] = $this->items;
+    }else{
+      $resp['#markup'] = "no keys to search for";
+    }
+
+    return $resp;
+  }
 }

+ 1 - 1
web/modules/custom/materio_sapi/src/Form/MaterioSapiSearchForm.php

@@ -32,7 +32,7 @@ class MaterioSapiSearchForm extends FormBase {
         "placeholder" => $this->t('Search'),
         // "@keyup" => "keyup",
         "@keyup.enter" => "submit",
-        "v-model" => "keys",
+        "v-model" => "typed",
         // "v-on:select" => "typed",
       ],
       '#autocomplete_route_name' => 'materio_sapi.search_autocomplete',

+ 7 - 0
web/modules/custom/rest_config/rest_config.info.yml

@@ -0,0 +1,7 @@
+name: 'REST Config'
+type: module
+description: 'Get site configiration through rest api'
+core: 8.x
+package: 'Custom'
+dependencies:
+  - rest

+ 24 - 0
web/modules/custom/rest_config/rest_config.module

@@ -0,0 +1,24 @@
+<?php
+
+/**
+ * @file
+ * Contains rest_config.module.
+ */
+
+use Drupal\Core\Routing\RouteMatchInterface;
+
+/**
+ * Implements hook_help().
+ */
+function rest_config_help($route_name, RouteMatchInterface $route_match) {
+  switch ($route_name) {
+    // Main module help for the rest_config module.
+    case 'help.page.rest_config':
+      $output = '';
+      $output .= '<h3>' . t('About') . '</h3>';
+      $output .= '<p>' . t('Get site configiration through rest api') . '</p>';
+      return $output;
+
+    default:
+  }
+}

+ 106 - 0
web/modules/custom/rest_config/src/Plugin/rest/resource/ConfigRestResource.php

@@ -0,0 +1,106 @@
+<?php
+
+namespace Drupal\rest_config\Plugin\rest\resource;
+
+use Drupal\Core\Session\AccountProxyInterface;
+use Drupal\rest\ModifiedResourceResponse;
+use Drupal\rest\Plugin\ResourceBase;
+use Drupal\rest\ResourceResponse;
+use Psr\Log\LoggerInterface;
+use Symfony\Component\DependencyInjection\ContainerInterface;
+use Symfony\Component\HttpKernel\Exception\AccessDeniedHttpException;
+
+/**
+ * Provides a resource to get configurations values.
+ *
+ * @RestResource(
+ *   id = "config_rest_resource",
+ *   label = @Translation("Config rest resource"),
+ *   uri_paths = {
+ *     "canonical" = "/config/{file}/{key}"
+ *   }
+ * )
+ */
+class ConfigRestResource extends ResourceBase {
+
+  /**
+   * A current user instance.
+   *
+   * @var \Drupal\Core\Session\AccountProxyInterface
+   */
+  protected $currentUser;
+
+  /**
+   * Constructs a new ConfigRestResource object.
+   *
+   * @param array $configuration
+   *   A configuration array containing information about the plugin instance.
+   * @param string $plugin_id
+   *   The plugin_id for the plugin instance.
+   * @param mixed $plugin_definition
+   *   The plugin implementation definition.
+   * @param array $serializer_formats
+   *   The available serialization formats.
+   * @param \Psr\Log\LoggerInterface $logger
+   *   A logger instance.
+   * @param \Drupal\Core\Session\AccountProxyInterface $current_user
+   *   A current user instance.
+   */
+  public function __construct(
+    array $configuration,
+    $plugin_id,
+    $plugin_definition,
+    array $serializer_formats,
+    LoggerInterface $logger,
+    AccountProxyInterface $current_user) {
+    parent::__construct($configuration, $plugin_id, $plugin_definition, $serializer_formats, $logger);
+
+    $this->currentUser = $current_user;
+  }
+
+  /**
+   * {@inheritdoc}
+   */
+  public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
+    return new static(
+      $configuration,
+      $plugin_id,
+      $plugin_definition,
+      $container->getParameter('serializer.formats'),
+      $container->get('logger.factory')->get('rest_config'),
+      $container->get('current_user')
+    );
+  }
+
+  /**
+   * Responds to GET requests.
+   *
+   * @return \Drupal\rest\ResourceResponse
+   *   The HTTP response object.
+   *
+   * @throws \Symfony\Component\HttpKernel\Exception\HttpException
+   *   Throws exception expected.
+   */
+  public function get($file = null, $key = null) {
+
+    // You must to implement the logic of your REST Resource here.
+    // Use current user after pass authentication to validate access.
+    if (!$this->currentUser->hasPermission('access content')) {
+      throw new AccessDeniedHttpException();
+    }
+
+    $data = [];
+    if($file && $key){
+      $config = \Drupal::config($file);
+      if($config){
+        $value = $config->get($key);
+        $data[$key] = $value;
+      }
+    }
+
+    $response = new ResourceResponse($data, 200);
+    $response->addCacheableDependency($data);
+    return $response;
+  }
+
+}

File diff suppressed because it is too large
+ 0 - 0
web/themes/custom/materiotheme/assets/dist/main.js


+ 1 - 1
web/themes/custom/materiotheme/assets/scripts/main.js

@@ -94,7 +94,7 @@ import 'theme/assets/styles/main.scss'
       let main_html = $main_content.innerHTML
       _v_main_content = new Vue({
         store,
-        render: h => h(VMainContent, {props:{id:id, html:main_html}})
+        render: h => h(VMainContent, {props:{id:id, html:main_html, isfront:drupalSettings.path.isFront}})
       }).$mount('#'+id)
       // console.log('initTestVContent', v_test_content);
     }

+ 25 - 0
web/themes/custom/materiotheme/vuejs/components/Content/Base.vue

@@ -28,6 +28,31 @@ export default {
       items: state => state.Search.items
     })
   },
+  methods: {
+    ...mapActions({
+      newSearch: 'Search/newSearch'
+    })
+  },
+  created() {
+    // laucnh a search if params exists in url query
+    console.log('Base created() location',window.location);
+    let params = new URLSearchParams(window.location.search)
+    if(params.has('keys')){
+      this.$store.commit('Search/setKeys', params.get('keys'))
+      this.newSearch()
+    }
+  },
+  // beforeRouteEnter (to, from, next) {
+  //   console.log('Base beforeRouteEnter');//, to, from, next);
+  //   next()
+  // },
+  beforeRouteUpdate (to, from, next) {
+    console.log('Base beforeRouteUpdate', to, from, next);
+    this.$store.commit('Search/setKeys', to.query.keys)
+    this.$store.commit('Search/setTerm', to.query.term)
+    this.newSearch()
+    next()
+  },
   components: {
     Card
   }

+ 4 - 24
web/themes/custom/materiotheme/vuejs/components/Content/Home.vue

@@ -1,45 +1,25 @@
-
 <script>
 
 import Vue from 'vue'
-import { MA } from 'vuejs/api/ma-axios'
 
 export default {
   props: ['html'], // get the html from parent with props
   data() {
     return {
-      template_src: null, // record the prop into data as it will be available in every hooks
       template: null // compiled template from html used in render
     }
   },
   beforeMount() {
-    // console.log('Home beforeMount this.html', this.html);
-    if(!this.template_src){
-      if(this.html){ // if html prop is available record it has data
-        this.template_src = this.html
-      }else{ // else get it from ajax (e.g. if we didn't load the page from home)
-        this.getHomeHtml()
-      }
-    }
+    // console.log('Home beforeMount');
     // compile the html src (coming from parent with props or from ajax call)
-    if(this.template_src){
-      this.template = Vue.compile(this.template_src)
+    if(this.html){
+      // console.log('html', this.html);
+      this.template = Vue.compile(this.html)
       this.$options.staticRenderFns = []
       this._staticTrees = []
       this.template.staticRenderFns.map(fn => (this.$options.staticRenderFns.push(fn)))
     }
   },
-  methods: {
-    getHomeHtml(){
-      MA.get(`/materio_user/login_block`)
-        .then(({data}) => {
-          this.template_src = data.rendered // record the html src into data
-        })
-        .catch(( error ) => {
-          console.warn('Issue with getHomeHtml', error)
-        })
-    }
-  },
   render(h) {
     if(!this.template){
       return h('span', 'Loading ...')

+ 31 - 14
web/themes/custom/materiotheme/vuejs/components/Content/MainContent.vue

@@ -1,6 +1,6 @@
 <template lang="html">
   <div :id="id">
-    <router-view name="home" :html="html"></router-view>
+    <router-view name="home" :html="home_template_src"></router-view>
     <router-view name="base"></router-view>
   </div>
 </template>
@@ -8,23 +8,40 @@
 <script>
 import { mapState, mapActions } from 'vuex'
 
+import { MA } from 'vuejs/api/ma-axios'
 import router from 'vuejs/route'
 
 export default {
   router,
-  props:['id','html']
-  // computed: {
-  //   ...mapState({
-  //     token: state => state.User.token,
-  //     isloggedin: state => state.User.isloggedin
-  //   })
-  // },
-  // beforeMount() {
-  //   console.log('MainContent beforeMount this.html', this.html);
-  // },
-  // mounted() {
-  //   console.log('MainContent this.$router', this.$router);
-  // }
+  props:['id','html', 'isfront'],
+  data() {
+    return {
+      home_template_src: null
+    }
+  },
+  beforeMount() {
+    // console.log('MainContent beforeMount this.html', this.html);
+    if(!this.home_template_src){
+      // console.log('no home_template_src');
+      if(this.html && this.isfront){ // if html prop is available and we are landing on home then record it has data
+        this.home_template_src = this.html
+      }else{ // else get it from ajax (e.g. if we didn't load the page from home)
+        this.getHomeHtml()
+      }
+    }
+  },
+  methods: {
+    getHomeHtml(){
+      MA.get('materio_home/ajax/gethome')
+        .then(({data}) => {
+          // console.log('Home getHomeHtml data', data);
+          this.home_template_src = data.rendered // record the html src into data
+        })
+        .catch(( error ) => {
+          console.warn('Issue with getHomeHtml', error)
+        })
+    }
+  }
 }
 </script>
 

+ 23 - 13
web/themes/custom/materiotheme/vuejs/components/Form/SearchForm.vue

@@ -4,7 +4,7 @@ import Vue from 'vue'
 
 import router from 'vuejs/route'
 
-import { mapState, mapActions } from 'vuex'
+import { mapState } from 'vuex'
 
 export default {
   router,
@@ -12,25 +12,26 @@ export default {
   data() {
     return {
       template: null,
-      keys: "",
-      autocomplete: ""
+      typed: null,
+      autocomplete: null
     }
   },
+  computed: {
+    ...mapState({
+      keys: state => state.Search.keys,
+      term: state => state.Search.term
+    })
+  },
   methods: {
-    ...mapActions({
-      newSearch: 'Search/newSearch'
-    }),
     submit() {
       console.log("search clicked", this.keys, this.autocomplete);
-      this.newSearch(this.keys, this.autocomplete)
-        .then(() => {
-          this.$router.push({name:'base'})
-        });
+      // New search is triggered by Base.vue with router (which will also fill the store)
+      this.$router.push({name:'base', query:{keys:this.typed,term:this.autocomplete}})
     },
     onAutoCompleteSelect(event, ui){
       event.preventDefault();
       // console.log('autoCompleteSelect', event, ui);
-      this.keys = ui.item.label
+      this.typed = ui.item.label
       this.autocomplete = ui.item.value
     }
   },
@@ -46,10 +47,19 @@ export default {
     }
   },
   watch: {
-    keys(){
-      console.log('keys changed', this.keys);
+    keys(n, o){
+      console.log('keys changed', n, o);
+      this.typed = n
+    },
+    term(n, o){
+      console.log('autocomplete changed', n, o);
+      this.autocomplete = n
     }
   },
+  created() {
+    this.typed = this.keys
+    this.autocomplete = this.term
+  },
   mounted(){
     // console.log('SearchForm mounted');
     Drupal.attachBehaviors(this.$el);

+ 10 - 0
web/themes/custom/materiotheme/vuejs/route/index.js

@@ -6,7 +6,10 @@ import Base from 'vuejs/components/Content/Base'
 
 Vue.use(VueRouter)
 
+// https://www.lullabot.com/articles/decoupled-hard-problems-routing
+
 export default new VueRouter({
+  mode: 'history',
   routes: [
     {
       path: '/',
@@ -22,5 +25,12 @@ export default new VueRouter({
         'base': Base
       }
     },
+    // {
+    //   path: '*',
+    //   name: 'notfound',
+    //   components: {
+    //     'notfound': NotFound
+    //   }
+    // }
   ]
 })

+ 9 - 10
web/themes/custom/materiotheme/vuejs/store/modules/search.js

@@ -8,10 +8,10 @@ export default {
   // initial state
   state : {
     keys: "",
-    autocomplete: "",
+    term: "",
     items: [],
-    limit: 15,
-    offset: 0
+    offset: 0,
+    limit: 15
   },
 
   // getters
@@ -25,8 +25,8 @@ export default {
     setKeys (state, keys) {
       state.keys = keys
     },
-    setAutocomplete (state, autocomplete) {
-      state.autocomplete = autocomplete
+    setTerm (state, term) {
+      state.term = term
     },
     resetOffset(state) {
       state.offset = 0
@@ -38,20 +38,19 @@ export default {
 
   // actions
   actions : {
-    newSearch({ dispatch, commit, state }, keys, autocomplete) {
+    newSearch({ dispatch, commit, state }) {
+      console.log('Search newSearch');
       commit('resetOffset')
-      commit('setKeys', keys)
-      commit('setAutocomplete', autocomplete)
       dispatch('getResults')
     },
     getResults ({ dispatch, commit, state }) {
       let params = {
         keys: state.keys,
-        autocomplete: state.autocomplete,
+        term: state.term,
         offset:state.offset,
         limit: state.limit
       }
-      console.log('Search getResults params', params);
+      // console.log('Search getResults params', params);
       let q = qs.stringify(params)
       return MA.get(`/materio_sapi/getresults?`+q)
         .then(({ data }) => {

Some files were not shown because too many files changed in this diff