language siwtchers links are working now (reloading the whole site but with the right url)

This commit is contained in:
2018-04-14 16:15:11 +02:00
parent cb2ae7ee35
commit 252149bfdc
9 changed files with 315 additions and 25 deletions
@@ -4,7 +4,9 @@ namespace Drupal\edlp_agenda\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Datetime\DrupalDateTime;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
// use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\core\render\RenderContext;
@@ -80,6 +82,23 @@ class AgendaController extends ControllerBase {
'rendered'=> $rendered
];
// translations links
// use Drupal\Core\Url;
// use Drupal\Core\Language\LanguageInterface;
$route_name = 'edlp_agenda.agenda';
$links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, Url::fromRoute($route_name));
if (isset($links->links)) {
$translations_build = [
'#theme' => 'links__language_block',
'#links' => $links->links,
'#attributes' => ['class' => ["language-switcher-{$links->method_id}",],],
'#set_active_class' => TRUE,
];
$translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
$data['translations_links'] = $translations_rendered;
}
$data['#cache'] = [
'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
'tags' => ['edlp-agenda-cache']
@@ -15,8 +15,9 @@ use Drupal\Core\Url;
function edlp_ajax_page_attachments(array &$attachments) {
$url = Url::fromRoute('edlp_ajax.entityjson');
$attachments['#attached']['drupalSettings']['edlp_ajax']['entityjson_path'] = $url->getInternalPath();
// $url = Url::fromRoute('edlp_ajax.urljson');
// $attachments['#attached']['drupalSettings']['edlp_ajax']['urljson_path'] = $url->getInternalPath();
$url = Url::fromRoute('edlp_ajax.blocksjson');
$attachments['#attached']['drupalSettings']['edlp_ajax']['blocksjson_path'] = $url->getInternalPath();
$redirect = false;
$current_path = \Drupal::service('path.current')->getPath();
@@ -10,10 +10,19 @@ edlp_ajax.entityjson:
path: '/edlp/ajax/entity/json/{entity_type}/{id}/{viewmode}'
defaults:
_controller: '\Drupal\edlp_ajax\Controller\EdlpAjaxController::entityjson'
_title: 'EdlpAjaxJson'
_title: 'EdlpAjaxEntityJson'
entity_type : null
id: null
viewmode: 'default'
requirements:
_permission: 'access content'
# id: \d+
# NOT USED (YET)
edlp_ajax.blocksjson:
path: '/edlp/ajax/blocks/json/{blockid}'
defaults:
_controller: '\Drupal\edlp_ajax\Controller\EdlpAjaxController::blocksjson'
_title: 'EdlpAjaxBlockJson'
blockid: null
requirements:
_permission: 'access content'
@@ -5,8 +5,10 @@ namespace Drupal\edlp_ajax\Controller;
use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\HttpFoundation\Request;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;
// use Symfony\Component\HttpFoundation\JsonResponse;
use \Drupal\block\Entity\Block;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\core\render\RenderContext;
@@ -94,6 +96,20 @@ class EdlpAjaxController extends ControllerBase {
$data['menu_parents'] = $menu_parents;
}
// translations links
$links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, $this->entity->toUrl());
if (isset($links->links)) {
$translations_build = [
'#theme' => 'links__language_block',
'#links' => $links->links,
'#attributes' => ['class' => ["language-switcher-{$links->method_id}"]],
'#set_active_class' => TRUE,
];
$translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
// dpm($links);
$data['translations_links'] = $translations_rendered;
}
$data['#cache'] = [
'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
'tags' => [
@@ -110,8 +126,85 @@ class EdlpAjaxController extends ControllerBase {
return $response;
dpm($response);
// dpm($response);
// return array(
// '#markup'=>'hello'
// );
}
/**
* Get all visisble blocks from edlptheme as json through ajax.
*
* @return json
*/
// NOT USED (YET)
public function blocksjson($blockid) {
$block_viewbuilder = \Drupal::entityTypeManager()->getViewBuilder('block');
//
$blocksids = [];
if(!$blockid){
// TODO: get all blocks definition from edlptheme
$block_storage = \Drupal::entityTypeManager()->getStorage('block');
// dpm($block_storage, '$block_storage');
$allblocks = $block_storage->loadMultiple();
// dpm($blocks, 'blocks');
foreach ($allblocks as $block) {
// dpm($block->id(), 'block');
// dpm($block->getTheme(), 'theme');
// $visibility = $block->getVisibility();
if($block->getTheme() == "edlptheme"){
// dpm($block, $block->id());
$blocksids[] = $block->id();
}
}
// $block_listbuilder = \Drupal::entityTypeManager()->getListBuilder('block');
// dpm($block_listbuilder, '$block_listbuilder');
// // foreach ($blocks as $key => $value) {
// // $block = \Drupal\block\Entity\Block::load('productions');
// // }
}
else{
$blocksids[] = $blockid;
}
// dpm($blocksids, 'blockids');
//
$blocks = [];
foreach ($blocksids as $id) {
$block = Block::load($id);
$block_render = $block_viewbuilder->view($block);
$rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($block_render) {
return render($block_render);
});
$blocks[$id] = array(
'rendered'=> $rendered,
'region'=> str_replace('_', '-', $block->getRegion()),
'id'=> preg_replace('/^[^:]+:(.+)$/', 'block-$1', $block->getPluginId())
);
}
// dpm($blocks, 'blocks');
//
$data = [
'blockid'=>$blockid,
'blocks' => $blocks,
'#cache' => [
'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
'tags' => [
'edlp-ajax-blocks-cache',
// $this->entity_type.':'.$this->id // not necessary as we add $renderable as CacheableMetadata to the response
]
]
];
// dpm($data);
//
$response = new CacheableJsonResponse($data);
// $response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($data));
//
return $response;
// dpm($response);
//
return array(
'#markup'=>'hello'
);
@@ -3,7 +3,10 @@
namespace Drupal\edlp_productions\Controller;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;
// use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Core\Cache\CacheableJsonResponse;
use Drupal\Core\Cache\CacheableMetadata;
@@ -106,6 +109,21 @@ class ProductionsController extends ControllerBase {
// )
];
// translations links
$route_name = 'edlp_productions.productions';
$links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, Url::fromRoute($route_name));
if (isset($links->links)) {
$translations_build = [
'#theme' => 'links__language_block',
'#links' => $links->links,
'#attributes' => ['class' => ["language-switcher-{$links->method_id}",],],
'#set_active_class' => TRUE,
];
$translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
$data ['translations_links'] = $translations_rendered;
}
$data['#cache'] = [
'max-age' => \Drupal\Core\Cache\Cache::PERMANENT,
'tags' => ['edlp-productions-cache']
@@ -118,6 +136,9 @@ class ProductionsController extends ControllerBase {
$response->addCacheableDependency(CacheableMetadata::createFromRenderArray($renderable));
return $response;
// return array(
// '#markup'=>'hello'
// );
}
}
@@ -6,6 +6,8 @@ use Drupal\Core\Controller\ControllerBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Form\FormBuilder;
use Drupal\search_api\Entity\Index;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
@@ -72,14 +74,29 @@ class EdlpSearchController extends ControllerBase {
$this->buildRenderable();
$rendered = render($this->renderable);
$data = [
'rendered' => $rendered
];
// translations links
$route_name = 'edlp_search.edlp_search_controller_searchForm';
$links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, Url::fromRoute($route_name));
if (isset($links->links)) {
$translations_build = [
'#theme' => 'links__language_block',
'#links' => $links->links,
'#attributes' => ['class' => ["language-switcher-{$links->method_id}",],],
'#set_active_class' => TRUE,
];
$translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
$data['translations_links'] = $translations_rendered;
}
// TODO: make respponse cachable
$response = new JsonResponse();
$response->setData([
'rendered'=> $rendered,
]);
$response->setData($data);
return $response;
}
public function autocomplete(Request $request){
@@ -7,6 +7,7 @@ use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\User\UserDataInterface;
use Drupal\Core\Url;
use Drupal\Core\Language\LanguageInterface;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\edlp_studio\Entity\Chutier;
@@ -60,11 +61,28 @@ class StudioUIController extends ControllerBase {
$renderable = $this->buildStudioUI();
$rendered = render($renderable);
$data = ['rendered'=>$rendered];
// translations links
// use Drupal\Core\Url;
// use Drupal\Core\Language\LanguageInterface;
$route_name = 'edlp_studio.studio_ui';
$links = \Drupal::languageManager()->getLanguageSwitchLinks(LanguageInterface::TYPE_URL, Url::fromRoute($route_name));
if (isset($links->links)) {
$translations_build = [
'#theme' => 'links__language_block',
'#links' => $links->links,
'#attributes' => ['class' => ["language-switcher-{$links->method_id}",],],
'#set_active_class' => TRUE,
];
$translations_rendered = \Drupal::service('renderer')->executeInRenderContext(new RenderContext(), function () use ($translations_build) {return render($translations_build);});
$data['translations_links'] = $translations_rendered;
}
// JSON
$response = new JsonResponse();
$response->setData([
'rendered'=> $rendered,
]);
$response->setData($data);
return $response;
}
@@ -163,7 +163,7 @@
};
function onAjaxLoaded(data, state){
console.log('ajax loaded url:'+state.url+' ajax_path:'+state.ajax_path+' sys_path:'+state.sys_path);
// console.log(data);
// reset all style may been added by other pages (like masonry for productions)
// and replace all content with newly loaded
// TODO: build a system to replace or append contents (like studio + search)
@@ -228,6 +228,28 @@
addCloseModalBtnToCols();
}
// update the language switcher block if it comes in the response
if(typeof data.translations_links != 'undefined'){
console.log('state',state);
var lang_code = drupalSettings.path.currentLanguage;
var $links = $(data.translations_links);
// set active link
$links.find('li[hreflang="'+lang_code+'"]').addClass('is-active').find('a').addClass('is-active');
if(state.view_mode){
$links.find('a').each(function(i,e){
var $a = $(this);
$a.attr('href', $a.attr('href')+'#'+state.view_mode);
});
}
// if(state.selector){
// $links.find('a').attr('selector', state.selector);
// }
$('ul','.block.language-switcher-language-url').replaceWith($links);
}
initAjaxLinks();
// trigger other modules behaviours
@@ -281,6 +303,34 @@
});
};
// _ _ ___ _ _
// /_\ (_)__ ___ __ | _ ) |___ __| |__ ___
// / _ \ | / _` \ \ / | _ \ / _ \/ _| / /(_-<
// /_/ \_\/ \__,_/_\_\ |___/_\___/\__|_\_\/__/
// |__/
// NOT USED (YET)
function refreshAllBlocks(){
var path = window.location.origin + Drupal.url(_ajax_settings.blocksjson_path);
$.getJSON(path, {})
.done(function(data){
onAjaxBlockLoaded(data);
})
.fail(function(jqxhr, textStatus, error){
onAjaxBlockLoadError(jqxhr, textStatus, error);
});
};
function onAjaxBlockLoadError(jqxhr, textStatus, error){
console.warn('ajax block load failed: '+error, jqxhr.responseText);
};
function onAjaxBlockLoaded(data){
console.log('onAjaxBlockLoaded', data);
// TODO: update each blocks (exepted language switcher)
for (var blockname in data.blocks) {
var block = data.blocks[blockname];
console.log(blockname, block);
$(block.id).replaceWith(block.rendered);
}
};
// _ _ _ _
// | || (_)__| |_ ___ _ _ _ _
// | __ | (_-< _/ _ \ '_| || |
@@ -300,6 +350,7 @@
var origin_hash = window.localStorage.getItem('edlp_origin_hash');
var view_mode = origin_hash.replace('#', '');
if(view_mode){
// TODO first load with index or notice do not activate the right link (activate all)
var $link = $('[href="'+origin_url+'"][viewmode="'+view_mode+'"]');
var selector = $link.attr('selector') || null;
if(selector){
@@ -371,7 +422,7 @@
$('a.site-name', '#block-edlptheme-branding')
.add('a', '#block-mainnavigation')
.add('a', '.block.language-switcher-language-url')
// .add('a', '.block.language-switcher-language-url')
.add('a', '#block-footer.menu--footer')
.add('a', '#block-productions')
.add('a', 'article.node:not(.node--type-enregistrement) h2.node-title')
@@ -409,10 +460,14 @@
return false;
}
if($link.is('.language-link')){
// TODO load all blocks translated ... :/
// then let load the content
}
// NOT USED (YET)
// if($link.is('.language-link')){
// TODO: change global site current language
// load all blocks translated (exepted language switcher) ... :/
// refreshAllBlocks();
// TODO: use a promise to initAjaxLinks again after blocks updated
// then let load the content
// }
// other links
var sys_path = $(this).attr('data-drupal-link-system-path');
@@ -443,6 +498,7 @@
return false;
};
// ___
// / __|___ _ _ _ __ _ _ ___
// | (__/ _ \ '_| '_ \ || (_-<
@@ -163,7 +163,7 @@
};
function onAjaxLoaded(data, state){
console.log('ajax loaded url:'+state.url+' ajax_path:'+state.ajax_path+' sys_path:'+state.sys_path);
// console.log(data);
// reset all style may been added by other pages (like masonry for productions)
// and replace all content with newly loaded
// TODO: build a system to replace or append contents (like studio + search)
@@ -228,6 +228,28 @@
addCloseModalBtnToCols();
}
// update the language switcher block if it comes in the response
if(typeof data.translations_links != 'undefined'){
console.log('state',state);
var lang_code = drupalSettings.path.currentLanguage;
var $links = $(data.translations_links);
// set active link
$links.find('li[hreflang="'+lang_code+'"]').addClass('is-active').find('a').addClass('is-active');
if(state.view_mode){
$links.find('a').each(function(i,e){
var $a = $(this);
$a.attr('href', $a.attr('href')+'#'+state.view_mode);
});
}
// if(state.selector){
// $links.find('a').attr('selector', state.selector);
// }
$('ul','.block.language-switcher-language-url').replaceWith($links);
}
initAjaxLinks();
// trigger other modules behaviours
@@ -281,6 +303,34 @@
});
};
// _ _ ___ _ _
// /_\ (_)__ ___ __ | _ ) |___ __| |__ ___
// / _ \ | / _` \ \ / | _ \ / _ \/ _| / /(_-<
// /_/ \_\/ \__,_/_\_\ |___/_\___/\__|_\_\/__/
// |__/
// NOT USED (YET)
function refreshAllBlocks(){
var path = window.location.origin + Drupal.url(_ajax_settings.blocksjson_path);
$.getJSON(path, {})
.done(function(data){
onAjaxBlockLoaded(data);
})
.fail(function(jqxhr, textStatus, error){
onAjaxBlockLoadError(jqxhr, textStatus, error);
});
};
function onAjaxBlockLoadError(jqxhr, textStatus, error){
console.warn('ajax block load failed: '+error, jqxhr.responseText);
};
function onAjaxBlockLoaded(data){
console.log('onAjaxBlockLoaded', data);
// TODO: update each blocks (exepted language switcher)
for (var blockname in data.blocks) {
var block = data.blocks[blockname];
console.log(blockname, block);
$(block.id).replaceWith(block.rendered);
}
};
// _ _ _ _
// | || (_)__| |_ ___ _ _ _ _
// | __ | (_-< _/ _ \ '_| || |
@@ -300,6 +350,7 @@
var origin_hash = window.localStorage.getItem('edlp_origin_hash');
var view_mode = origin_hash.replace('#', '');
if(view_mode){
// TODO first load with index or notice do not activate the right link (activate all)
var $link = $('[href="'+origin_url+'"][viewmode="'+view_mode+'"]');
var selector = $link.attr('selector') || null;
if(selector){
@@ -371,7 +422,7 @@
$('a.site-name', '#block-edlptheme-branding')
.add('a', '#block-mainnavigation')
.add('a', '.block.language-switcher-language-url')
// .add('a', '.block.language-switcher-language-url')
.add('a', '#block-footer.menu--footer')
.add('a', '#block-productions')
.add('a', 'article.node:not(.node--type-enregistrement) h2.node-title')
@@ -409,10 +460,14 @@
return false;
}
if($link.is('.language-link')){
// TODO load all blocks translated ... :/
// then let load the content
}
// NOT USED (YET)
// if($link.is('.language-link')){
// TODO: change global site current language
// load all blocks translated (exepted language switcher) ... :/
// refreshAllBlocks();
// TODO: use a promise to initAjaxLinks again after blocks updated
// then let load the content
// }
// other links
var sys_path = $(this).attr('data-drupal-link-system-path');
@@ -443,6 +498,7 @@
return false;
};
// ___
// / __|___ _ _ _ __ _ _ ___
// | (__/ _ \ '_| '_ \ || (_-<