footer elements are almost displayed

This commit is contained in:
Bachir Soussi Chiadmi
2018-01-02 16:32:17 +01:00
parent 9c6a1ce9a9
commit 7b9de31a42
70 changed files with 6581 additions and 65 deletions
@@ -0,0 +1,17 @@
# This file is for unifying the coding style for various code editors and IDEs.
# Make sure to have an editorconfig plug-in installed in your editor to have
# the editor use this file.
# Sets this config file to be the top-most one.
root = true
[*]
charset = utf-8
end_of_line = lf
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.md]
trim_trailing_whitespace = false
@@ -0,0 +1 @@
.DS_Store
@@ -0,0 +1,41 @@
language: php
sudo: false
php:
- 5.5
- 5.6
- 7.0
- hhvm
matrix:
allow_failures:
- php: hhvm
fast_finish: true
mysql:
database: context
username: root
encoding: utf8
before_script:
# Remember the current context test directory for later use in the Drupal
# installation.
- TESTDIR=$(pwd)
# Navigate out of module directory to prevent blown stack by recursive module
# lookup.
- cd ..
# Create database.
- mysql -e 'create database context'
# Export database variable for kernel tests.
- export SIMPLETEST_DB=mysql://root:@127.0.0.1/context
# Download Drupal 8 core.
- travis_retry git clone --branch 8.0.x --depth 1 http://git.drupal.org/project/drupal.git
- cd drupal
# Reference rules in build site.
- ln -s $TESTDIR modules/context
script:
# Run the PHPUnit tests which also include the kernel tests.
- ./vendor/phpunit/phpunit/phpunit -c ./core/phpunit.xml.dist ./modules/context
@@ -0,0 +1,4 @@
# Change log
All notable changes to this project will be documented in this file.
This project adheres to [Semantic Versioning](http://semver.org/).
@@ -0,0 +1,3 @@
# Contributing
This file will contain information on how you can contribute to the project.
@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 Odd Hill
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.
@@ -0,0 +1,23 @@
# Context
The context module lets you define conditions for when certain reactions should take place.
An example of a condition could be when viewing a certain node type and blocks should be placed as a reaction when viewing a page with this node type.
###Good resources
- [Drupal 8 Plugin API](https://www.drupal.org/developing/api/8/plugins)
Conditions
---
Context for Drupal 8 uses the built in condition plugins supplied by Drupal through the [Plugin API](https://www.drupal.org/developing/api/8/plugins). So any conditional plug-ins supplied by other modules can also be used with context.
Reactions
---
Reactions for the context module are defined trough the new Drupal 8 [Plugin API](https://www.drupal.org/developing/api/8/plugins).
The context module defines a plugin type named Context Reaction that you can extend when creating your own plugins.
A context reaction requires a configuration form and execute method. The execution of the plugin is also something that will have to be handled by the author of the reaction.
@@ -0,0 +1,21 @@
{
"name": "drupal/context",
"description": "Manage contextual conditions and reactions for different portions of your site.",
"keywords": ["Drupal", "context", "block", "visibility", "conditions"],
"type": "drupal-module",
"license": "MIT",
"homepage": "https://github.com/oddhill/context",
"authors": [
{
"name": "Christoffer Palm",
"email": "christoffer.palm@oddhill.se",
"homepage": "http://www.oddhill.se/",
"role": "Developer"
}
],
"support": {
"issues": "https://github.com/oddhill/context/issues",
"source": "https://github.com/oddhill/context",
"docs": "https://github.com/oddhill/context"
}
}
@@ -0,0 +1,11 @@
name: Context
description: 'Set conditions and configure reactions that should be implemented when conditions pass.'
package: Context
type: module
# core: 8.x
# Information added by Drupal.org packaging script on 2017-09-14
version: '8.x-4.0-beta2'
core: '8.x'
project: 'context'
datestamp: 1505379269
@@ -0,0 +1,43 @@
<?php
/**
* Update all blocks reaction configuration with additional "context_id" property.
*/
function context_update_8001() {
foreach (Drupal::service('context.manager')->getContexts() as $context) {
foreach ($context->getReactions() as $reaction) {
if ($reaction instanceof Drupal\context\Plugin\ContextReaction\Blocks) {
foreach ($reaction->getBlocks() as $block) {
$config = $block->getConfiguration();
if (!isset($config['context_id'])) {
$config['context_id'] = $context->id();
$block->setConfiguration($config);
$context->save();
}
}
}
}
}
}
/**
* Update all blocks reaction configuration with additional "css_class" property.
*/
function context_update_8002() {
$context_manager = \Drupal::service('context.manager');
foreach ($context_manager->getContexts() as $context) {
foreach ($context->getReactions() as $reaction) {
if ($reaction instanceof \Drupal\context\Plugin\ContextReaction\Blocks) {
foreach ($reaction->getBlocks() as $block) {
$configuration = $block->getConfiguration();
if (!isset($configuration['css_class'])) {
$configuration['css_class'] = '';
// Update the block.
$reaction->updateBlock($configuration['uuid'], $configuration);
$context->save();
}
}
}
}
}
}
@@ -0,0 +1,75 @@
<?php
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Component\Utility\NestedArray;
/**
* Implements hook_help().
*/
function context_help($route_name, RouteMatchInterface $route_match) {
switch ($route_name) {
case 'help.page.context':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>'.t('The Context module lets users define conditions for when certain reactions should take place.').'</p>';
$output .= '<p>'.t('An example of a condition could be when viewing a certain node type and blocks should be placed as a reaction when viewing a page with this node type.').'</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Managing context') . '</dt>';
$output .= '<dd>' . t('Users with <em>Administer contexts</em> permission can add contextual conditions and reactions for different portions of their site. For each context, they can choose the conditions that trigger this context to be active and choose different aspects of their site that should react to this active context.') . '</dd>';
$output .= '<dt>' . t('Adding new custom reactions') . '</dt>';
$output .= '<dd>' . t('Reactions for the context module are defined trough the new <a href=":link">Drupal 8 Plugin API</a>.', array(':link' =>'https://www.drupal.org/developing/api/8/plugins')) . '</dd>';
$output .= '<dd>' . t('The Context module defines a plugin type named ContextReaction that users can extend when creating their own plugins.') . '</dd>';
$output .= '<dd>' . t('A context reaction requires a configuration form and execute method. The execution of the plugin is also something that will have to be handled by the author of the reaction.') . '</dd>';
$output .= '</dl>';
return $output;
}
}
/**
* Run the body class context reactions if there are any and let them add
* classes to the page body.
*
* Implements hook_preprocess_HOOK().
*/
function context_preprocess_html(&$variables) {
/** @var \Drupal\context\ContextManager $context_manager */
$context_manager = \Drupal::service('context.manager');
foreach ($context_manager->getActiveReactions('body_class') as $reaction) {
$variables['attributes'] = NestedArray::mergeDeep($variables['attributes'], $reaction->execute());
}
}
/**
* Implements hook_theme_suggestions_page_alter().
*/
function context_theme_suggestions_page_alter(array &$suggestions, array $variables) {
$context_manager = \Drupal::service('context.manager');
foreach ($context_manager->getActiveReactions('page_template_suggestions') as $reaction) {
$template_suggestions = explode(PHP_EOL, $reaction->execute());
$suggestions = array_merge($suggestions, $template_suggestions);
}
}
/**
* Implements hook_preprocess_page().
*/
function context_preprocess_page(&$variables) {
// Active theme for route.
$current_theme = \Drupal::service('theme.negotiator')->determineActiveTheme(Drupal::routeMatch());
// Context manager.
$context_manager = \Drupal::service('context.manager');
// Disable regions based on regions reaction.
foreach ($context_manager->getActiveReactions('regions') as $region_reaction) {
$configuration = $region_reaction->getConfiguration();
if (isset($configuration['regions'][$current_theme])) {
foreach ($configuration['regions'][$current_theme] as $region) {
unset($variables['page'][$region]);
}
}
}
}
@@ -0,0 +1,8 @@
# Page to edit a context.
entity.context.edit_form:
path: '/admin/structure/context/{context}'
defaults:
_entity_form: 'context.edit'
_title: 'Edit context'
requirements:
_permission: 'administer contexts'
@@ -0,0 +1,16 @@
services:
context.manager:
class: Drupal\context\ContextManager
arguments: ['@entity.query', '@entity.manager', '@context.repository', '@context.handler', '@entity.form_builder', '@theme.manager']
plugin.manager.context_reaction:
class: Drupal\context\ContextReactionManager
parent: default_plugin_manager
context.block_page_display_variant_subscriber:
class: Drupal\context\EventSubscriber\BlockPageDisplayVariantSubscriber
arguments: ['@context.manager']
tags:
- { name: event_subscriber }
theme.negotiator.context_themeswitcher:
class: Drupal\context\Theme\ThemeSwitcherNegotiator
tags:
- { name: theme_negotiator, priority: 1000 }
@@ -0,0 +1,69 @@
/**
* @file
* Context admin behaviors.
*/
(function ($, Drupal) {
'use strict';
/**
* This is a generic table filter that works with any table formatted in the
* correct way with classes and data attributes.
*
* @type {Drupal~behavior}
*
* @prop {Drupal~behaviorAttach} attach
* Attaches the behavior for the block filtering.
*/
Drupal.behaviors.contextTableFilter = {
attach: function () {
var $input = $('input.context-table-filter').once('.context-table-filter');
var $table = $($input.attr('data-element'));
var $filter_rows;
// Only attach the filter listener if there is a table to filter.
if ($table.length) {
$filter_rows = $table.find('.context-table-filter-text-source');
$input.on('keyup', filterTableRows);
}
/**
* Filters the table rows.
*
* @param {jQuery.Event} e
* The jQuery event for the keyup event that triggered the filter.
*/
function filterTableRows(e) {
var query = $(e.target).val().toLowerCase();
/**
* Shows or hides the Table rows based on the query.
*
* @param {number} index
* The index in the loop, as provided by `jQuery.each`
*
* @param {HTMLElement} label
* The label of the block.
*/
function toggleTableRow(index, label) {
var $label = $(label);
var $row = $label.parent().parent();
var textMatch = $label.text().toLowerCase().indexOf(query) !== -1;
$row.toggle(textMatch);
}
// Filter if the length of the query is at least 2 characters.
if (query.length >= 2) {
$filter_rows.each(toggleTableRow);
}
else {
$filter_rows.each(function () {
$(this).parent().parent().show();
});
}
}
}
};
}(jQuery, Drupal));
@@ -0,0 +1,16 @@
name: Context UI
description: 'Provides a simple UI for settings up a site structure using Context.'
package: Context
type: module
# core: 8.x
configure: entity.context.collection
# Module dependencies.
dependencies:
- context
# Information added by Drupal.org packaging script on 2017-09-14
version: '8.x-4.0-beta2'
core: '8.x'
project: 'context'
datestamp: 1505379269
@@ -0,0 +1,7 @@
admin:
version: VERSION
js:
assets/js/context_ui.admin.js: {}
dependencies:
- core/jquery
- core/drupal
@@ -0,0 +1,5 @@
entity.context.add_form:
title: 'Add context'
route_name: entity.context.add_form
appears_on:
- entity.context.collection
@@ -0,0 +1,4 @@
context_block_config:
title: 'Configure block'
route_name: 'context.reaction.blocks.block_edit'
group: 'context_block'
@@ -0,0 +1,5 @@
entity.context.collection:
title: 'Context'
parent: system.admin_structure
description: 'Associate menus, views, blocks, etc. with different contexts to structure your site.'
route_name: entity.context.collection
@@ -0,0 +1,3 @@
administer contexts:
title: 'Administer contexts'
description: 'Associate menus, views, blocks, etc. with different contexts to structure your site.'
@@ -0,0 +1,137 @@
# Page to lists all contexts.
entity.context.collection:
path: '/admin/structure/context'
defaults:
_entity_list: 'context'
_title: 'Context'
requirements:
_permission: 'administer contexts'
# Page to add a context.
entity.context.add_form:
path: '/admin/structure/context/add'
defaults:
_entity_form: 'context.add'
_title: 'Add context'
requirements:
_permission: 'administer contexts'
# Page to remove a context.
entity.context.delete_form:
path: '/admin/structure/context/{context}/delete'
defaults:
_entity_form: 'context.delete'
_title: 'Delete context'
requirements:
_permission: 'administer contexts'
# Page to disable a context.
entity.context.disable_form:
path: '/admin/structure/context/{context}/disable'
defaults:
_entity_form: 'context.disable'
_title: 'Disable context'
requirements:
_permission: 'administer contexts'
# Route to get autocomplete results for context groups.
context.groups.autocomplete:
path: '/admin/structure/context/groups/autocomplete'
defaults:
_controller: '\Drupal\context_ui\Controller\ContextUIController::groupsAutocomplete'
requirements:
_permission: 'administer contexts'
## Context conditions.
context.conditions_library:
path: '/admin/structure/context/{context}/conditions/library'
defaults:
_title: 'Add condition'
_controller: '\Drupal\context_ui\Controller\ContextUIController::listConditions'
requirements:
_entity_access: 'context.update'
context.condition_add:
path: '/admin/structure/context/{context}/condition/add/{condition_id}'
defaults:
_controller: '\Drupal\context_ui\Controller\ContextUIController::addCondition'
requirements:
_entity_access: 'context.update'
context.condition_delete:
path: '/admin/structure/context/{context}/condition/delete/{condition_id}'
defaults:
_form: '\Drupal\context_ui\Form\ConditionDeleteForm'
requirements:
_entity_access: 'context.update'
## Context reactions.
context.reactions_library:
path: '/admin/structure/context/{context}/reactions/library'
defaults:
_title: 'Add reaction'
_controller: '\Drupal\context_ui\Controller\ContextUIController::listReactions'
requirements:
_entity_access: 'context.update'
context.reaction_add:
path: '/admin/structure/context/{context}/reaction/add/{reaction_id}'
defaults:
_controller: '\Drupal\context_ui\Controller\ContextUIController::addReaction'
requirements:
_entity_access: 'context.update'
context.reaction_delete:
path: '/admin/structure/context/{context}/reaction/delete/{reaction_id}'
defaults:
_form: '\Drupal\context_ui\Form\ReactionDeleteForm'
requirements:
_entity_access: 'context.update'
## Context blocks reaction.
# Callback handler for when the theme is changed in the blocks configuration form.
context.reaction.blocks.regions:
path: '/admin/structure/context/{context}/reaction/blocks/regions'
defaults:
_controller: '\Drupal\context\Reaction\Blocks\Controller\ContextReactionBlocksController::blocksFormThemeSelect'
requirements:
_entity_access: 'context.update'
# Display a list of all blocks.
context.reaction.blocks.library:
path: '/admin/structure/context/{context}/reaction/blocks/{reaction_id}/library'
defaults:
_title: 'Add block'
_controller: '\Drupal\context\Reaction\Blocks\Controller\ContextReactionBlocksController::blocksLibrary'
requirements:
_entity_access: 'context.update'
# Display a form to deleta a block.
context.reaction.blocks.block_delete:
path: '/admin/structure/context/{context}/reaction/blocks/delete/{block_id}'
defaults:
_form: '\Drupal\context\Reaction\Blocks\Form\BlockDeleteForm'
_title: 'Delete block'
requirements:
_entity_access: 'context.update'
# Display a form to add a block.
context.reaction.blocks.block_add:
path: '/admin/structure/context/{context}/reaction/blocks/{reaction_id}/add/{block_id}'
defaults:
_form: '\Drupal\context\Reaction\Blocks\Form\BlockAddForm'
_title: 'Add block'
requirements:
_entity_access: 'context.update'
# Display a form to edit a block.
context.reaction.blocks.block_edit:
path: '/admin/structure/context/{context}/reaction/blocks/{reaction_id}/edit/{block_id}'
defaults:
_form: '\Drupal\context\Reaction\Blocks\Form\BlockEditForm'
_title: 'Edit block'
requirements:
_entity_access: 'context.update'
@@ -0,0 +1,263 @@
<?php
namespace Drupal\context_ui;
use Drupal\context\ContextInterface;
use Drupal\context\ContextManager;
use Drupal\context\Entity\Context;
use Drupal\Component\Utility\Html;
use Drupal\Core\Form\FormInterface;
use Drupal\context\Form\AjaxFormTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Entity\EntityStorageInterface;
use Drupal\Core\Config\Entity\ConfigEntityListBuilder;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContextListBuilder extends ConfigEntityListBuilder implements FormInterface {
use AjaxFormTrait;
/**
* The Context modules context manager.
*
* @var ContextManager
*/
protected $contextManager;
/**
* @var FormBuilderInterface
*/
protected $formBuilder;
/**
* Constructs a new ContextListBuilder object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
*
* @param \Drupal\Core\Entity\EntityStorageInterface $storage
* The entity storage class.
*
* @param \Drupal\context\ContextManager $contextManager
* The Context module context manager.
*
* @param \Drupal\Core\Form\FormBuilderInterface $formBuilder
* The Drupal form builder.
*/
public function __construct(
EntityTypeInterface $entity_type,
EntityStorageInterface $storage,
ContextManager $contextManager,
FormBuilderInterface $formBuilder
) {
parent::__construct($entity_type, $storage);
$this->contextManager = $contextManager;
$this->formBuilder = $formBuilder;
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static(
$entity_type,
$container->get('entity.manager')->getStorage($entity_type->id()),
$container->get('context.manager'),
$container->get('form_builder')
);
}
/**
* Use a form instead of the entity list builder to display contexts.
*
* {@inheritdoc}
*/
public function render() {
return $this->formBuilder->getForm($this);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'context_ui_admin_display_form';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$groups = $this->contextManager->getContextsByGroup();
$form['contexts'] = array(
'#type' => 'table',
'#header' => array(
$this->t('Context'),
$this->t('Description'),
$this->t('Group'),
$this->t('Weight'),
$this->t('Operations'),
),
'#empty' => $this->t('There are no contexts defined.'),
'#attributes' => array(
'id' => 'contexts',
),
);
$group_options = [];
// @todo Make this a bit prettier.
foreach ($groups as $group => $contexts) {
$group_options[$group] = ($group === 'not_grouped') ? $this->t('Not grouped') : $group;
}
// Count the number of entities to get a good delta for the weights.
$weight_delta = round(count($this->getEntityIds()) / 2);
foreach ($groups as $group => $contexts) {
$group_class = Html::getClass($group);
$form['contexts']['#tabledrag'][] = array(
'action' => 'match',
'relationship' => 'sibling',
'group' => 'context-group-select',
'subgroup' => 'context-group-' . $group_class,
'hidden' => FALSE,
);
$form['contexts']['#tabledrag'][] = array(
'action' => 'order',
'relationship' => 'sibling',
'group' => 'context-weight',
'subgroup' => 'context-weight-' . $group_class,
);
$form['contexts']['group-' . $group_class] = array(
'#attributes' => array(
'class' => array('group-label', 'group-label-' . $group_class),
'no_striping' => TRUE,
),
);
$form['contexts']['group-' . $group_class] = [
'#attributes' => [
'class' => ['region-title'],
],
'title' => [
'#markup' => ($group === 'not_grouped') ? $this->t('Not grouped') : $group,
'#wrapper_attributes' => [
'colspan' => 5,
],
],
];
/** @var ContextInterface $context */
foreach ($contexts as $context_id => $context) {
$operations = [
'edit' => [
'title' => $this->t('Edit'),
'url' => $context->urlInfo('edit-form'),
],
'delete' => [
'title' => $this->t('Delete'),
'url' => $context->urlInfo('delete-form'),
'attributes' => $this->getAjaxAttributes(),
],
'disable' => [
'title' => $context->disabled() ? $this->t('Enable') : $this->t('Disable'),
'url' => $context->toUrl('disable-form'),
'attributes' => $this->getAjaxAttributes(),
]
];
$form['contexts'][$context_id] = [
'#attributes' => [
'class' => ['draggable'],
],
'label' => [
'#markup' => $context->getLabel(),
'#wrapper_attributes' => $context->disabled() ? ['style' => 'opacity:0.6'] : NULL,
],
'description' => [
'#markup' => $context->getDescription(),
],
'group' => [
'#type' => 'select',
'#title' => $this->t('Group for @context context', ['@context' => $context->getLabel()]),
'#title_display' => 'invisible',
'#default_value' => $context->getGroup(),
'#options' => $group_options,
'#attributes' => [
'class' => ['context-group-select', 'context-group-' . $group_class],
],
],
'weight' => [
'#type' => 'weight',
'#title' => $this->t('Weight for @context context', ['@context' => $context->getLabel()]),
'#default_value' => $context->getWeight(),
'#delta' => $weight_delta,
'#title_display' => 'invisible',
'#attributes' => [
'class' => ['context-weight', 'context-weight-' . $group_class],
],
],
'operations' => [
'#type' => 'operations',
'#links' => $operations,
],
];
}
}
$form['actions'] = array(
'#type' => 'actions',
);
if (count($groups) > 0) {
$form['actions']['submit'] = array(
'#type' => 'submit',
'#value' => $this->t('Save contexts'),
'#button_type' => 'primary',
);
}
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
// No validation.
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$contexts = $this->storage->loadMultiple(array_keys($form_state->getValue('contexts')));
/*** @var ContextInterface $context */
foreach ($contexts as $context_id => $context) {
$context_values = $form_state->getValue(['contexts', $context_id]);
$context->setWeight($context_values['weight']);
// Not grouped contexts needs a specific group value.
if ($context_values['group'] === 'not_grouped') {
$context->setGroup(Context::CONTEXT_GROUP_NONE);
}
else {
$context->setGroup($context_values['group']);
}
$context->save();
}
drupal_set_message($this->t('The context settings have been updated.'));
}
}
@@ -0,0 +1,395 @@
<?php
namespace Drupal\context_ui\Controller;
use Drupal\Core\Ajax\OpenModalDialogCommand;
use Drupal\Core\Url;
use Drupal\Component\Utility\Html;
use Drupal\context\ContextManager;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\context\ContextInterface;
use Drupal\context\ContextReactionManager;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Condition\ConditionManager;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\JsonResponse;
use Drupal\Component\Plugin\Exception\PluginException;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContextUIController extends ControllerBase {
/**
* The context reaction manager.
*
* @var ContextReactionManager
*/
protected $contextReactionManager;
/**
* The Context module context manager.
*
* @var ContextManager
*/
protected $contextManager;
/**
* The Drupal core condition manager.
*
* @var ConditionManager
*/
protected $conditionManager;
/**
* Construct a new context controller.
*
* @param ContextManager $contextManager
* The Context module context manager.
*
* @param ContextReactionManager $contextReactionManager
* The Context module context reaction plugin manager.
*
* @param ConditionManager $conditionManager
* The Drupal core condition manager.
*/
function __construct(
ContextManager $contextManager,
ContextReactionManager $contextReactionManager,
ConditionManager $conditionManager
) {
$this->contextManager = $contextManager;
$this->contextReactionManager = $contextReactionManager;
$this->conditionManager = $conditionManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('context.manager'),
$container->get('plugin.manager.context_reaction'),
$container->get('plugin.manager.condition')
);
}
/**
* Retrieves group suggestions for a context.
*
* @param Request $request
* The current request.
*
* @return JsonResponse
* A JSON response with groups matching the query.
*/
public function groupsAutocomplete(Request $request) {
$query = $request->query->get('q');
$matches = [];
foreach ($this->contextManager->getContexts() as $context) {
if (stripos($context->getGroup(), $query) === 0) {
$matches[] = $context->getGroup();
}
}
$response = [];
// Format the unique matches to be used with the autocomplete field.
foreach (array_unique($matches) as $match) {
$response[] = [
'value' => $match,
'label' => Html::escape($match),
];
}
return new JsonResponse($response);
}
/**
* Displays a list of conditions that can be added to the context.
*
* @param ContextInterface $context
* The context to display available conditions for.
*
* @return array
*/
public function listConditions(ContextInterface $context) {
// Get a list of all available conditions.
$conditions = $this->conditionManager->getDefinitions();
$header = [
$this->t('Condition')
];
$build['filter'] = [
'#type' => 'search',
'#title' => $this->t('Filter'),
'#title_display' => 'invisible',
'#size' => 30,
'#placeholder' => $this->t('Filter by condition name'),
'#attributes' => [
'class' => ['context-table-filter'],
'data-element' => '.condition-add-table',
'title' => $this->t('Enter a part of the condition name to filter by.'),
],
];
$rows = [];
// Add a table row for each condition.
foreach ($conditions as $condition_id => $condition) {
// Only add the condition to the list of it's not already been added to
// the context.
if ($context->hasCondition($condition_id)) {
continue;
}
$rows[] = [
'condition' => [
'data' => [
'#type' => 'link',
'#title' => $condition['label'] . ' (' . $condition['provider'] . ')',
'#url' => Url::fromRoute('context.condition_add', [
'context' => $context->id(),
'condition_id' => $condition_id,
]),
'#attributes' => [
'class' => ['use-ajax', 'context-table-filter-text-source'],
],
'#options' => [
'html' => TRUE,
]
],
],
];
}
$build['conditions'] = [
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t('There are no conditions left that can be added to this context.'),
'#attributes' => [
'class' => ['condition-add-table'],
],
];
$build['#attached']['library'][] = 'context_ui/admin';
return $build;
}
/**
* Displays a list of reactions that can be added to the context.
*
* @param ContextInterface $context
* The context to display available
*
* @return array
*/
public function listReactions(ContextInterface $context) {
// Get a list of all available conditions.
$reactions = $this->contextReactionManager->getDefinitions();
$header = [
$this->t('Reactions')
];
$build['filter'] = [
'#type' => 'search',
'#title' => $this->t('Filter'),
'#title_display' => 'invisible',
'#size' => 30,
'#placeholder' => $this->t('Filter by reaction name'),
'#attributes' => [
'class' => ['context-table-filter'],
'data-element' => '.reaction-add-table',
'title' => $this->t('Enter a part of the reaction name to filter by.'),
],
];
$rows = [];
// Add a table row for each context reaction.
foreach ($reactions as $reaction_id => $reaction) {
// Only add the reaction to the list of it's not already been added to
// the context.
if ($context->hasReaction($reaction_id)) {
continue;
}
$rows[] = [
'reaction' => [
'data' => [
'#type' => 'link',
'#title' => $reaction['label'],
'#url' => Url::fromRoute('context.reaction_add', [
'context' => $context->id(),
'reaction_id' => $reaction_id,
]),
'#attributes' => [
'class' => ['use-ajax', 'context-table-filter-text-source'],
],
'#options' => [
'html' => TRUE,
],
'#ajax' => TRUE,
],
],
];
}
$build['reactions'] = [
'#type' => 'table',
'#header' => $header,
'#rows' => $rows,
'#empty' => $this->t('There are no reactions left that can be added to this context.'),
'#attributes' => [
'class' => ['reaction-add-table'],
],
];
$build['#attached']['library'][] = 'context_ui/admin';
return $build;
}
/**
* Add the specified reaction to the context.
*
* @param Request $request
* The current request.
*
* @param ContextInterface $context
* The context to add the reaction to.
*
* @param $reaction_id
* The ID of the reaction to add.
*
* @return AjaxResponse|RedirectResponse
*/
public function addReaction(Request $request, ContextInterface $context, $reaction_id) {
if ($context->hasReaction($reaction_id)) {
throw new HttpException(403, 'The specified reaction had already been added to the context.');
}
// Create an instance of the reaction and add it to the context.
try {
$reaction = $this->contextReactionManager->createInstance($reaction_id);
}
catch (PluginException $e) {
throw new HttpException(400, $e->getMessage());
}
// If one of the condition is "Current theme", prevent adding Theme reaction.
// Else this will cause an infinite loop when checking for active contexts.
if ($reaction_id == 'theme') {
$conditions = $context->getConditions();
foreach ($conditions as $condition) {
if ($condition->getPluginId() == 'current_theme') {
if ($request->isXmlHttpRequest()) {
$response = new AjaxResponse();
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new OpenModalDialogCommand($this->t("Theme reaction"), $this->t("You can not place Theme reaction if Current theme condition is set."), ['width' => '700']));
return $response;
}
}
}
}
$context->addReaction($reaction->getConfiguration());
$context->save();
// If the request is an AJAX request then return an AJAX response with
// commands to replace the content on the page.
if ($request->isXmlHttpRequest()) {
$response = new AjaxResponse();
$contextForm = $this->contextManager->getForm($context, 'edit');
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new ReplaceCommand('#context-reactions', $contextForm['reactions']));
return $response;
}
$url = $context->urlInfo('edit-form');
return $this->redirect($url->getRouteName(), $url->getRouteParameters());
}
/**
* Add the specified condition to the context.
*
* @param Request $request
* The current request.
*
* @param ContextInterface $context
* The context to add the condition to.
*
* @param $condition_id
* The ID of the condition to add.
*
* @return AjaxResponse|RedirectResponse
*/
public function addCondition(Request $request, ContextInterface $context, $condition_id) {
if ($context->hasCondition($condition_id)) {
throw new HttpException(403, 'The specified condition had already been added to the context.');
}
// Create an instance of the condition and add it to the context.
try {
$condition = $this->conditionManager->createInstance($condition_id);
}
catch (PluginException $e) {
throw new HttpException(400, $e->getMessage());
}
// Prevent adding "Current theme" condition, if "Theme" reaction is already set.
// Else this will cause an infinite loop when checking for active contexts.
if ($condition_id == 'current_theme') {
$reactions = $context->getReactions();
foreach ($reactions as $reaction) {
if ($reaction->getPluginId() == 'theme') {
if ($request->isXmlHttpRequest()) {
$response = new AjaxResponse();
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new OpenModalDialogCommand($this->t("Current theme condition"), $this->t("You can not set Current theme condition if Theme reaction is set."), ['width' => '700']));
return $response;
}
}
}
}
$context->addCondition($condition->getConfiguration());
$context->save();
// If the request is an AJAX request then return an AJAX response with
// commands to replace the content on the page.
if ($request->isXmlHttpRequest()) {
$response = new AjaxResponse();
$contextForm = $this->contextManager->getForm($context, 'edit');
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new ReplaceCommand('#context-conditions', $contextForm['conditions']));
return $response;
}
$url = $context->urlInfo('edit-form');
return $this->redirect($url->getRouteName(), $url->getRouteParameters());
}
}
@@ -0,0 +1,142 @@
<?php
namespace Drupal\context_ui\Form;
use Drupal\context\ContextManager;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\context\ContextInterface;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ConditionDeleteForm extends ConfirmFormBase {
/**
* The context to delete a condition from.
*
* @var \Drupal\context\Entity\Context
*/
protected $context;
/**
* The condition to delete from the context.
*
* @var \Drupal\Core\Condition\ConditionInterface
*/
protected $condition;
/**
* The Context module context manager.
*
* @var \Drupal\context\ContextManager
*/
protected $contextManager;
/**
* Construct a condition delete form.
*
* @param ContextManager $contextManager
*/
public function __construct(ContextManager $contextManager) {
$this->contextManager = $contextManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static (
$container->get('context.manager')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'context_ui_condition_delete_form';
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete the %label condition?', [
'%label' => $this->condition->getPluginDefinition()['label'],
]);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return $this->context->urlInfo('edit-form');
}
/**
* {@inheritdoc}
*/
public function getConfirmText() {
return $this->t('Delete');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ContextInterface $context = NULL, $condition_id = NULL) {
$this->context = $context;
$this->condition = $context->getCondition($condition_id);
$form = parent::buildForm($form, $form_state);
// Remove the cancel button if this is an AJAX request since Drupals built
// in modal dialogues does not handle buttons that are not a primary
// button very well.
if ($this->getRequest()->isXmlHttpRequest()) {
unset($form['actions']['cancel']);
}
// Submit the form with AJAX if possible.
$form['actions']['submit']['#ajax'] = [
'callback' => '::submitFormAjax'
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Remove the condition and save the context.
$this->context->removeCondition($this->condition->getConfiguration()['id'])->save();
// If this is not an AJAX request then redirect and show a message.
if (!$this->getRequest()->isXmlHttpRequest()) {
drupal_set_message($this->t('The condition %name has been removed.', [
'%name' => $this->condition->getPluginDefinition()['label']]
));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}
/**
* Handle when the form is submitted trough AJAX.
*
* @return AjaxResponse
*/
public function submitFormAjax() {
$contextForm = $this->contextManager->getForm($this->context, 'edit');
$response = new AjaxResponse();
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new ReplaceCommand('#context-conditions', $contextForm['conditions']));
return $response;
}
}
@@ -0,0 +1,30 @@
<?php
namespace Drupal\context_ui\Form;
use Drupal\Core\Form\FormStateInterface;
class ContextAddForm extends ContextFormBase {
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $formState) {
$status = parent::save($form, $formState);
if ($status) {
drupal_set_message($this->t('The context %label has been added.', [
'%label' => $this->entity->getLabel(),
]));
}
else {
drupal_set_message($this->t('The context was not saved.'));
}
$formState->setRedirect('entity.context.edit_form', [
'context' => $this->entity->id(),
]);
}
}
@@ -0,0 +1,79 @@
<?php
namespace Drupal\context_ui\Form;
use Drupal\Core\Url;
use Drupal\context\ContextManager;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContextDeleteForm extends EntityConfirmFormBase {
/**
* @var ContextManager
*/
protected $contextManager;
/**
* @param ContextManager $contextManager
*/
function __construct(ContextManager $contextManager) {
$this->contextManager = $contextManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('context.manager')
);
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to delete the %label context?', array(
'%label' => $this->entity->getLabel(),
));
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('entity.context.collection');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
// Remove the cancel button if this is an AJAX request since Drupals built
// in modal dialogues does not handle buttons that are not a primary
// button very well.
if ($this->getRequest()->isXmlHttpRequest()) {
unset($form['actions']['cancel']);
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $formState) {
$this->entity->delete();
drupal_set_message($this->t('The context %title has been deleted.', array(
'%title' => $this->entity->getLabel(),
)));
$formState->setRedirectUrl($this->getCancelUrl());
}
}
@@ -0,0 +1,89 @@
<?php
namespace Drupal\context_ui\Form;
use Drupal\Core\Url;
use Drupal\context\ContextManager;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Entity\EntityConfirmFormBase;
use Symfony\Component\DependencyInjection\ContainerInterface;
class ContextDisableForm extends EntityConfirmFormBase {
/**
* @var ContextManager
*/
protected $contextManager;
/**
* @param ContextManager $contextManager
*/
function __construct(ContextManager $contextManager) {
$this->contextManager = $contextManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('context.manager')
);
}
/**
* {@inheritdoc}
*/
public function getQuestion() {
return $this->t('Are you sure you want to %status the %label context?', array(
'%status' => $this->entity->disabled() ? "enable" : "disable",
'%label' => $this->entity->getLabel(),
));
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->t('This action will %status the %label context.', array(
'%status' => $this->entity->disabled() ? "enable" : "disable",
'%label' => $this->entity->getLabel(),
));
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return new Url('entity.context.collection');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form = parent::buildForm($form, $form_state);
// Remove the cancel button if this is an AJAX request since Drupals built
// in modal dialogues does not handle buttons that are not a primary
// button very well.
if ($this->getRequest()->isXmlHttpRequest()) {
unset($form['actions']['cancel']);
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $formState) {
$this->entity->disable();
drupal_set_message($this->t('The context %title has been %status.', array(
'%title' => $this->entity->getLabel(),
'%status' => $this->entity->disabled() ? "disabled" : "enabled",
)));
$formState->setRedirectUrl($this->getCancelUrl());
}
}
@@ -0,0 +1,268 @@
<?php
namespace Drupal\context_ui\Form;
use Drupal\Core\Url;
use Drupal\Core\Form\FormState;
use Drupal\context\Form\AjaxFormTrait;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Form\FormStateInterface;
class ContextEditForm extends ContextFormBase {
use AjaxFormTrait;
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
// Store contexts on the form state so that plugins can use these values
// when building their forms.
$form_state->setTemporaryValue('gathered_contexts', $this->contextRepository->getAvailableContexts());
$form['require_all_conditions'] = [
'#type' => 'checkbox',
'#title' => $this->t('Require all conditions'),
'#description' => $this->t('If checked, all conditions must be met for this context to be active. Otherwise, the first condition that is met will activate this context.'),
'#default_value' => $this->entity->requiresAllConditions(),
];
$form['conditions'] = [
'#prefix' => '<div id="context-conditions">',
'#suffix' => '</div>',
'#markup' => '<h3>' . $this->t('Conditions') . '</h3>',
'#tree' => TRUE,
'#process' => array(
array($this, 'processConditions'),
),
];
$form['reactions'] = [
'#prefix' => '<div id="context-reactions">',
'#suffix' => '</div>',
'#markup' => '<h3>' . $this->t('Reactions') . '</h3>',
'#tree' => TRUE,
'#process' => array(
array($this, 'processReactions'),
),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $formState) {
$status = parent::save($form, $formState);
if ($status) {
drupal_set_message($this->t('The context %label has been saved.', [
'%label' => $this->entity->getLabel(),
]));
}
else {
drupal_set_message($this->t('The context was not saved.'));
}
}
/**
* Process function for the conditions.
*
* @param $element
* The element to process.
*
* @param FormStateInterface $form_state
* The current form state.
*
* @return array
*/
public function processConditions(&$element, FormStateInterface $form_state) {
$conditions = $this->entity->getConditions();
$element['add_condition'] = array(
'#type' => 'link',
'#title' => $this->t('Add condition'),
'#url' => Url::fromRoute('context.conditions_library', [
'context' => $this->entity->id(),
]),
'#attributes' => [
'class' => [
'use-ajax', 'button', 'button--small'
],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 700,
]),
],
);
if (!count($conditions)) {
$element['reactions']['empty'] = [
'#type' => 'container',
'#markup' => $this->t('No conditions has been added. When there are no added conditions the context will be considered sitewide.'),
];
}
$element['condition_tabs'] = [
'#type' => 'vertical_tabs',
'#parents' => ['condition_tabs'],
];
foreach ($conditions as $condition_id => $condition) {
$element['condition-' . $condition_id] = [
'#type' => 'details',
'#title' => $condition->getPluginDefinition()['label'],
'#group' => 'condition_tabs',
];
$element['condition-' . $condition_id]['options'] = $condition->buildConfigurationForm([], $form_state);
$element['condition-' . $condition_id]['options']['#parents'] = ['conditions', $condition_id];
$element['condition-' . $condition_id]['remove'] = [
'#type' => 'link',
'#title' => $this->t('Remove condition'),
'#url' => Url::fromRoute('context.condition_delete', [
'context' => $this->entity->id(),
'condition_id' => $condition_id,
]),
'#attributes' => [
'class' => [
'use-ajax', 'button', 'button--small'
],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 700,
]),
],
];
}
return $element;
}
/**
* Process function for the reactions.
*
* @param $element
* The element to process.
*
* @param FormStateInterface $form_state
* The current form state.
*
* @return array
*/
public function processReactions(&$element, FormStateInterface $form_state) {
$reactions = $this->entity->getReactions();
$element['add_reaction'] = [
'#type' => 'link',
'#title' => $this->t('Add reaction'),
'#url' => Url::fromRoute('context.reactions_library', [
'context' => $this->entity->id(),
]),
'#attributes' => [
'class' => [
'use-ajax', 'button', 'button--small'
],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 700,
]),
],
];
if (!count($reactions)) {
$element['empty'] = [
'#type' => 'container',
'#markup' => $this->t('No reactions has been added.'),
];
}
$element['reaction_tabs'] = [
'#type' => 'vertical_tabs',
'#parents' => ['reaction_tabs'],
];
foreach ($reactions as $reaction_id => $reaction) {
$element['reaction-' . $reaction_id] = [
'#type' => 'details',
'#title' => $reaction->getPluginDefinition()['label'],
'#group' => 'reaction_tabs',
];
$reaction_values = $form_state->getValue(['reactions', $reaction_id], []);
$reaction_state = (new FormState())->setValues($reaction_values);
$element['reaction-' . $reaction_id]['options'] = $reaction->buildConfigurationForm([], $reaction_state, $this->entity);
$element['reaction-' . $reaction_id]['options']['#parents'] = ['reactions', $reaction_id];
$element['reaction-' . $reaction_id]['remove'] = [
'#type' => 'link',
'#title' => $this->t('Remove reaction'),
'#url' => Url::fromRoute('context.reaction_delete', [
'context' => $this->entity->id(),
'reaction_id' => $reaction_id,
]),
'#attributes' => [
'class' => [
'use-ajax', 'button', 'button--small'
],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 700,
]),
],
];
}
return $element;
}
/**
* Actions function.
*
* @param array $form
* Form object.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* Form state object.
*
* @return mixed
* Return mixed object.
*/
protected function actions(array $form, FormStateInterface $form_state) {
$element = parent::actions($form, $form_state);
$element['submit'] = [
'#type' => 'submit',
'#dropbutton' => 'save',
'#value' => t('Save and continue'),
'#submit' => ['::submitForm', '::save'],
];
$element['submit_exit'] = [
'#type' => 'submit',
'#dropbutton' => 'save',
'#value' => t('Save and exit'),
'#submit' => ['::submitForm', '::save', '::collection'],
];
return $element;
}
/**
* Collection function makes redirection to route name.
*
* @param array $form
* Form object.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* From state object.
*/
public function collection(array $form, FormStateInterface $form_state) {
$form_state->setRedirect('entity.context.collection');
}
}
@@ -0,0 +1,230 @@
<?php
namespace Drupal\context_ui\Form;
use Drupal\Core\Form\FormState;
use Drupal\context\ContextManager;
use Drupal\context\Entity\Context;
use Drupal\Core\Entity\EntityForm;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
abstract class ContextFormBase extends EntityForm {
/**
* The entity being used by this form.
*
* @var \Drupal\context\ContextInterface
*/
protected $entity;
/**
* The Context module context manager.
*
* @var ContextManager
*/
protected $contextManager;
/**
* The Drupal context repository.
*
* @var ContextRepositoryInterface
*/
protected $contextRepository;
/**
* Construct a new context form.
*
* @param ContextManager $contextManager
* @param ContextRepositoryInterface $contextRepository
*/
function __construct(ContextManager $contextManager, ContextRepositoryInterface $contextRepository) {
$this->contextManager = $contextManager;
$this->contextRepository = $contextRepository;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('context.manager'),
$container->get('context.repository')
);
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $formState) {
$form['general'] = [
'#type' => 'fieldset',
'#title' => $this->t('General details'),
];
$form['general']['label'] = [
'#type' => 'textfield',
'#title' => $this->t('Label'),
'#default_value' => $this->entity->getLabel(),
'#required' => TRUE,
'#description' => $this->t('Enter label for this context.'),
];
$form['general']['name'] = [
'#type' => 'machine_name',
'#title' => $this->t('Machine name'),
'#default_value' => $this->entity->getName(),
'#machine_name' => [
'source' => ['general', 'label'],
'exists' => [$this, 'contextExists'],
],
];
$form['general']['group'] = [
'#type' => 'textfield',
'#title' => $this->t('Group'),
'#default_value' => $this->entity->getGroup(),
'#description' => $this->t('Enter name of the group this context should belong to.'),
'#autocomplete_route_name' => 'context.groups.autocomplete',
];
$form['general']['description'] = [
'#type' => 'textfield',
'#title' => $this->t('Description'),
'#default_value' => $this->entity->getDescription(),
'#description' => $this->t('Enter a description for this context definition.'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
if ($form_state->hasValue('reactions')) {
$this->validateReactions($form, $form_state);
}
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Save entity values that the built in submit handler cant take care of.
if ($form_state->hasValue('require_all_conditions')) {
$this->entity->setRequireAllConditions($form_state->getValue('require_all_conditions'));
}
if ($form_state->hasValue('conditions')) {
$this->handleConditions($form, $form_state);
}
if ($form_state->hasValue('reactions')) {
$this->handleReactions($form, $form_state);
}
// If the group is empty set it to the context no group value,
// otherwise Drupal will save it as an empty string instead.
if ($form_state->hasValue('group') && empty($form_state->getValue('group'))) {
$form_state->setValue('group', Context::CONTEXT_GROUP_NONE);
}
// Run the default submit method.
parent::submitForm($form, $form_state);
}
/**
* Handle submitting the condition plugins configuration forms.
*
* @param array $form
* The rendered form.
*
* @param FormStateInterface $form_state
* The current form state.
*/
private function handleConditions(array &$form, FormStateInterface $form_state) {
$conditions = $form_state->getValue('conditions', []);
// Loop trough each condition and update the configuration values by
// submitting the conditions form.
foreach ($conditions as $condition_id => $configuration) {
$condition = $this->entity->getCondition($condition_id);
$condition_values = (new FormState())->setValues($configuration);
$condition->submitConfigurationForm($form, $condition_values);
// If the condition is context aware then add context mapping to
// the condition.
if ($condition instanceof ContextAwarePluginInterface) {
$condition->setContextMapping($condition_values->getValue('context_mapping', []));
}
}
}
/**
* Handle submitting the context reaction plugins configuration forms.
*
* @param array $form
* The rendered form.
*
* @param FormStateInterface $form_state
* The current form state.
*/
private function handleReactions(array &$form, FormStateInterface $form_state) {
$reactions = $form_state->getValue('reactions', []);
// Loop trough each reaction and update the configuration values by
// submitting the reactions form.
foreach ($reactions as $reaction_id => $configuration) {
$reaction = $this->entity->getReaction($reaction_id);
$reaction_values = (new FormState())->setValues($configuration);
$reaction->submitConfigurationForm($form, $reaction_values);
}
}
/**
* Validate the context reaction plugins configuration forms.
*
* @param array $form
* The rendered form.
*
* @param FormStateInterface $form_state
* The current form state.
*/
private function validateReactions(array &$form, FormStateInterface $form_state) {
$reactions = $form_state->getValue('reactions', []);
// Loop trough each reaction and update the configuration values by
// validating the reactions form.
foreach ($reactions as $reaction_id => $configuration) {
$reaction = $this->entity->getReaction($reaction_id);
$reaction_values = (new FormState())->setValues($configuration);
$reaction->validateConfigurationForm($form, $reaction_values);
if ($reaction_values->hasAnyErrors()) {
// In case of errors, copy them back from the dummy FormState to the
// master form.
foreach ($reaction_values->getErrors() as $element => $error) {
$form_state->setErrorByName("reactions][$reaction_id][$element", $error);
}
}
}
}
/**
* Check to see if a context already exists with the specified name.
*
* @param string $name
* The machine name to check for.
*
* @return bool
*/
public function contextExists($name) {
return $this->contextManager->contextExists($name);
}
}
@@ -0,0 +1,143 @@
<?php
namespace Drupal\context_ui\Form;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\context\ContextManager;
use Drupal\context\ContextInterface;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\context\ContextReactionInterface;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Drupal\Core\DependencyInjection\ContainerInjectionInterface;
class ReactionDeleteForm extends ConfirmFormBase implements ContainerInjectionInterface {
/**
* @var ContextInterface
*/
protected $context;
/**
* @var ContextReactionInterface
*/
protected $reaction;
/**
* The Context module context manager.
*
* @var ContextManager
*/
protected $contextManager;
/**
* Construct.
*
* @param ContextManager $contextManager
*/
function __construct(ContextManager $contextManager) {
$this->contextManager = $contextManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('context.manager')
);
}
/**
* Returns the question to ask the user.
*
* @return string
* The form question. The page title will be set to this value.
*/
public function getQuestion() {
return $this->t('Are you sure you want to remove the %reaction reaction.', [
'%reaction' => $this->reaction->getPluginDefinition()['label'],
]);
}
/**
* Returns the route to go to if the user cancels the action.
*
* @return \Drupal\Core\Url
* A URL object.
*/
public function getCancelUrl() {
return $this->context->urlInfo();
}
/**
* Returns a unique string identifying the form.
*
* @return string
* The unique string identifying the form.
*/
public function getFormId() {
return 'context_reaction_delete_confirm';
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ContextInterface $context = NULL, $reaction_id = NULL) {
$this->context = $context;
$this->reaction = $this->context->getReaction($reaction_id);
$form = parent::buildForm($form, $form_state);
// Remove the cancel button if this is an AJAX request since Drupals built
// in modal dialogues does not handle buttons that are not a primary
// button very well.
if ($this->getRequest()->isXmlHttpRequest()) {
unset($form['actions']['cancel']);
}
$form['actions']['submit']['#ajax'] = [
'callback' => '::submitFormAjax',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$definition = $this->reaction->getPluginDefinition();
$this->context->removeReaction($this->reaction->getPluginId());
$this->context->save();
// If this is not an AJAX request then redirect and show a message.
if (!$this->getRequest()->isXmlHttpRequest()) {
drupal_set_message($this->t('The %label context reaction has been removed.', [
'%label' => $definition['label']]
));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}
/**
* Handle when the form is submitted through AJAX.
*
* @return AjaxResponse
*/
public function submitFormAjax() {
$response = new AjaxResponse();
$contextForm = $this->contextManager->getForm($this->context, 'edit');
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new ReplaceCommand('#context-reactions', $contextForm['reactions']));
return $response;
}
}
@@ -0,0 +1,215 @@
<?php
namespace Drupal\context;
use Drupal\Core\Condition\ConditionInterface;
use Drupal\Core\Condition\ConditionPluginCollection;
use Drupal\Core\Config\Entity\ConfigEntityInterface;
use Drupal\context\Plugin\ContextReactionPluginCollection;
use Drupal\Core\Entity\EntityWithPluginCollectionInterface;
interface ContextInterface extends ConfigEntityInterface, EntityWithPluginCollectionInterface {
/**
* The default value for a context that is not assigned to a group.
*/
const CONTEXT_GROUP_NONE = NULL;
/**
* Get the ID of the context.
*
* @return string
*/
public function id();
/**
* Get the machine name of the context.
*
* @return string
*/
public function getName();
/**
* Set the machine name of the context.
*
* @param string $name
*
* @return $this
*/
public function setName($name);
/**
* Get the context label.
*
* @return string
*/
public function getLabel();
/**
* Set the context label.
*
* @param string $label
*
* @return $this
*/
public function setLabel($label);
/**
* Get the context description.
*
* @return string
*/
public function getDescription();
/**
* Set the context description.
*
* @param string $description
*
* @return $this
*/
public function setDescription($description);
/**
* Get the group this context belongs to.
*
* @return null|string
*/
public function getGroup();
/**
* Set the group this context should belong to.
*
* @param null|string $group
*
* @return $this
*/
public function setGroup($group);
/**
* Get the weight for this context.
*
* @return int
*/
public function getWeight();
/**
* Set the weight for this context.
*
* @param int $weight
* The weight to set for this context.
*
* @return $this
*/
public function setWeight($weight);
/**
* If the context requires all conditions to validate.
*
* @return boolean
*/
public function requiresAllConditions();
/**
* Set if all conditions should be required for this context to validate.
*
* @param bool $require
* If a condition is required or not.
*
* @return $this
*/
public function setRequireAllConditions($require);
/**
* Get a list of all conditions.
*
* @return ConditionInterface[]|ConditionPluginCollection
*/
public function getConditions();
/**
* Get a condition with the specified ID.
*
* @param string $condition_id
* The condition to get.
*
* @return \Drupal\Core\Condition\ConditionInterface
*/
public function getCondition($condition_id);
/**
* Set the conditions.
*
* @param array $configuration
* The configuration for the condition plugin.
*
* @return string
*/
public function addCondition(array $configuration);
/**
* Remove the specified condition.
*
* @param string $condition_id
* The id of the condition to remove.
*
* @return $this
*/
public function removeCondition($condition_id);
/**
* Check to see if the context has the specified condition.
*
* @param string $condition_id
* The ID of the condition to check for.
*
* @return bool
*/
public function hasCondition($condition_id);
/**
* Get a list of all the reactions.
*
* @return ContextReactionInterface[]|ContextReactionPluginCollection
*/
public function getReactions();
/**
* Get a reaction with the specified ID.
*
* @param string $reaction_id
* The ID of the reaction to get.
*
* @return ContextReactionInterface
*/
public function getReaction($reaction_id);
/**
* Add a context reaction.
*
* @param array $configuration
*
* @return string
*/
public function addReaction(array $configuration);
/**
* Remove the specified reaction.
*
* @param string $reaction_id
* The id of the reaction to remove.
*
* @return $this
*/
public function removeReaction($reaction_id);
/**
* Check to see if the context has the specified reaction.
*
* @param string $reaction_id
* The ID of the reaction to check for.
*
* @return bool
*/
public function hasReaction($reaction_id);
}
@@ -0,0 +1,360 @@
<?php
namespace Drupal\context;
use Drupal\context\Entity\Context;
use Drupal\context\Plugin\ContextReaction\Blocks;
use Drupal\Core\Entity\Query\QueryFactory;
use Drupal\Core\Entity\EntityManagerInterface;
use Drupal\Core\Entity\EntityFormBuilderInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Condition\ConditionPluginCollection;
use Drupal\Component\Plugin\Exception\ContextException;
use Drupal\Core\Condition\ConditionAccessResolverTrait;
use Drupal\Core\Plugin\Context\ContextHandlerInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\Theme\ThemeManagerInterface;
/**
* This is the manager service for the context module and should not be
* confused with the built in contexts in Drupal.
*/
class ContextManager {
use ConditionAccessResolverTrait;
use StringTranslationTrait;
/**
* @var \Drupal\Core\Entity\Query\QueryFactory
*/
protected $entityQuery;
/**
* @var \Drupal\Core\Entity\EntityManagerInterface
*/
protected $entityManager;
/**
* @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
*/
protected $contextRepository;
/**
* @var \Drupal\Core\Plugin\Context\ContextHandlerInterface
*/
protected $contextHandler;
/**
* If the context conditions has been evaluated then this is set to TRUE
* otherwise FALSE.
*
* @var bool
*/
protected $contextConditionsEvaluated = FALSE;
/**
* An array of contexts that have been evaluated and are active.
*
* @var array
*/
protected $activeContexts = [];
/**
* @var \Drupal\Core\Entity\EntityFormBuilderInterface
*/
private $entityFormBuilder;
/**
* @var \Drupal\Core\Theme\ThemeManagerInterface;
*/
protected $themeManager;
/**
* Construct.
*
* @param QueryFactory $entityQuery
* The Drupal entity query service.
*
* @param EntityManagerInterface $entityManager
* The Drupal entity manager service.
*
* @param ContextRepositoryInterface $contextRepository
* The drupal context repository service.
*
* @param ContextHandlerInterface $contextHandler
* The Drupal context handler service.
*
* @param ThemeManagerInterface $themeManager
* The Drupal theme manager service.
*
* @param \Drupal\Core\Entity\EntityFormBuilderInterface $entityFormBuilder
*/
function __construct(
QueryFactory $entityQuery,
EntityManagerInterface $entityManager,
ContextRepositoryInterface $contextRepository,
ContextHandlerInterface $contextHandler,
EntityFormBuilderInterface $entityFormBuilder,
ThemeManagerInterface $themeManager
)
{
$this->entityQuery = $entityQuery;
$this->entityManager = $entityManager;
$this->contextRepository = $contextRepository;
$this->contextHandler = $contextHandler;
$this->entityFormBuilder = $entityFormBuilder;
$this->themeManager = $themeManager;
}
/**
* Get all contexts.
*
* @return Context[]
*/
public function getContexts() {
$contextIds = $this->entityQuery
->get('context')
->execute();
$contexts = $this->entityManager
->getStorage('context')
->loadMultiple($contextIds);
// Sort the contexts by their weight.
uasort($contexts, [$this, 'sortContextsByWeight']);
return $contexts;
}
/**
* Get all contexts sorted by their group and sorted by their weight inside
* of each group.
*
* @return array
*/
public function getContextsByGroup() {
$contexts = $this->getContexts();
$groups = [];
// Add each context to their respective groups.
foreach ($contexts as $context_id => $context) {
$group = $context->getGroup();
if ($group === Context::CONTEXT_GROUP_NONE) {
$group = 'not_grouped';
}
$groups[$group][$context_id] = $context;
}
return $groups;
}
/**
* Check to validate that the context name does not already exist.
*
* @param string $name
* The machine name of the context to validate.
*
* @return bool
*/
public function contextExists($name) {
$entity = $this->entityQuery->get('context')
->condition('name', $name)
->execute();
return (bool) $entity;
}
/**
* Check to see if context conditions has been evaluated.
*
* @return bool
*/
public function conditionsHasBeenEvaluated() {
return $this->contextConditionsEvaluated;
}
/**
* Get the evaluated and active contexts.
*
* @return \Drupal\context\ContextInterface[]
*/
public function getActiveContexts() {
if ($this->conditionsHasBeenEvaluated()) {
return $this->activeContexts;
}
$this->evaluateContexts();
return $this->activeContexts;
}
/**
* Evaluate all context conditions.
*/
public function evaluateContexts() {
/** @var \Drupal\context\ContextInterface $context */
foreach ($this->getContexts() as $context) {
if ($this->evaluateContextConditions($context) && !$context->disabled()) {
$this->activeContexts[] = $context;
}
}
$this->contextConditionsEvaluated = TRUE;
}
/**
* Get all active reactions or reactions of a certain type.
*
* @param string $reactionType
* Either the reaction class name or the id of the reaction type to get.
*
* @return ContextReactionInterface[]
*/
public function getActiveReactions($reactionType = NULL) {
$reactions = [];
foreach ($this->getActiveContexts() as $context) {
// If no reaction type has been specified then add all reactions and
// continue to the next context.
if (is_null($reactionType)) {
foreach ($context->getReactions() as $reaction) {
// Only return block reaction if there is a block applied to the current theme.
if ($reaction instanceof Blocks) {
$blocks = $reaction->getBlocks();
$current_theme = $this->getCurrentTheme();
foreach ($blocks as $block) {
if ($block->getConfiguration()['theme'] == $current_theme) {
$reactions[] = $reaction;
break;
}
}
}
else {
$reactions[] = $reaction;
}
}
continue;
}
$contextReactions = $context->getReactions();
// Filter the reactions based on the reaction type.
foreach ($contextReactions as $reaction) {
if (class_exists($reactionType) && $reaction instanceof $reactionType) {
$reactions[] = $reaction;
continue;
}
if ($reaction->getPluginId() === $reactionType) {
$reactions[] = $reaction;
continue;
}
}
}
return $reactions;
}
/**
* Evaluate a contexts conditions.
*
* @param ContextInterface $context
* The context to evaluate conditions for.
*
* @return bool
*/
public function evaluateContextConditions(ContextInterface $context) {
$conditions = $context->getConditions();
// Apply context to any context aware conditions.
$this->applyContexts($conditions);
// Set the logic to use when validating the conditions.
$logic = $context->requiresAllConditions()
? 'and'
: 'or';
// Of there are no conditions then the context will be
// applied as a site wide context.
if (!count($conditions)) {
$logic = 'and';
}
return $this->resolveConditions($conditions, $logic);
}
/**
* Apply context to all the context aware conditions in the collection.
*
* @param ConditionPluginCollection $conditions
* A collection of conditions to apply context to.
*
* @return bool
*/
protected function applyContexts(ConditionPluginCollection &$conditions) {
foreach ($conditions as $condition) {
if ($condition instanceof ContextAwarePluginInterface) {
try {
$contexts = $this->contextRepository->getRuntimeContexts(array_values($condition->getContextMapping()));
$this->contextHandler->applyContextMapping($condition, $contexts);
}
catch (ContextException $e) {
return FALSE;
}
}
}
return TRUE;
}
/**
* Get a rendered form for the context.
* @param \Drupal\context\ContextInterface $context
* @param string $formType
* @param array $form_state_additions
* @return array
*/
public function getForm(ContextInterface $context, $formType = 'edit', array $form_state_additions = array()) {
return $this->entityFormBuilder->getForm($context, $formType, $form_state_additions);
}
/**
* Sorts an array of context entities by their weight.
*
* Callback for uasort().
*
* @param ContextInterface $a
* First item for comparison.
*
* @param ContextInterface $b
* Second item for comparison.
*
* @return int
* The comparison result for uasort().
*/
public function sortContextsByWeight(ContextInterface $a, ContextInterface $b) {
if ($a->getWeight() == $b->getWeight()) {
return 0;
}
return ($a->getWeight() < $b->getWeight()) ? -1 : 1;
}
/**
* Get current active theme.
*
* @return string
* Current active theme name.
*/
private function getCurrentTheme() {
return $this->themeManager->getActiveTheme()->getName();
}
}
@@ -0,0 +1,51 @@
<?php
namespace Drupal\context;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Lock\LockBackendInterface;
use Drupal\Core\Menu\MenuActiveTrail;
use Drupal\Core\Menu\MenuLinkManagerInterface;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\menu_link_content\Entity\MenuLinkContent;
/**
* Extend the MenuActiveTrail class.
*/
class ContextMenuActiveTrail extends MenuActiveTrail {
/**
* @var \Drupal\context\ContextManager.
*/
protected $contextManager;
/**
* {@inheritdoc}
*/
public function __construct(MenuLinkManagerInterface $menu_link_manager, RouteMatchInterface $route_match, CacheBackendInterface $cache, LockBackendInterface $lock, ContextManager $context_manager) {
parent::__construct($menu_link_manager, $route_match, $cache, $lock);
$this->contextManager = $context_manager;
}
/**
* {@inheritdoc}
*/
public function getActiveLink($menu_name = NULL) {
$found = parent::getActiveLink($menu_name);
// Get active reaction of Menu type.
foreach($this->contextManager->getActiveReactions('menu') as $reaction) {
$menu_items = $reaction->execute();
foreach ($menu_items as $menu_link_content) {
$menu = strtok($menu_link_content, ':');
if ($menu == $menu_name) {
$plugin_id = substr($menu_link_content, strlen($menu) + 1);
return $this->menuLinkManager->createInstance($plugin_id);
}
}
}
return $found;
}
}
@@ -0,0 +1,25 @@
<?php
namespace Drupal\context;
use Drupal\Core\Executable\ExecutableInterface;
use Drupal\Component\Plugin\PluginInspectionInterface;
use Drupal\Component\Plugin\ConfigurablePluginInterface;
use Drupal\Core\Plugin\PluginFormInterface;
interface ContextReactionInterface extends ConfigurablePluginInterface, PluginFormInterface, PluginInspectionInterface, ExecutableInterface {
/**
* Get the unique ID of this context reaction.
*
* @return string|null
*/
public function getId();
/**
* Provides a human readable summary of the condition's configuration.
*
* @return \Drupal\Core\StringTranslation\TranslatableMarkup
*/
public function summary();
}
@@ -0,0 +1,21 @@
<?php
namespace Drupal\context;
use Traversable;
use Drupal\Core\Plugin\DefaultPluginManager;
use Drupal\Core\Cache\CacheBackendInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
class ContextReactionManager extends DefaultPluginManager {
/**
* {@inheritdoc}
*/
public function __construct(\Traversable $namespaces, CacheBackendInterface $cache_backend, ModuleHandlerInterface $module_handler) {
parent::__construct('Plugin/ContextReaction', $namespaces, $module_handler, 'Drupal\context\ContextReactionInterface', 'Drupal\context\Reaction\Annotation\ContextReaction');
$this->alterInfo('context_condition_info');
$this->setCacheBackend($cache_backend, 'context_condition_plugins');
}
}
@@ -0,0 +1,68 @@
<?php
namespace Drupal\context;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\PluginBase;
abstract class ContextReactionPluginBase extends PluginBase implements ContextReactionInterface {
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->setConfiguration($configuration);
}
/**
* {@inheritdoc}
*/
public function getId() {
if (isset($this->getConfiguration()['id'])) {
return $this->getConfiguration()['id'];
}
return NULL;
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return [
'id' => $this->getPluginId(),
] + $this->configuration;
}
/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration) {
$this->configuration = $configuration + $this->defaultConfiguration();
return $this;
}
/**
* Form validation handler is optional.
*
* {@inheritdoc}
*/
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) {}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'saved' => FALSE,
];
}
/**
* {@inheritdoc}
*/
public function calculateDependencies() {
return [];
}
}
@@ -0,0 +1,23 @@
<?php
namespace Drupal\context;
use Drupal\Core\DependencyInjection\ContainerBuilder;
use Drupal\Core\DependencyInjection\ServiceProviderBase;
/**
* Alter the service container to use a custom class.
*/
class ContextServiceProvider extends ServiceProviderBase {
/**
* {@inheritdoc}
*/
public function alter(ContainerBuilder $container) {
// Override the menu active trail with a new class.
$definition = $container->getDefinition('menu.active_trail');
$definition->setClass('Drupal\context\ContextMenuActiveTrail');
$definition->addArgument($container->getDefinition('context.manager'));
}
}
@@ -0,0 +1,376 @@
<?php
namespace Drupal\context\Entity;
use Drupal;
use InvalidArgumentException;
use Drupal\context\ContextInterface;
use Drupal\Core\Config\Entity\ConfigEntityBase;
use Drupal\Core\Condition\ConditionPluginCollection;
use Drupal\context\Plugin\ContextReactionPluginCollection;
/**
* Defines the Context entity.
*
* @ConfigEntityType(
* id = "context",
* label = @Translation("Context"),
* handlers = {
* "access" = "Drupal\context\Entity\ContextAccess",
* "list_builder" = "Drupal\context_ui\ContextListBuilder",
* "form" = {
* "add" = "Drupal\context_ui\Form\ContextAddForm",
* "edit" = "Drupal\context_ui\Form\ContextEditForm",
* "delete" = "Drupal\context_ui\Form\ContextDeleteForm",
* "disable" = "Drupal\context_ui\Form\ContextDisableForm",
* }
* },
* links = {
* "edit-form" = "/admin/structure/context/{context}",
* "delete-form" = "/admin/structure/context/{context}/delete",
* "disable-form" = "/admin/structure/context/{context}/disable",
* "collection" = "/admin/structure/context",
* },
* admin_permission = "administer contexts",
* entity_keys = {
* "id" = "name",
* "label" = "label",
* },
* config_export = {
* "name",
* "label",
* "group",
* "description",
* "requireAllConditions",
* "disabled",
* "conditions",
* "reactions",
* "weight",
* }
* )
*/
class Context extends ConfigEntityBase implements ContextInterface {
/**
* The machine name of the context.
*
* @var string
*/
protected $name;
/**
* The label of the context.
*
* @var string
*/
protected $label;
/**
* A description for this context.
*
* @var string
*/
protected $description = '';
/**
* The group this context belongs to.
*
* @var string|null
*/
protected $group = self::CONTEXT_GROUP_NONE;
/**
* If all conditions must validate for this context.
*
* @var bool
*/
protected $requireAllConditions = FALSE;
/**
* The context conditions as a collection.
*
* @var ConditionPluginCollection
*/
protected $conditionsCollection;
/**
* The context reactions as a collection.
*
* @var ContextReactionPluginCollection
*/
protected $reactionsCollection;
/**
* A list of conditions this context should react to.
*
* @var array
*/
protected $conditions = [];
/**
* A list of reactions that should be taken when conditions match.
*
* @var array
*/
protected $reactions = [];
/**
* If the context is disabled or not.
*
* @var bool
*/
protected $disabled = FALSE;
/**
* The weight for this context.
*
* @var int
*/
protected $weight = 0;
/**
* Returns the ID of the context. The ID is the unique machine name of the
* context.
*/
public function id() {
return $this->name;
}
/**
* {@inheritdoc}
*/
public function getName() {
return $this->name;
}
/**
* {@inheritdoc}
*/
public function setName($name) {
if (!is_string($name)) {
throw new InvalidArgumentException('The context name must be a string.');
}
$this->name = $name;
return $this;
}
/**
* {@inheritdoc}
*/
public function getLabel() {
return $this->label;
}
/**
* {@inheritdoc}
*/
public function setLabel($label) {
if (!is_string($label)) {
throw new InvalidArgumentException('The context label must be a string.');
}
$this->label = $label;
return $this;
}
/**
* {@inheritdoc}
*/
public function getDescription() {
return $this->description;
}
/**
* {@inheritdoc}
*/
public function setDescription($description) {
if (!is_string($description)) {
throw new InvalidArgumentException('The context description must be a string.');
}
$this->description = $description;
return $this;
}
/**
* {@inheritdoc}
*/
public function getGroup() {
return $this->group;
}
/**
* {@inheritdoc}
*/
public function setGroup($group) {
$this->group = (is_string($group) && !empty($group)) ? $group : self::CONTEXT_GROUP_NONE;
return $this;
}
/**
* {@inheritdoc}
*/
public function getWeight() {
return $this->weight;
}
/**
* {@inheritdoc}
*/
public function setWeight($weight) {
$this->weight = (int) $weight;
return $this;
}
/**
* {@inheritdoc}
*/
public function requiresAllConditions() {
return $this->requireAllConditions;
}
/**
* {@inheritdoc}
*/
public function setRequireAllConditions($require) {
$this->requireAllConditions = (bool) $require;
return $this;
}
/**
* {@inheritdoc}
*/
public function getConditions() {
if (!$this->conditionsCollection) {
$conditionManager = Drupal::service('plugin.manager.condition');
$this->conditionsCollection = new ConditionPluginCollection($conditionManager, $this->conditions);
}
return $this->conditionsCollection;
}
/**
* {@inheritdoc}
*/
public function getCondition($condition_id) {
return $this->getConditions()->get($condition_id);
}
/**
* {@inheritdoc}
*/
public function addCondition(array $configuration) {
// Add an UUID to the condition to make sure the configuration is saved
// since the configuration export from the conditions collection wont
// export configuration that has not been "configured".
$configuration['uuid'] = $this->uuidGenerator()->generate();
$this->getConditions()->addInstanceId($configuration['id'], $configuration);
return $configuration['id'];
}
/**
* {@inheritdoc}
*/
public function removeCondition($condition_id) {
$this->getConditions()->removeInstanceId($condition_id);
return $this;
}
/**
* {@inheritdoc}
*/
public function hasCondition($condition_id) {
return $this->getConditions()->has($condition_id);
}
/**
* {@inheritdoc}
*/
public function getReactions() {
if (!$this->reactionsCollection) {
$reactionManager = Drupal::service('plugin.manager.context_reaction');
$this->reactionsCollection = new ContextReactionPluginCollection($reactionManager, $this->reactions);
}
return $this->reactionsCollection;
}
/**
* {@inheritdoc}
*/
public function getReaction($reaction_id) {
return $this->getReactions()->get($reaction_id);
}
/**
* {@inheritdoc}
*/
public function addReaction(array $configuration) {
// Add an UUID to the condition to make sure the configuration is saved
// since the configuration export from the conditions collection wont
// export configuration that has not been "configured".
$configuration['uuid'] = $this->uuidGenerator()->generate();
$this->getReactions()->addInstanceId($configuration['id'], $configuration);
return $configuration['id'];
}
/**
* {@inheritdoc}
*/
public function removeReaction($reaction_id) {
$this->getReactions()->removeInstanceId($reaction_id);
return $this;
}
/**
* {@inheritdoc}
*/
public function hasReaction($reaction_id) {
return $this->getReactions()->has($reaction_id);
}
/**
* Gets the plugin collections used by this entity.
*
* @return \Drupal\Component\Plugin\LazyPluginCollection[]
* An array of plugin collections, keyed by the property name they use to
* store their configuration.
*/
public function getPluginCollections() {
return [
'reactions' => $this->getReactions(),
'conditions' => $this->getConditions(),
];
}
/**
* Disable context.
*/
public function disable() {
$this->disabled = !$this->disabled();
$this->save();
}
/**
* {@inheritdoc}
*/
public function disabled() {
return $this->disabled;
}
}
@@ -0,0 +1,45 @@
<?php
/**
* @file
* Contains \Drupal\context\Entity\ContextAccess.
*/
namespace Drupal\context\Entity;
use Drupal\Core\Entity\EntityAccessControlHandler;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\Session\AccountInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines the access control handler for the page entity type.
*/
class ContextAccess extends EntityAccessControlHandler implements EntityHandlerInterface {
/**
* Constructs an access control handler instance.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type definition.
*/
public function __construct(EntityTypeInterface $entity_type) {
parent::__construct($entity_type);
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($entity_type);
}
/**
* {@inheritdoc}
*/
protected function checkAccess(EntityInterface $entity, $operation, AccountInterface $account) {
return parent::checkAccess($entity, $operation, $account);
}
}
@@ -0,0 +1,60 @@
<?php
/**
* @file
* Contains \Drupal\context\EventSubscriber\BlockPageDisplayVariantSubscriber.
*/
namespace Drupal\context\EventSubscriber;
use Drupal\context\ContextManager;
use Drupal\Core\Render\RenderEvents;
use Drupal\context\Plugin\ContextReaction\Blocks;
use Drupal\Core\Render\PageDisplayVariantSelectionEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* Selects the block page display variant.
*
* @see \Drupal\block\Plugin\DisplayVariant\BlockPageVariant
*/
class BlockPageDisplayVariantSubscriber implements EventSubscriberInterface {
/**
* @var \Drupal\context\ContextManager
*/
private $contextManager;
/**
* @param \Drupal\context\ContextManager $contextManager
*/
function __construct(ContextManager $contextManager) {
$this->contextManager = $contextManager;
}
/**
* Selects the context block page display variant.
*
* @param \Drupal\Core\Render\PageDisplayVariantSelectionEvent $event
* The event to process.
*/
public function onSelectPageDisplayVariant(PageDisplayVariantSelectionEvent $event) {
// Activate the context block page display variant if any of the reactions
// is a blocks reaction.
foreach ($this->contextManager->getActiveReactions() as $reaction) {
if ($reaction instanceof Blocks) {
$event->setPluginId('context_block_page');
break;
}
}
}
/**
* {@inheritdoc}
*/
static function getSubscribedEvents() {
$events[RenderEvents::SELECT_PAGE_DISPLAY_VARIANT][] = array('onSelectPageDisplayVariant');
return $events;
}
}
@@ -0,0 +1,49 @@
<?php
/**
* @file
* Contains \Drupal\context\Form\AjaxFormTrait.
*/
namespace Drupal\context\Form;
use Drupal\Component\Serialization\Json;
use Drupal\Component\Utility\NestedArray;
/**
* Provides helper methods for using an AJAX modal. This is a copy of the
* ctools AjaxFormTrait.
*/
trait AjaxFormTrait {
/**
* Gets attributes for use with an AJAX modal.
*
* @return array
*/
public static function getAjaxAttributes() {
return [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 1000,
]),
];
}
/**
* Gets attributes for use with an add button AJAX modal.
*
* @return array
*/
public static function getAjaxButtonAttributes() {
return NestedArray::mergeDeep(AjaxFormTrait::getAjaxAttributes(), [
'class' => [
'button',
'button--small',
'button-action',
],
]);
}
}
@@ -0,0 +1,36 @@
<?php
namespace Drupal\context\Plugin\Condition;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\system\Plugin\Condition\RequestPath;
/**
* Provides a 'Request path exclusion' condition.
*
* @Condition(
* id = "request_path_exclusion",
* label = @Translation("Request path exclusion"),
* context = {
* "request_path_exclusion" = @ContextDefinition("request_path_exclusion", label = @Translation("Request path exclusion"))
* }
* )
*/
class RequestPathExclusion extends RequestPath implements ContainerFactoryPluginInterface {
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form = parent::buildConfigurationForm($form, $form_state);
unset($form['negate']);
return $form;
}
/**
* {@inheritdoc}
*/
public function evaluate() {
return !parent::evaluate();
}
}
@@ -0,0 +1,681 @@
<?php
namespace Drupal\context\Plugin\ContextReaction;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\Core\Form\FormState;
use Drupal\Core\Render\Element;
use Drupal\context\ContextInterface;
use Drupal\context\Form\AjaxFormTrait;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Component\Uuid\UuidInterface;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Theme\ThemeManagerInterface;
use Drupal\context\ContextReactionPluginBase;
use Drupal\Core\Block\TitleBlockPluginInterface;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\context\Reaction\Blocks\BlockCollection;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Block\MainContentBlockPluginInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Plugin\Context\ContextHandlerInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a content reaction that will let you place blocks in the current
* themes regions.
*
* @ContextReaction(
* id = "blocks",
* label = @Translation("Blocks")
* )
*/
class Blocks extends ContextReactionPluginBase implements ContainerFactoryPluginInterface {
use AjaxFormTrait;
/**
* An array of blocks to be displayed with this reaction.
*
* @var array
*/
protected $blocks = [];
/**
* Contains a temporary collection of blocks.
*
* @var BlockCollection
*/
protected $blocksCollection;
/**
* The Drupal UUID service.
*
* @var \Drupal\Component\Uuid\UuidInterface
*/
protected $uuid;
/**
* @var \Drupal\Core\Theme\ThemeManagerInterface
*/
protected $themeManager;
/**
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* @var ContextRepositoryInterface
*/
protected $contextRepository;
/**
* @var ContextHandlerInterface
*/
protected $contextHandler;
/**
* @var AccountInterface
*/
protected $account;
/**
* {@inheritdoc}
*/
function __construct(
array $configuration,
$pluginId,
$pluginDefinition,
UuidInterface $uuid,
ThemeManagerInterface $themeManager,
ThemeHandlerInterface $themeHandler,
ContextRepositoryInterface $contextRepository,
ContextHandlerInterface $contextHandler,
AccountInterface $account
) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->uuid = $uuid;
$this->themeManager = $themeManager;
$this->themeHandler = $themeHandler;
$this->contextRepository = $contextRepository;
$this->contextHandler = $contextHandler;
$this->account = $account;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
return new static(
$configuration,
$pluginId,
$pluginDefinition,
$container->get('uuid'),
$container->get('theme.manager'),
$container->get('theme_handler'),
$container->get('context.repository'),
$container->get('context.handler'),
$container->get('current_user')
);
}
/**
* Executes the plugin.
*
* @param array $build
* The current build of the page.
*
* @param string|null $title
* The page title.
*
* @param string|null $main_content
* The main page content.
*
* @return array
*/
public function execute(array $build = array(), $title = NULL, $main_content = NULL) {
$cacheability = CacheableMetadata::createFromRenderArray($build);
// Use the currently active theme to fetch blocks.
$theme = $this->themeManager->getActiveTheme()->getName();
$regions = $this->getBlocks()->getAllByRegion($theme);
// Add each block to the page build.
foreach ($regions as $region => $blocks) {
/** @var $blocks BlockPluginInterface[] */
foreach ($blocks as $block_id => $block) {
$configuration = $block->getConfiguration();
$block_placement_key = $this->blockShouldBePlacedUniquely($block)
? $block_id
: $block->getConfiguration()['id'];
if ($block instanceof MainContentBlockPluginInterface) {
if (isset($build['content']['system_main'])) {
unset($build['content']['system_main']);
}
$block->setMainContent($main_content);
}
// Make sure the user is allowed to view the block.
$access = $block->access($this->account, TRUE);
$cacheability->addCacheableDependency($access);
// If the user is not allowed then do not render the block.
if (!$access->isAllowed()) {
continue;
}
if ($block instanceof TitleBlockPluginInterface) {
if (isset($build['content']['messages'])) {
unset($build['content']['messages']);
}
$block->setTitle($title);
}
// Inject runtime contexts.
if ($block instanceof ContextAwarePluginInterface) {
$contexts = $this->contextRepository->getRuntimeContexts($block->getContextMapping());
$this->contextHandler->applyContextMapping($block, $contexts);
}
// Create the render array for the block as a whole.
// @see template_preprocess_block().
$blockBuild = [
'#theme' => 'block',
'#attributes' => [
'class' => [$block->getConfiguration()['css_class']]
],
'#configuration' => $configuration,
'#plugin_id' => $block->getPluginId(),
'#base_plugin_id' => $block->getBaseId(),
'#derivative_plugin_id' => $block->getDerivativeId(),
'#block_plugin' => $block,
'#pre_render' => [[$this, 'preRenderBlock']],
'#cache' => [
'keys' => ['context_blocks_reaction', 'block', $block_placement_key],
'tags' => $block->getCacheTags(),
'contexts' => $block->getCacheContexts(),
'max-age' => $block->getCacheMaxAge(),
],
];
// Add contextual links to block.
$content = $block->build();
if (isset($content['#contextual_links'])) {
$blockBuild['#contextual_links'] = $content['#contextual_links'];
}
// Add additional contextual link, for editing block configuration.
$blockBuild['#contextual_links']['context_block'] = [
'route_parameters' => [
'context' => $configuration['context_id'],
'reaction_id' => 'blocks',
'block_id' => $block->getConfiguration()['uuid'],
],
];
if (array_key_exists('weight', $configuration)) {
$blockBuild['#weight'] = $configuration['weight'];
}
$build[$region][$block_placement_key] = $blockBuild;
// After merging with blocks from Block layout, we want to sort all of
// them again.
$build[$region]['#sorted'] = FALSE;
// The main content block cannot be cached: it is a placeholder for the
// render array returned by the controller. It should be rendered as-is,
// with other placed blocks "decorating" it. Analogous reasoning for the
// title block.
if ($block instanceof MainContentBlockPluginInterface || $block instanceof TitleBlockPluginInterface) {
unset($build[$region][$block_placement_key]['#cache']['keys']);
}
$cacheability->addCacheableDependency($block);
}
}
$cacheability->applyTo($build);
return $build;
}
/**
* Renders the content using the provided block plugin.
*
* @param array $build
* @return array
*/
public function preRenderBlock($build) {
$content = $build['#block_plugin']->build();
unset($build['#block_plugin']);
// Abort rendering: render as the empty string and ensure this block is
// render cached, so we can avoid the work of having to repeatedly
// determine whether the block is empty. E.g. modifying or adding entities
// could cause the block to no longer be empty.
if (is_null($content) || Element::isEmpty($content)) {
$build = [
'#markup' => '',
'#cache' => $build['#cache'],
];
// If $content is not empty, then it contains cacheability metadata, and
// we must merge it with the existing cacheability metadata. This allows
// blocks to be empty, yet still bubble cacheability metadata, to indicate
// why they are empty.
if (!empty($content)) {
CacheableMetadata::createFromRenderArray($build)
->merge(CacheableMetadata::createFromRenderArray($content))
->applyTo($build);
}
}
else {
$build['content'] = $content;
}
return $build;
}
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return [
'blocks' => []
] + parent::defaultConfiguration();
}
/**
* {@inheritdoc}
*/
public function setConfiguration(array $configuration) {
$this->configuration = $configuration + $this->defaultConfiguration();
if (isset($configuration['blocks'])) {
$this->blocks = $configuration['blocks'];
}
return $this;
}
/**
* {@inheritdoc}
*/
public function getConfiguration() {
return [
'blocks' => $this->getBlocks()->getConfiguration(),
] + parent::getConfiguration();
}
/**
* {@inheritdoc}
*/
public function summary() {
return $this->t('Lets you add blocks to the selected themes regions');
}
/**
* Get all blocks as a collection.
*
* @return BlockPluginInterface[]|BlockCollection
*/
public function getBlocks() {
if (!$this->blocksCollection) {
$blockManager = \Drupal::service('plugin.manager.block');
$this->blocksCollection = new BlockCollection($blockManager, $this->blocks);
}
return $this->blocksCollection;
}
/**
* Get a block by id.
*
* @param string $blockId
* The ID of the block to get.
*
* @return BlockPluginInterface
*/
public function getBlock($blockId) {
return $this->getBlocks()->get($blockId);
}
/**
* Add a new block.
*
* @param array $configuration
*/
public function addBlock(array $configuration) {
$configuration['uuid'] = $this->uuid->generate();
$this->getBlocks()->addInstanceId($configuration['uuid'], $configuration);
return $configuration['uuid'];
}
/**
* Update an existing blocks configuration.
*
* @param string $blockId
* The ID of the block to update.
*
* @param $configuration
* The updated configuration for the block.
*
* @return $this
*/
public function updateBlock($blockId, array $configuration) {
$existingConfiguration = $this->getBlock($blockId)->getConfiguration();
$this->getBlocks()->setInstanceConfiguration($blockId, $configuration + $existingConfiguration);
return $this;
}
/**
* @param $blockId
* @return $this
*/
public function removeBlock($blockId) {
$this->getBlocks()->removeInstanceId($blockId);
return $this;
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state, ContextInterface $context = NULL) {
$form['#attached']['library'][] = 'block/drupal.block';
$themes = $this->themeHandler->listInfo();
$default_theme = $this->themeHandler->getDefault();
// Select list for changing themes.
$form['theme'] = [
'#type' => 'select',
'#title' => $this->t('Theme'),
'#options' => [],
'#description' => $this->t('Select the theme you want to display regions for.'),
'#default_value' => $form_state->getValue('theme', $default_theme),
'#ajax' => [
'url' => Url::fromRoute('context.reaction.blocks.regions', [
'context' => $context->id(),
]),
],
];
// Add each theme to the theme select.
foreach ($themes as $theme_id => $theme) {
if ($theme_id === $default_theme) {
$form['theme']['#options'][$theme_id] = $this->t('%theme (Default)', [
'%theme' => $theme->info['name'],
]);
}
else {
$form['theme']['#options'][$theme_id] = $theme->info['name'];
}
}
$form['blocks'] = [
'#type' => 'container',
'#attributes' => [
'id' => 'context-reaction-blocks-container',
],
];
$form['blocks']['include_default_blocks'] = [
'#type' => 'checkbox',
'#title' => $this->t('Include blocks from Block layout'),
'#description' => $this->t('if checked, all blocks from default Block layout will also be included in page build.'),
'#weight' => -10,
'#default_value' => isset($this->getConfiguration()['include_default_blocks']) ? $this->getConfiguration()['include_default_blocks'] : FALSE,
];
$form['blocks']['block_add'] = [
'#type' => 'link',
'#title' => $this->t('Place block'),
'#attributes' => [
'id' => 'context-reaction-blocks-region-add',
] + $this->getAjaxButtonAttributes(),
'#url' => Url::fromRoute('context.reaction.blocks.library', [
'context' => $context->id(),
'reaction_id' => $this->getPluginId(),
], [
'query' => [
'theme' => $form_state->getValue('theme', $default_theme),
],
]),
];
$form['blocks']['blocks'] = [
'#type' => 'table',
'#header' => [
$this->t('Block'),
$this->t('Category'),
$this->t('Unique'),
$this->t('Region'),
$this->t('Weight'),
$this->t('Operations'),
],
'#empty' => $this->t('No regions available to place blocks in.'),
'#attributes' => [
'id' => 'blocks',
],
];
// If a theme has been selected use that to get the regions otherwise use
// the default theme.
$theme = $form_state->getValue('theme', $default_theme);
// Get all blocks by their regions.
$blocks = $this->getBlocks()->getAllByRegion($theme);
// Get regions of the selected theme.
$regions = $this->getSystemRegionList($theme);
// Add each region.
foreach ($regions as $region => $title) {
// Add the tabledrag details for this region.
$form['blocks']['blocks']['#tabledrag'][] = [
'action' => 'match',
'relationship' => 'sibling',
'group' => 'block-region-select',
'subgroup' => 'block-region-' . $region,
'hidden' => FALSE,
];
$form['blocks']['blocks']['#tabledrag'][] = [
'action' => 'order',
'relationship' => 'sibling',
'group' => 'block-weight',
'subgroup' => 'block-weight-' . $region,
];
// Add the theme region.
$form['blocks']['blocks']['region-' . $region] = [
'#attributes' => [
'class' => ['region-title'],
],
'title' => [
'#markup' => $title,
'#wrapper_attributes' => [
'colspan' => 6,
],
],
];
$regionEmptyClass = empty($blocks[$region])
? 'region-empty'
: 'region-populated';
$form['blocks']['blocks']['region-' . $region . '-message'] = [
'#attributes' => [
'class' => ['region-message', 'region-' . $region . '-message', $regionEmptyClass],
],
'message' => [
'#markup' => '<em>' . $this->t('No blocks in this region') . '</em>',
'#wrapper_attributes' => [
'colspan' => 6,
],
],
];
// Add each block specified for the region if there are any.
if (isset($blocks[$region])) {
/** @var BlockPluginInterface $block */
foreach ($blocks[$region] as $block_id => $block) {
$configuration = $block->getConfiguration();
$operations = [
'edit' => [
'title' => $this->t('Edit'),
'url' => Url::fromRoute('context.reaction.blocks.block_edit', [
'context' => $context->id(),
'reaction_id' => $this->getPluginId(),
'block_id' => $block_id,
], [
'query' => [
'theme' => $theme,
],
]),
'attributes' => $this->getAjaxAttributes(),
],
'delete' => [
'title' => $this->t('Delete'),
'url' => Url::fromRoute('context.reaction.blocks.block_delete', [
'context' => $context->id(),
'block_id' => $block_id,
]),
'attributes' => $this->getAjaxAttributes(),
],
];
$form['blocks']['blocks'][$block_id] = [
'#attributes' => [
'class' => ['draggable'],
],
'label' => [
'#markup' => $block->label(),
],
'category' => [
'#markup' => $block->getPluginDefinition()['category'],
],
'unique' => [
'#markup' => $this->blockShouldBePlacedUniquely($block) ? $this->t('Yes') : $this->t('No'),
],
'region' => [
'#type' => 'select',
'#title' => $this->t('Region for @block block', ['@block' => $block->label()]),
'#title_display' => 'invisible',
'#default_value' => $region,
'#options' => $regions,
'#attributes' => [
'class' => ['block-region-select', 'block-region-' . $region],
],
],
'weight' => [
'#type' => 'weight',
'#default_value' => isset($configuration['weight']) ? $configuration['weight'] : 0,
'#title' => $this->t('Weight for @block block', ['@block' => $block->label()]),
'#title_display' => 'invisible',
'#attributes' => [
'class' => ['block-weight', 'block-weight-' . $region],
],
],
'operations' => [
'#type' => 'operations',
'#links' => $operations,
],
];
}
}
}
return $form;
}
/**
* Check to see if the block should be uniquely placed.
*
* @param BlockPluginInterface $block
*
* @return bool
*/
private function blockShouldBePlacedUniquely(BlockPluginInterface $block) {
$configuration = $block->getConfiguration();
return (isset($configuration['unique']) && $configuration['unique']);
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$blocks = $form_state->getValue(['blocks', 'blocks'], []);
// Save configuration for including default blocks.
$config = $this->getConfiguration();
$config['include_default_blocks'] = $form_state->getValue(['blocks', 'include_default_blocks'], FALSE);
$this->setConfiguration($config);
if (is_array($blocks)) {
foreach ($blocks as $block_id => $configuration) {
$block = $this->getBlock($block_id);
$configuration += $block->getConfiguration();
$block_state = (new FormState())->setValues($configuration);
$block->submitConfigurationForm($form, $block_state);
// If the block is context aware then add context mapping to the block.
if ($block instanceof ContextAwarePluginInterface) {
$block->setContextMapping($block_state->getValue('context_mapping', []));
}
$this->updateBlock($block_id, $block_state->getValues());
}
}
}
/**
* Should reaction include default blocks from Block layout.
*
* @return bool
*/
public function includeDefaultBlocks() {
$config = $this->getConfiguration();
return isset($config['include_default_blocks']) ? $config['include_default_blocks'] : FALSE;
}
/**
* Wraps system_region_list().
*
* @param string $theme
* The theme to get a list of regions for.
*
* @param string $show
* What type of regions that should be returned, defaults to all regions.
*
* @return array
*
* @todo This could be moved to a service since we use it in a couple of places.
*/
protected function getSystemRegionList($theme, $show = REGIONS_ALL) {
return system_region_list($theme, $show);
}
}
@@ -0,0 +1,66 @@
<?php
namespace Drupal\context\Plugin\ContextReaction;
use Drupal\context\ContextReactionPluginBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a content reaction that adds a new css class.
*
* @ContextReaction(
* id = "body_class",
* label = @Translation("Body class")
* )
*/
class BodyClass extends ContextReactionPluginBase {
/**
* {@inheritdoc}
*/
public function defaultConfiguration() {
return parent::defaultConfiguration() + [
'body_class' => '',
];
}
/**
* {@inheritdoc}
*/
public function summary() {
return $this->getConfiguration()['body_class'];
}
/**
* {@inheritdoc}
*/
public function execute(array &$vars = []) {
return [
'class' => explode(' ', $this->getConfiguration()['body_class']),
];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$form['body_class'] = [
'#title' => $this->t('Section class'),
'#type' => 'textfield',
'#description' => $this->t('Provides this text as additional body class in the html.html.twig.'),
'#default_value' => $this->getConfiguration()['body_class'],
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$this->setConfiguration([
'body_class' => $form_state->getValue('body_class'),
]);
}
}
@@ -0,0 +1,91 @@
<?php
namespace Drupal\context\Plugin\ContextReaction;
use Drupal\context\ContextReactionPluginBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Menu\MenuParentFormSelectorInterface;
use Drupal\Core\Menu\MenuTreeParameters;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a content reaction that adds a css 'active' class to menu item.
*
* @ContextReaction(
* id = "menu",
* label = @Translation("Menu")
* )
*/
class Menu extends ContextReactionPluginBase implements ContainerFactoryPluginInterface {
/**
* @var \Drupal\Core\Menu\MenuParentFormSelector
*/
protected $menuParentFormSelector;
/**
* {@inheritdoc}
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, MenuParentFormSelectorInterface $menu_parent_form_selector) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->menuParentFormSelector = $menu_parent_form_selector;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('menu.parent_form_selector')
);
}
/**
* {@inheritdoc}
*/
public function summary() {
return $this->t('Set active menu item based on conditions.');
}
/**
* {@inheritdoc}
*/
public function execute(array &$vars = []) {
$config = $this->getConfiguration();
return $config['menu'];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$parent_element = $this->menuParentFormSelector->parentSelectElement('main:');
$config = $this->getConfiguration();
$form['menu_items'] = [
'#title' => $this->t('Menu'),
'#type' => 'select',
'#options' => $parent_element['#options'],
'#multiple' => TRUE,
'#default_value' => isset($config['menu']) ? $config['menu'] : '',
'#size' => 15,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$values = array_keys($form_state->getValue('menu_items'));
$this->setConfiguration([
'menu' => $values,
]);
}
}
@@ -0,0 +1,55 @@
<?php
namespace Drupal\context\Plugin\ContextReaction;
use Drupal\context\ContextReactionPluginBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Provides a content reaction that will let you change theme.
*
* @ContextReaction(
* id = "page_template_suggestions",
* label = @Translation("Page template suggestions")
* )
*/
class PageTemplateSuggestions extends ContextReactionPluginBase {
/**
* {@inheritdoc}
*/
public function summary() {
return $this->t('Gives you ability to add template suggestions.');
}
/**
* Executes the plugin.
*/
public function execute() {
$config = $this->getConfiguration();
return $config['suggestions'];
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$config = $this->getConfiguration();
$form['suggestions'] = [
'#type' => 'textarea',
'#title' => $this->t('Page template suggestions'),
'#default_value' => isset($config['suggestions']) ? $config['suggestions'] : '',
'#description' => $this->t('Enter page template suggestions such as "page__front", one per line, in order of preference (using underscores instead of hyphens). Entered template suggestions will override page.html.twig template.'),
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$config['suggestions'] = str_replace("\r\n", "\n", $form_state->getValue('suggestions'));
$this->setConfiguration($config);
}
}
@@ -0,0 +1,170 @@
<?php
namespace Drupal\context\Plugin\ContextReaction;
use Drupal\context\ContextReactionPluginBase;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Theme\ThemeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a content reaction that will let you disable regions.
*
* @ContextReaction(
* id = "regions",
* label = @Translation("Regions")
* )
*/
class Regions extends ContextReactionPluginBase implements ContainerFactoryPluginInterface {
/**
* An array of regions to be disabled with this reaction.
*
* @var array
*/
protected $regions = [];
/**
* @var \Drupal\Core\Theme\ThemeManagerInterface
*/
protected $themeManager;
/**
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* {@inheritdoc}
*/
function __construct(
array $configuration,
$pluginId,
$pluginDefinition,
ThemeManagerInterface $themeManager,
ThemeHandlerInterface $themeHandler
) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->themeManager = $themeManager;
$this->themeHandler = $themeHandler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
return new static(
$configuration,
$pluginId,
$pluginDefinition,
$container->get('theme.manager'),
$container->get('theme_handler')
);
}
/**
* {@inheritdoc}
*/
public function summary() {
return $this->t('Lets you remove regions from selected theme.');
}
/**
* Executes the plugin.
*/
public function execute() {
// TODO: Implement execute() method.
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$themes = $this->themeHandler->listInfo();
$default_theme = $this->themeHandler->getDefault();
// Build configuration form for each installed theme.
foreach ($themes as $theme_id => $theme) {
if ($theme_id == $default_theme) {
$title = $this->t('Disable Regions in %theme (Default)', [
'%theme' => $theme->info['name'],
]);
}
else {
$title = $this->t('Disable Regions in %theme', [
'%theme' => $theme->info['name'],
]);
}
$form[$theme_id] = [
'#type' => 'details',
'#title' => $title,
'#weight' => 5,
'#open' => FALSE,
];
// Get regions of the theme.
$regions = $this->getSystemRegionList($theme_id);
// Get disabled regions.
$disabled_regions = $this->getDisabledRegions();
$form[$theme_id]['regions'] = [
'#type' => 'checkboxes',
'#options' => $regions,
'#title' => $this->t('Disable the following'),
'#default_value' => isset($disabled_regions[$theme_id]) ? $disabled_regions[$theme_id] : [],
];
}
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$themes = $form_state->getValues();
if (is_array($themes)) {
foreach ($themes as $theme_name => $region) {
$disabled_regions = array_keys(array_filter($region['regions']));
if (!empty($disabled_regions)) {
$configuration['regions'][$theme_name] = $disabled_regions;
$configuration += $this->getConfiguration();
}
else {
$configuration['regions'][$theme_name] = [];
$configuration += $this->getConfiguration();
}
$this->setConfiguration($configuration);
}
}
}
/**
* Wraps system_region_list().
*
* @param string $theme
* The theme to get a list of regions for.
*
* @param string $show
* What type of regions that should be returned, defaults to all regions.
*
* @return array
*
* @todo This could be moved to a service since we use it in a couple of places.
*/
protected function getSystemRegionList($theme, $show = REGIONS_ALL) {
return system_region_list($theme, $show);
}
/**
* Get disabled regions.
*/
protected function getDisabledRegions() {
$configurations = $this->getConfiguration();
return isset($configurations['regions']) ? $configurations['regions'] : [];
}
}
@@ -0,0 +1,105 @@
<?php
namespace Drupal\context\Plugin\ContextReaction;
use Drupal\context\ContextReactionPluginBase;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Theme\ThemeManagerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a content reaction that will let you change theme.
*
* @ContextReaction(
* id = "theme",
* label = @Translation("Theme")
* )
*/
class Theme extends ContextReactionPluginBase implements ContainerFactoryPluginInterface {
/**
* @var \Drupal\Core\Theme\ThemeManagerInterface
*/
protected $themeManager;
/**
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* {@inheritdoc}
*/
function __construct(
array $configuration,
$pluginId,
$pluginDefinition,
ThemeManagerInterface $themeManager,
ThemeHandlerInterface $themeHandler
) {
parent::__construct($configuration, $pluginId, $pluginDefinition);
$this->themeManager = $themeManager;
$this->themeHandler = $themeHandler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $pluginId, $pluginDefinition) {
return new static(
$configuration,
$pluginId,
$pluginDefinition,
$container->get('theme.manager'),
$container->get('theme_handler')
);
}
/**
* {@inheritdoc}
*/
public function summary() {
return $this->t('Gives you ability to change theme.');
}
/**
* Executes the plugin.
*/
public function execute() {
// TODO: Implement execute() method.
}
/**
* {@inheritdoc}
*/
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$themes = $this->themeHandler->listInfo();
$default_theme = $this->themeHandler->getDefault();
$theme_options = [];
foreach ($themes as $theme_id => $theme) {
$theme_options[$theme_id] = $theme->info['name'];
}
$configuration = $this->getConfiguration();
$form['theme'] = [
'#type' => 'radios',
'#options' => $theme_options,
'#title' => $this->t('Select theme'),
'#default_value' => isset($configuration['theme']) ? $configuration['theme'] : $default_theme,
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
$configuration['theme'] = $form_state->getValue('theme');
$configuration += $this->getConfiguration();
$this->setConfiguration($configuration);
}
}
@@ -0,0 +1,17 @@
<?php
namespace Drupal\context\Plugin;
use Drupal\Core\Plugin\DefaultLazyPluginCollection;
class ContextReactionPluginCollection extends DefaultLazyPluginCollection {
/**
* {@inheritdoc}
*
* @return \Drupal\context\ContextReactionInterface
*/
public function &get($instance_id) {
return parent::get($instance_id);
}
}
@@ -0,0 +1,133 @@
<?php
namespace Drupal\context\Plugin\DisplayVariant;
use Drupal\Component\Utility\NestedArray;
use Drupal\context\ContextManager;
use Drupal\Core\Display\VariantBase;
use Drupal\Core\Display\PageVariantInterface;
use Drupal\Core\Display\VariantManager;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a page display variant that decorates the main content with blocks.
*
* @see \Drupal\Core\Block\MainContentBlockPluginInterface
* @see \Drupal\Core\Block\MessagesBlockPluginInterface
*
* @PageDisplayVariant(
* id = "context_block_page",
* admin_label = @Translation("Page with blocks")
* )
*/
class ContextBlockPageVariant extends VariantBase implements PageVariantInterface, ContainerFactoryPluginInterface {
/**
* @var ContextManager
*/
protected $contextManager;
/**
* The render array representing the main page content.
*
* @var array
*/
protected $mainContent = [];
/**
* The page title: a string (plain title) or a render array (formatted title).
*
* @var string|array
*/
protected $title = '';
/**
* Constructs a new ContextBlockPageVariant.
*
* @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 ContextManager $contextManager
* The context module manager.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, ContextManager $contextManager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->contextManager = $contextManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('context.manager')
);
}
/**
* {@inheritdoc}
*/
public function setMainContent(array $main_content) {
$this->mainContent = $main_content;
return $this;
}
/**
* {@inheritdoc}
*/
public function setTitle($title) {
$this->title = $title;
return $this;
}
/**
* {@inheritdoc}
*/
public function build() {
$build = [
'#cache' => [
'tags' => ['context_block_page', $this->getPluginId()],
],
];
// Place main content block, it will be removed by the reactions if a main
// content block has been manually placed.
$build['content']['system_main'] = $this->mainContent;
// Execute each block reaction and let them modify the page build.
foreach ($this->contextManager->getActiveReactions('blocks') as $reaction) {
$build = $reaction->execute($build, $this->title, $this->mainContent);
}
// Execute each block reaction and check if default block should be included in page build.
foreach ($this->contextManager->getActiveReactions('blocks') as $reaction) {
if ($reaction->includeDefaultBlocks()) {
$build = NestedArray::mergeDeep($this->getBuildFromBlockLayout(), $build);
return $build;
}
}
return $build;
}
/**
* Get build from Block layout.
*/
private function getBuildFromBlockLayout() {
$plugin_manager = \Drupal::service('plugin.manager.display_variant');
$display_variant = $plugin_manager->createInstance('block_page', $plugin_manager->getDefinition('block_page'));
$display_variant->setTitle($this->title);
return $display_variant->build();
}
}
@@ -0,0 +1,48 @@
<?php
/**
* @file
* Contains \Drupal\context\Reaction\Annotation\ContextReaction.
*/
namespace Drupal\context\Reaction\Annotation;
use Drupal\Component\Annotation\Plugin;
/**
* Defines an context reaction annotation object.
*
* Plugin Namespace: Plugin\ContextReaction
*
* @Annotation
*/
class ContextReaction extends Plugin {
/**
* The plugin ID.
*
* @var string
*/
public $id;
/**
* The human-readable name of the context reaction.
*
* @ingroup plugin_translatable
*
* @var \Drupal\Core\Annotation\Translation
*/
public $label;
/**
* A brief description of the context reaction.
*
* This will be shown when adding or configuring this context reaction.
*
* @ingroup plugin_translatable
*
* @var \Drupal\Core\Annotation\Translation (optional)
*/
public $description = '';
}
@@ -0,0 +1,69 @@
<?php
namespace Drupal\context\Reaction\Blocks;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Plugin\DefaultLazyPluginCollection;
class BlockCollection extends DefaultLazyPluginCollection {
/**
* {@inheritdoc}
*
* @return BlockPluginInterface
*/
public function &get($instance_id) {
return parent::get($instance_id);
}
/**
* Returns all blocks keyed by their region. Base code from the ctools block
* plugin collection.
*
* @param string $theme
* The theme to get blocks for.
*
* @return BlockPluginInterface[]
* An associative array keyed by region, containing an associative array of
* block plugins.
*/
public function getAllByRegion($theme) {
$region_assignments = [];
/** @var BlockPluginInterface[] $this */
foreach ($this as $block_id => $block) {
$configuration = $block->getConfiguration();
if ($configuration['theme'] !== $theme) {
continue;
}
$region = isset($configuration['region'])
? $configuration['region']
: NULL;
$region_assignments[$region][$block_id] = $block;
}
foreach ($region_assignments as $region => $region_assignment) {
// @todo Determine the reason this needs error suppression.
@uasort($region_assignment, function (BlockPluginInterface $a, BlockPluginInterface $b) {
$a_config = $a->getConfiguration();
$a_weight = isset($a_config['weight']) ? $a_config['weight'] : 0;
$b_config = $b->getConfiguration();
$b_weight = isset($b_config['weight']) ? $b_config['weight'] : 0;
if ($a_weight == $b_weight) {
return strcmp($a->label(), $b->label());
}
return $a_weight > $b_weight ? 1 : -1;
});
$region_assignments[$region] = $region_assignment;
}
return $region_assignments;
}
}
@@ -0,0 +1,210 @@
<?php
namespace Drupal\context\Reaction\Blocks\Controller;
use Drupal\context\ContextManager;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\FormState;
use Drupal\Core\Url;
use Drupal\context\ContextInterface;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
class ContextReactionBlocksController extends ControllerBase {
/**
* @var \Drupal\Core\Block\BlockManagerInterface
*/
protected $blockManager;
/**
* @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
*/
protected $contextRepository;
/**
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* @var \Drupal\context\ContextManager
*/
protected $contextManager;
/**
* Construct.
*
* @param \Drupal\Core\Block\BlockManagerInterface $blockManager
* @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $contextRepository
* @param \Drupal\Core\Extension\ThemeHandlerInterface $themeHandler
* @param \Drupal\context\ContextManager $contextManager
*/
function __construct(
BlockManagerInterface $blockManager,
ContextRepositoryInterface $contextRepository,
ThemeHandlerInterface $themeHandler,
ContextManager $contextManager
) {
$this->blockManager = $blockManager;
$this->contextRepository = $contextRepository;
$this->themeHandler = $themeHandler;
$this->contextManager = $contextManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.block'),
$container->get('context.repository'),
$container->get('theme_handler'),
$container->get('context.manager')
);
}
/**
* Display a library of blocks that can be added to the context reaction.
*
* @param \Symfony\Component\HttpFoundation\Request $request
* The request object.
*
* @param \Drupal\context\ContextInterface $context
* The context the blocks reaction belongs to.
*
* @param string $reaction_id
* The ID of the blocks reaction that the selected block
* should be added to.
*
* @return array
*/
public function blocksLibrary(Request $request, ContextInterface $context, $reaction_id) {
// If a theme has been defined in the query string then use this for
// the add block link, default back to the default theme.
$theme = $request->query->get('theme', $this->themeHandler->getDefault());
// Only add blocks which work without any available context.
$blocks = $this->blockManager->getDefinitionsForContexts($this->contextRepository->getAvailableContexts());
// Order by category, and then by admin label.
$blocks = $this->blockManager->getSortedDefinitions($blocks);
$build['filter'] = [
'#type' => 'search',
'#title' => $this->t('Filter'),
'#title_display' => 'invisible',
'#size' => 30,
'#placeholder' => $this->t('Filter by block name'),
'#attributes' => [
'class' => ['context-table-filter'],
'data-element' => '.block-add-table',
'title' => $this->t('Enter a part of the block name to filter by.'),
],
];
$headers = [
$this->t('Block'),
$this->t('Category'),
$this->t('Operations'),
];
$build['blocks'] = [
'#type' => 'table',
'#header' => $headers,
'#rows' => [],
'#empty' => $this->t('No blocks available.'),
'#attributes' => [
'class' => ['block-add-table'],
],
];
// Add each block definition to the table.
foreach ($blocks as $block_id => $block) {
$links = [
'add' => [
'title' => $this->t('Place block'),
'url' => Url::fromRoute('context.reaction.blocks.block_add', [
'context' => $context->id(),
'reaction_id' => $reaction_id,
'block_id' => $block_id,
], [
'query' => [
'theme' => $theme,
],
]),
'attributes' => [
'class' => ['use-ajax'],
'data-dialog-type' => 'modal',
'data-dialog-options' => Json::encode([
'width' => 700,
]),
],
],
];
$build['blocks']['#rows'][] = [
'title' => [
'data' => [
'#type' => 'inline_template',
'#template' => '<div class="context-table-filter-text-source">{{ label }}</div>',
'#context' => [
'label' => $block['admin_label'],
],
],
],
'category' => [
'data' => $block['category'],
],
'operations' => [
'data' => [
'#type' => 'operations',
'#links' => $links,
],
],
];
}
$build['#attached']['library'][] = 'context_ui/admin';
return $build;
}
/**
* Callback for the theme select list on the Context blocks reaction form.
*
* @param Request $request
* The current request.
*
* @param ContextInterface $context
* The context the block reaction is located on.
*
* @return \Drupal\Core\Ajax\AjaxResponse
*/
public function blocksFormThemeSelect(Request $request, ContextInterface $context) {
$theme = $request->request->get('reactions[blocks][theme]', '', TRUE);
// Get the context form and supply it with the blocks theme value.
$form = $this->contextManager->getForm($context, 'edit', [
'reactions' => [
'blocks' => [
'theme' => $theme,
],
],
]);
$response = new AjaxResponse();
$response->addCommand(new ReplaceCommand('#context-reactions', $form['reactions']));
return $response;
}
}
@@ -0,0 +1,30 @@
<?php
namespace Drupal\context\Reaction\Blocks\Form;
use Drupal\Core\StringTranslation\TranslatableMarkup;
class BlockAddForm extends BlockFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'context_reaction_blocks_add_block_form';
}
/**
* {@inheritdoc}
*/
protected function getSubmitValue() {
return $this->t('Add block');
}
/**
* {@inheritdoc}
*/
protected function prepareBlock($block_id) {
return $this->blockManager->createInstance($block_id);
}
}
@@ -0,0 +1,151 @@
<?php
namespace Drupal\context\Reaction\Blocks\Form;
use Drupal\context\ContextInterface;
use Drupal\context\ContextManager;
use Drupal\context\Plugin\ContextReaction\Blocks;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Form\ConfirmFormBase;
use Drupal\Core\Form\FormStateInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class BlockDeleteForm extends ConfirmFormBase {
/**
* The context that the block is being removed from.
*
* @var ContextInterface
*/
protected $context;
/**
* The blocks reaction.
*
* @var Blocks
*/
protected $reaction;
/**
* The block that is being removed.
*
* @var BlockPluginInterface
*/
protected $block;
/**
* The Context module context manager.
*
* @var \Drupal\context\ContextManager
*/
protected $contextManager;
/**
* Construct a condition delete form.
*
* @param ContextManager $contextManager
*/
public function __construct(ContextManager $contextManager) {
$this->contextManager = $contextManager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static (
$container->get('context.manager')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'context_reaction_blocks_delete_block_form';
}
/**
* Returns the question to ask the user.
*
* @return string
* The form question. The page title will be set to this value.
*/
public function getQuestion() {
return $this->t('Are you sure you want to remove the %label block?', [
'%label' => $this->block->getConfiguration()['label'],
]);
}
/**
* {@inheritdoc}
*/
public function getCancelUrl() {
return $this->context->urlInfo();
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ContextInterface $context = NULL, $block_id = NULL) {
$this->context = $context;
$this->reaction = $this->context->getReaction('blocks');
$this->block = $this->reaction->getBlock($block_id);
$form = parent::buildForm($form, $form_state);
// Remove the cancel button if this is an AJAX request since Drupals built
// in modal dialogues does not handle buttons that are not a primary
// button very well.
if ($this->getRequest()->isXmlHttpRequest()) {
unset($form['actions']['cancel']);
}
// Submit the form with AJAX if possible.
$form['actions']['submit']['#ajax'] = [
'callback' => '::submitFormAjax'
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$configuration = $this->block->getConfiguration();
$this->reaction->removeBlock($configuration['uuid']);
$this->context->save();
// If this is not an AJAX request then redirect and show a message.
if (!$this->getRequest()->isXmlHttpRequest()) {
drupal_set_message($this->t('The %label block has been removed.', [
'%label' => $configuration['label']]
));
$form_state->setRedirectUrl($this->getCancelUrl());
}
}
/**
* Handle when the form is submitted trough AJAX.
*
* @return AjaxResponse
*/
public function submitFormAjax() {
$contextForm = $this->contextManager->getForm($this->context, 'edit');
$response = new AjaxResponse();
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new ReplaceCommand('#context-reactions', $contextForm['reactions']));
return $response;
}
}
@@ -0,0 +1,28 @@
<?php
namespace Drupal\context\Reaction\Blocks\Form;
class BlockEditForm extends BlockFormBase {
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'context_reaction_blocks_edit_block_form';
}
/**
* {@inheritdoc}
*/
protected function getSubmitValue() {
return $this->t('Update block');
}
/**
* {@inheritdoc}
*/
protected function prepareBlock($block_id) {
return $this->reaction->getBlock($block_id);
}
}
@@ -0,0 +1,343 @@
<?php
namespace Drupal\context\Reaction\Blocks\Form;
use Drupal\context\ContextManager;
use Drupal\context\ContextReactionManager;
use Drupal\context\Form\AjaxFormTrait;
use Drupal\Core\Ajax\AjaxResponse;
use Drupal\Core\Ajax\CloseModalDialogCommand;
use Drupal\Core\Ajax\RemoveCommand;
use Drupal\Core\Ajax\ReplaceCommand;
use Drupal\Core\Extension\ThemeHandlerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormBuilderInterface;
use Drupal\Core\Form\FormState;
use Drupal\context\ContextInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Component\Plugin\PluginManagerInterface;
use Drupal\Core\Plugin\Context\ContextRepositoryInterface;
use Drupal\Core\Plugin\ContextAwarePluginInterface;
use Drupal\Core\Render\Element\StatusMessages;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\Url;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\RequestStack;
abstract class BlockFormBase extends FormBase {
use AjaxFormTrait;
/**
* The plugin being configured.
*
* @var \Drupal\Core\Block\BlockPluginInterface
*/
protected $block;
/**
* The context entity the reaction belongs to.
*
* @var ContextInterface
*/
protected $context;
/**
* The blocks reaction this block should be added to.
*
* @var \Drupal\context\Plugin\ContextReaction\Blocks
*/
protected $reaction;
/**
* The block manager.
*
* @var \Drupal\Component\Plugin\PluginManagerInterface
*/
protected $blockManager;
/**
* @var \Drupal\Core\Plugin\Context\ContextRepositoryInterface
*/
protected $contextRepository;
/**
* @var \Drupal\Core\Extension\ThemeHandlerInterface
*/
protected $themeHandler;
/**
* @var \Drupal\Core\Form\FormBuilderInterface
*/
protected $formBuilder;
/**
* @var \Drupal\context\ContextReactionManager
*/
protected $contextReactionManager;
/**
* @var \Drupal\context\ContextManager
*/
protected $contextManager;
/**
* @var \Symfony\Component\HttpFoundation\Request
*/
protected $request;
/**
* Constructs a new VariantPluginFormBase.
*
* @param \Drupal\Component\Plugin\PluginManagerInterface $block_manager
* The block manager.
*
* @param \Drupal\Core\Plugin\Context\ContextRepositoryInterface $contextRepository
*
* @param \Drupal\Core\Extension\ThemeHandlerInterface $themeHandler
* @param \Drupal\Core\Form\FormBuilderInterface $formBuilder
* @param \Drupal\context\ContextReactionManager $contextReactionManager
* @param \Drupal\context\ContextManager $contextManager
* @param \Symfony\Component\HttpFoundation\RequestStack $requestStack
*/
public function __construct(
PluginManagerInterface $block_manager,
ContextRepositoryInterface $contextRepository,
ThemeHandlerInterface $themeHandler,
FormBuilderInterface $formBuilder,
ContextReactionManager $contextReactionManager,
ContextManager $contextManager,
RequestStack $requestStack
)
{
$this->blockManager = $block_manager;
$this->contextRepository = $contextRepository;
$this->themeHandler = $themeHandler;
$this->formBuilder = $formBuilder;
$this->contextReactionManager = $contextReactionManager;
$this->contextManager = $contextManager;
$this->request = $requestStack->getCurrentRequest();
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.block'),
$container->get('context.repository'),
$container->get('theme_handler'),
$container->get('form_builder'),
$container->get('plugin.manager.context_reaction'),
$container->get('context.manager'),
$container->get('request_stack')
);
}
/**
* Prepares the block plugin based on the block ID.
*
* @param string $block_id
* Either a block ID, or the plugin ID used to create a new block.
*
* @return \Drupal\Core\Block\BlockPluginInterface
* The block plugin.
*/
abstract protected function prepareBlock($block_id);
/**
* Get the value to use for the submit button.
*
* @return TranslatableMarkup
*/
abstract protected function getSubmitValue();
/**
* Form constructor.
*
* @param array $form
* An associative array containing the structure of the form.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @param ContextInterface $context
* The context the reaction belongs to.
*
* @param string|null $reaction_id
* The ID of the blocks reaction the block should be added to.
*
* @param string|null $block_id
* The ID of the block to show a configuration form for.
*
* @return array
*/
public function buildForm(array $form, FormStateInterface $form_state, ContextInterface $context = NULL, $reaction_id = NULL, $block_id = NULL) {
$this->context = $context;
$this->reaction = $this->context->getReaction($reaction_id);
$this->block = $this->prepareBlock($block_id);
// If a theme was defined in the query use this theme for the block
// otherwise use the default theme.
$theme = $this->getRequest()->query->get('theme', $this->themeHandler->getDefault());
// Some blocks require the theme name in the form state like Site Branding
$form_state->set('block_theme', $theme);
// Some blocks require contexts, set a temporary value with gathered
// contextual values.
$form_state->setTemporaryValue('gathered_contexts', $this->contextRepository->getAvailableContexts());
$configuration = $this->block->getConfiguration();
$form['#tree'] = TRUE;
$form['settings'] = $this->block->buildConfigurationForm([], $form_state);
$form['settings']['id'] = [
'#type' => 'value',
'#value' => $this->block->getPluginId(),
];
$form['region'] = [
'#type' => 'select',
'#title' => $this->t('Region'),
'#description' => $this->t('Select the region where this block should be displayed.'),
'#options' => $this->getThemeRegionOptions($theme),
'#default_value' => isset($configuration['region']) ? $configuration['region'] : '',
];
$form['unique'] = [
'#type' => 'checkbox',
'#title' => $this->t('Unique'),
'#description' => $this->t('Check if the block should be uniquely placed, this means that the block can not be overridden by other blocks of the same type in the selected region.'),
'#default_value' => isset($configuration['unique']) ? $configuration['unique'] : FALSE,
];
$form['theme'] = [
'#type' => 'value',
'#value' => $theme,
];
$form['css_class'] = [
'#type' => 'textfield',
'#title' => $this->t('Block Class'),
'#default_value' => isset($configuration['css_class']) ? $configuration['css_class'] : '',
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->getSubmitValue(),
'#button_type' => 'primary',
'#ajax' => [
'callback' => '::submitFormAjax'
],
];
// Remove ajax from submit, if this is not ajax request.
if (!$this->request->isXmlHttpRequest()) {
unset($form['actions']['submit']['#ajax']);
}
// Disable cache on form to prevent ajax forms from failing.
$form_state->disableCache();
return $form;
}
/**
* Form submission handler.
*
* @param array $form
* An associative array containing the structure of the form.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$settings = (new FormState())->setValues($form_state->getValue('settings'));
// Call the plugin submit handler.
$this->block->submitConfigurationForm($form, $settings);
// Update the original form values.
$form_state->setValue('settings', $settings->getValues());
// Add available contexts if this is a context aware block.
if ($this->block instanceof ContextAwarePluginInterface) {
$this->block->setContextMapping($form_state->getValue(['settings', 'context_mapping'], []));
}
$configuration = array_merge($this->block->getConfiguration(), [
'region' => $form_state->getValue('region'),
'theme' => $form_state->getValue('theme'),
'css_class' => $form_state->getValue('css_class'),
'unique' => $form_state->getValue('unique'),
'context_id' => $this->context->id(),
]);
// Add/Update the block.
if (!isset($configuration['uuid'])) {
$this->reaction->addBlock($configuration);
} else {
$this->reaction->updateBlock($configuration['uuid'], $configuration);
}
$this->context->save();
$form_state->setRedirectUrl(Url::fromRoute('entity.context.edit_form', [
'context' => $this->context->id(),
]));
}
/**
* Handle when the form is submitted trough AJAX.
*
* @return AjaxResponse
*/
public function submitFormAjax(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
if ($form_state->getErrors()) {
$messages = StatusMessages::renderMessages(NULL);
$output[] = $messages;
$output[] = $form;
$form_class = '.' . str_replace('_', '-', $form_state->getFormObject()->getFormId()) ;
// Remove any previously added error messages.
$response->addCommand(new RemoveCommand('#drupal-modal .messages--error'));
// Replace old form with new one and with error message.
$response->addCommand(new ReplaceCommand($form_class, $output));
}
else {
$form = $this->contextManager->getForm($this->context, 'edit');
$response->addCommand(new CloseModalDialogCommand());
$response->addCommand(new ReplaceCommand('#context-reactions', $form['reactions']));
}
return $response;
}
/**
* Get a list of regions for the select list.
*
* @param string $theme
* The theme to get a list of regions for.
*
* @param string $show
* What type of regions that should be returned, defaults to all regions.
*
* @return array
*/
protected function getThemeRegionOptions($theme, $show = REGIONS_ALL) {
$regions = system_region_list($theme, $show);
foreach ($regions as $region => $title) {
$regions[$region] = $title;
}
return $regions;
}
}
@@ -0,0 +1,67 @@
<?php
namespace Drupal\context\Reaction;
use Drupal\context\ContextInterface;
use Drupal\context\ContextReactionInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
abstract class ContextReactionFormBase extends FormBase {
/**
* @var ContextInterface
*/
protected $context;
/**
* @var ContextReactionInterface
*/
protected $reaction;
/**
* Form constructor.
*
* @param array $form
* An associative array containing the structure of the form.
*
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*
* @param \Drupal\context\ContextInterface $context
* The context that contains the reaction.
*
* @param $reaction_id
* The id of the reaction that is being configured.
*
* @return array The form structure.
* The form structure.
*/
public function buildForm(array $form, FormStateInterface $form_state, ContextInterface $context = NULL, $reaction_id = NULL) {
$this->context = $context;
$this->reaction = $this->context->getReaction($reaction_id);
$form['reaction'] = [
'#tree' => TRUE,
];
$form['actions'] = [
'#type' => 'actions'
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this->t('Save'),
'#button_type' => 'primary',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
$this->context->save();
}
}
@@ -0,0 +1,55 @@
<?php
/**
* @file
* Contains \Drupal\context\Theme\ThemeSwitcherNegotiator.
*/
namespace Drupal\context\Theme;
use Drupal\context\Plugin\ContextReaction\Theme;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Theme\ThemeNegotiatorInterface;
class ThemeSwitcherNegotiator implements ThemeNegotiatorInterface {
/**
* @var string
*/
protected $theme;
/**
* {@inheritdoc}
*/
public function applies(RouteMatchInterface $route_match) {
$context_manager = \Drupal::service('context.manager');
// If there is no Theme reaction set, do not try to get active reactions,
// since this causes infinite loop.
$theme_reaction = FALSE;
foreach ($context_manager->getContexts() as $context) {
foreach ($context->getReactions() as $reaction) {
if ($reaction instanceof Theme) {
$theme_reaction = TRUE;
break;
}
}
}
if ($theme_reaction) {
foreach($context_manager->getActiveReactions('theme') as $theme_reaction) {
$configuration = $theme_reaction->getConfiguration();
$this->theme = $configuration['theme'];
return TRUE;
}
}
return FALSE;
}
/**
* {@inheritdoc}
*/
public function determineActiveTheme(RouteMatchInterface $route_match) {
return $this->theme;
}
}
@@ -115,9 +115,12 @@
// console.log("Mouse pos: ", {x:_m_pos.x, y:_m_pos.y});
})
.on('click', function(event) {
event.preventDefault();
if(_node_hover_id != -1){
console.log("click on node", _nodes[_node_hover_id]);
if(event.target.tagName != "A"){
console.log("Corpus : click", event);
event.preventDefault();
if(_node_hover_id != -1){
console.log("click on node", _nodes[_node_hover_id]);
}
}
});
};
@@ -115,9 +115,12 @@
// console.log("Mouse pos: ", {x:_m_pos.x, y:_m_pos.y});
})
.on('click', function(event) {
event.preventDefault();
if(_node_hover_id != -1){
console.log("click on node", _nodes[_node_hover_id]);
if(event.target.tagName != "A"){
console.log("Corpus : click", event);
event.preventDefault();
if(_node_hover_id != -1){
console.log("click on node", _nodes[_node_hover_id]);
}
}
});
};
@@ -0,0 +1,48 @@
<?php
/**
* @file
*/
namespace Drupal\edlp_corpus\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Link;
use Drupal\Core\Url;
/**
* Creates a 'Entrees' Block
* @Block(
* id = "block_edlp_entrees",
* admin_label = @Translation("Edlp entrees block"),
* )
*/
class BlockEntrees extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
$query = \Drupal::entityQuery('taxonomy_term')
->condition('vid', 'entrees');
$tids = $query->execute();
$terms = entity_load_multiple('taxonomy_term', $tids);
// dsm($terms);
foreach ($terms as $term) {
$tid = $term->id();
$name = $term->getName();
$url = Url::fromRoute('entity.taxonomy_term.canonical', ['taxonomy_term' => $tid]);
$link = Link::fromTextAndUrl($name, $url);
$link = $link->toRenderable();
$link["#attributes"]["class"] = 'term-'.$term->id();
$entrees[] = $link;
}
return array (
'#theme' => 'item_list',
'#items' => $entrees,
);
}
}
@@ -28,7 +28,138 @@ header[role="banner"] {
outline: 1px solid blue; }
main[role="main"] {
outline: 1px solid green; }
outline: 1px solid green;
background-color: rgba(255, 255, 255, 0.9); }
footer[role="contentinfo"] {
outline: 1px solid pink; }
outline: 1px solid pink;
position: fixed;
bottom: 0;
width: 100%; }
canvas#edlp-map {
outline: 1px solid grey; }
footer {
text-align: center; }
footer > .region {
outline: 1px dotted pink; }
footer .region-footer-left {
float: left;
text-align: left; }
footer .region-footer-center {
display: inline-block;
margin: 0 auto;
text-align: center; }
footer .region-footer-right {
float: right;
text-align: right;
padding-right: 5em; }
footer nav.block-menu {
display: inline-block; }
footer nav.block-menu ul {
margin: 0;
padding: 0; }
footer nav.block-menu ul li {
display: inline-block;
position: relative;
list-style: none;
margin: 0 1.5em 0 0;
padding: 0; }
footer nav.block-menu ul li a {
position: absolute;
-webkit-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: rotateZ(-45deg);
transform: rotateZ(-45deg);
color: #000;
text-decoration: none;
text-transform: uppercase;
font-size: 0.756em;
white-space: nowrap; }
footer .block-language {
display: inline-block; }
footer .block-language ul {
position: absolute;
margin: 0;
padding: 0 0 0 0.5em;
-webkit-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: rotateZ(-45deg);
transform: rotateZ(-45deg); }
footer .block-language ul li {
margin: 0;
padding: 0;
list-style: none;
display: inline-block; }
footer .block-language ul li:last-of-type:before {
content: "/";
margin: 0 0.2em; }
footer .block-language ul li a {
color: inherit;
text-decoration: none;
font-size: 0.756em; }
footer .block-block-edlp-entrees {
display: inline-block; }
footer .block-block-edlp-entrees ul li {
display: inline-block;
position: relative;
list-style: none;
margin: 0 1.5em 0 0;
padding: 0; }
footer .block-block-edlp-entrees ul li a {
position: absolute;
-webkit-transform-origin: left bottom;
transform-origin: left bottom;
-webkit-transform: rotateZ(-45deg);
transform: rotateZ(-45deg);
color: #000;
text-decoration: none;
text-transform: uppercase;
font-size: 0.756em;
white-space: nowrap; }
footer .block-block-edlp-entrees ul li a:before {
content: "";
display: inline-block;
width: 7px;
height: 7px;
border: 1px solid #000;
margin-right: 0.5em; }
footer .block-block-edlp-entrees ul li a.term-134:before {
border-color: #2b8f2f; }
footer .block-block-edlp-entrees ul li a.term-121:before {
border-color: #3a33b6; }
footer .block-block-edlp-entrees ul li a.term-125:before {
border-color: #2c9f57; }
footer .block-block-edlp-entrees ul li a.term-119:before {
border-color: #c48978; }
footer .block-block-edlp-entrees ul li a.term-132:before {
border-color: #5270bb; }
footer .block-block-edlp-entrees ul li a.term-122:before {
border-color: #fb54d3; }
footer .block-block-edlp-entrees ul li a.term-129:before {
border-color: #e07483; }
footer .block-block-edlp-entrees ul li a.term-120:before {
border-color: #655845; }
footer .block-block-edlp-entrees ul li a.term-130:before {
border-color: #7e0868; }
footer .block-block-edlp-entrees ul li a.term-118:before {
border-color: #0e7121; }
footer .block-block-edlp-entrees ul li a.term-127:before {
border-color: #dabd42; }
footer .block-block-edlp-entrees ul li a.term-133:before {
border-color: #0399bb; }
footer .block-block-edlp-entrees ul li a.term-128:before {
border-color: #399a1c; }
footer .block-block-edlp-entrees ul li a.term-124:before {
border-color: #708540; }
footer .block-block-edlp-entrees ul li a.term-116:before {
border-color: #191bff; }
footer .block-block-edlp-entrees ul li a.term-117:before {
border-color: #279d84; }
footer .block-block-edlp-entrees ul li a.term-131:before {
border-color: #5219ab; }
footer .block-block-edlp-entrees ul li a.term-126:before {
border-color: #d49cb6; }
footer .block-block-edlp-entrees ul li a.term-123:before {
border-color: #497715; }
@@ -40,8 +40,133 @@ header[role="banner"]{
main[role="main"]{
outline:1px solid green;
background-color: rgba(255,255,255, 0.9);
}
footer[role="contentinfo"]{
outline: 1px solid pink;
position: fixed;
bottom:0;
width:100%;
}
canvas#edlp-map{
outline: 1px solid grey;
}
@mixin oblique-list {
display: inline-block;
position: relative;
list-style: none;
margin: 0 1.5em 0 0;
// width:2em; height:10em;
padding: 0;
a{
position: absolute;
transform-origin: left bottom;
transform: rotateZ(-45deg);
color: #000;
text-decoration: none;
text-transform: uppercase;
font-size: 0.756em;
white-space: nowrap;
}
}
footer{
text-align: center;
>.region{
outline: 1px dotted pink;
}
.region-footer-left{
float: left;
text-align: left;
}
.region-footer-center{
display: inline-block;
margin: 0 auto;
text-align: center;
}
.region-footer-right{
float: right;
text-align: right;
padding-right: 5em;
}
nav.block-menu{
display: inline-block;
ul{
margin:0;
padding:0;
li{
@include oblique-list;
}
}
}
.block-language{
display: inline-block;
ul{
position: absolute;
margin:0;
padding:0 0 0 0.5em;
transform-origin: left bottom;
transform: rotateZ(-45deg);
li{
margin:0; padding:0;
list-style: none;
display: inline-block;
&:last-of-type{
&:before{
content:"/";
margin:0 0.2em;
}
}
a{
color: inherit;
text-decoration: none;
font-size: 0.756em;
}
}
}
}
.block-block-edlp-entrees{
display: inline-block;
ul{
li{
@include oblique-list;
a{
&:before{
content: "";
display:inline-block;
$sq:7px;
width: $sq; height:$sq;
border: 1px solid #000;
margin-right: 0.5em;
}
&.term-134:before{border-color: $entree-color-134;}
&.term-121:before{border-color: $entree-color-121;}
&.term-125:before{border-color: $entree-color-125;}
&.term-119:before{border-color: $entree-color-119;}
&.term-132:before{border-color: $entree-color-132;}
&.term-122:before{border-color: $entree-color-122;}
&.term-129:before{border-color: $entree-color-129;}
&.term-120:before{border-color: $entree-color-120;}
&.term-130:before{border-color: $entree-color-130;}
&.term-118:before{border-color: $entree-color-118;}
&.term-127:before{border-color: $entree-color-127;}
&.term-133:before{border-color: $entree-color-133;}
&.term-128:before{border-color: $entree-color-128;}
&.term-124:before{border-color: $entree-color-124;}
&.term-116:before{border-color: $entree-color-116;}
&.term-117:before{border-color: $entree-color-117;}
&.term-131:before{border-color: $entree-color-131;}
&.term-126:before{border-color: $entree-color-126;}
&.term-123:before{border-color: $entree-color-123;}
}
}
}
}
}
@@ -1,21 +1,21 @@
$130:rgb(75, 143, 126);
$121:rgb(134, 142, 36);
$134:rgb(43, 143, 47);
$121:rgb(58, 51, 182);
$125:rgb(44, 159, 87);
$119:rgb(196, 137, 120);
$132:rgb(82, 112, 187);
$122:rgb(251, 84, 211);
$129:rgb(224, 116, 131);
$120:rgb(101, 88, 69);
$130:rgb(126, 8, 104);
$118:rgb(14, 113, 33);
$127:rgb(218, 189, 66);
$133:rgb(3, 153, 187);
$128:rgb(57, 154, 28);
$124:rgb(112, 133, 64);
$116:rgb(25, 27, 255);
$117:rgb(39, 157, 132);
$131:rgb(82, 25, 171);
$126:rgb(212, 156, 182);
$123:rgb(73, 119, 21);
$entree-color-130: rgb(75, 143, 126);
$entree-color-121: rgb(134, 142, 36);
$entree-color-134: rgb(43, 143, 47);
$entree-color-121: rgb(58, 51, 182);
$entree-color-125: rgb(44, 159, 87);
$entree-color-119: rgb(196, 137, 120);
$entree-color-132: rgb(82, 112, 187);
$entree-color-122: rgb(251, 84, 211);
$entree-color-129: rgb(224, 116, 131);
$entree-color-120: rgb(101, 88, 69);
$entree-color-130: rgb(126, 8, 104);
$entree-color-118: rgb(14, 113, 33);
$entree-color-127: rgb(218, 189, 66);
$entree-color-133: rgb(3, 153, 187);
$entree-color-128: rgb(57, 154, 28);
$entree-color-124: rgb(112, 133, 64);
$entree-color-116: rgb(25, 27, 255);
$entree-color-117: rgb(39, 157, 132);
$entree-color-131: rgb(82, 25, 171);
$entree-color-126: rgb(212, 156, 182);
$entree-color-123: rgb(73, 119, 21);
@@ -0,0 +1,18 @@
bartik.mobile:
label: mobile
mediaQuery: ''
weight: 0
multipliers:
- 1x
bartik.narrow:
label: narrow
mediaQuery: 'all and (min-width: 560px) and (max-width: 850px)'
weight: 1
multipliers:
- 1x
bartik.wide:
label: wide
mediaQuery: 'all and (min-width: 851px)'
weight: 2
multipliers:
- 1x
@@ -15,17 +15,9 @@ libraries:
# - core/modules/system/css/system.theme.css
# - core/modules/views/css/views.module.css
# regions:
# content: Content
# content_top: 'Content Top'
# content_bottom: 'Content Bottom'
# nav: Navigation
# front_one: 'Front One'
# front_two: 'Front Two'
# front_three: 'Front Three'
# front_four: 'Front Four'
# front_five: 'Front Five'
# front_six: 'Front Six'
# front_seven: 'Front Seven'
# front_eight: 'Front Eight'
# footer: Footer
regions:
header: Header
content: Content
footer_left: 'Footer Left'
footer_center: 'Footer Center'
footer_right: 'Footer Right'
@@ -48,15 +48,6 @@
{{ page.header }}
</header>
{{ page.primary_menu }}
{{ page.secondary_menu }}
{{ page.breadcrumb }}
{{ page.highlighted }}
{{ page.help }}
<main role="main">
<a id="main-content" tabindex="-1"></a>{# link is in html.html.twig #}
@@ -64,23 +55,14 @@
{{ page.content }}
</div>{# /.layout-content #}
{% if page.sidebar_first %}
<aside class="layout-sidebar-first" role="complementary">
{{ page.sidebar_first }}
</aside>
{% endif %}
{% if page.sidebar_second %}
<aside class="layout-sidebar-second" role="complementary">
{{ page.sidebar_second }}
</aside>
{% endif %}
</main>
{% if page.footer %}
{% if page.footer_left or page.footer_center or page.footer_right %}
<footer role="contentinfo">
{{ page.footer }}
{{ page.footer_left }}
{{ page.footer_center }}
{{ page.footer_right }}
</footer>
{% endif %}
@@ -0,0 +1,57 @@
{#
/**
* @file
* Default theme implementation for a set of links.
*
* Available variables:
* - attributes: Attributes for the UL containing the list of links.
* - links: Links to be output.
* Each link will have the following elements:
* - title: The link text.
* - url: The link URL. If omitted, the 'title' is shown as a plain text
* item in the links list. If 'url' is supplied, the entire link is passed
* to l() as its $options parameter.
* - attributes: (optional) HTML attributes for the anchor, or for the <span>
* tag if no 'url' is supplied.
* - heading: (optional) A heading to precede the links.
* - text: The heading text.
* - level: The heading level (e.g. 'h2', 'h3').
* - attributes: (optional) A keyed list of attributes for the heading.
* If the heading is a string, it will be used as the text of the heading and
* the level will default to 'h2'.
*
* Headings should be used on navigation menus and any list of links that
* consistently appears on multiple pages. To make the heading invisible use
* the 'visually-hidden' CSS class. Do not use 'display:none', which
* removes it from screen readers and assistive technology. Headings allow
* screen reader and keyboard only users to navigate to or skip the links.
* See http://juicystudio.com/article/screen-readers-display-none.php and
* http://www.w3.org/TR/WCAG-TECHS/H42.html for more information.
*
* @see template_preprocess_links()
*
* @ingroup themeable
*/
#}
{% if links -%}
{%- if heading -%}
{%- if heading.level -%}
<{{ heading.level }}{{ heading.attributes }}>{{ heading.text }}</{{ heading.level }}>
{%- else -%}
<h2{{ heading.attributes }}>{{ heading.text }}</h2>
{%- endif -%}
{%- endif -%}
<ul{{ attributes }}>
{%- for item in links -%}
<li{{ item.attributes }}>
{%- if item.link -%}
<a href="{{ item.link.url }}">{{ item.text|slice(0,2) }}</a>
{%- elseif item.text_attributes -%}
<span{{ item.text_attributes }}>{{ item.text }}</span>
{%- else -%}
{{ item.text }}
{%- endif -%}
</li>
{%- endfor -%}
</ul>
{%- endif %}