updated contrib modules : migrate_tools, migrate_plus, piwik -> matomo, color_field, config_filter, admin_toolbar

This commit is contained in:
2018-09-12 14:41:53 +02:00
parent b01aa458f8
commit 4caa864a8f
176 changed files with 8874 additions and 1500 deletions
@@ -0,0 +1 @@
.idea/
@@ -0,0 +1,123 @@
# Color Field - Drupal 8
## ABOUT & FEATURES
### Formatters
Plain text HEX code (#FFFFFF)
Css Declaration (color/background-color)
### Widgets
- *Color Boxes*: Provides a row of colored boxes to select from a configured
list of colors. If enabled, opacity is a number field.
- *Color Default*: Textbox to put in a hex value. If enabled, opacity is a
number field.
- *Color Grid*: Uses [jQuery Simple Color](https://github.com/recurser/jquery-simple-color)
to provide a pop up grid of color options. If enabled, opacity is a number
field.
- *Color HTML5*: Uses the color HTML5 input type to render in a browser/system
native manner. If enabled, opacity is a number field.
- *Color Spectrum*: Uses [Spectrum](https://github.com/bgrins/spectrum) to
provide a user friendly color palette to choose the correct color. This has an
integrated slider for opacity (if opacity is enabled).
## ROAD MAP
1) Make this module a base that could be used by any color picker.
2) include http://www.eyecon.ro/colorpicker/
3) include http://www.dematte.at/colorPicker/
4) include http://acko.net/blog/farbtastic-jquery-color-picker-plug-in/
## INSTALLATION
Install as you would normally install a contributed Drupal module. See also
[Core Documentation](https://www.drupal.org/docs/8/extending-drupal-8/installing-modules)
### DEPENDENCIES
There are JavaScript libraries required for a couple of the field widgets. If
you are not actively using those field widgets, you can skip their installation
if desired.
#### COMPOSER
If you installed color field via [Composer](https://getcomposer.org), the
packages will have been suggested but not automatically installed. If you have
Asset Packagist already configured - as most Commerce users will - skip to just
requiring the desired package(s).
```bash
composer require bower-asset/jquery-simple-color bower-asset/spectrum
```
Otherwise, to install them you will need to add
[Asset Packagist](https://asset-packagist.org) to your composer.json and
do some and make a couple other changes to your `composer.json`. Specifically,
in the `extra` key add/adjust current values:
```json
"installer-types": [
"npm-asset",
"bower-asset"
],
"installer-paths": {
"web/core": [
"type:drupal-core"
],
"web/libraries/{$name}": [
"type:bower-asset",
"type:npm-asset",
"type:drupal-library"
],
"web/modules/contrib/{$name}": [
"type:drupal-module"
],
"web/profiles/contrib/{$name}": [
"type:drupal-profile"
],
"web/themes/contrib/{$name}": [
"type:drupal-theme"
],
"drush/contrib/{$name}": [
"type:drupal-drush"
]
},
```
then run
```bash
composer require oomphinc/composer-installers-extender
composer require bower-asset/jquery-simple-color bower-asset/spectrum
```
#### MANUAL
If you are not using Composer, you will need to manually install them.
- [jQuery Simple Color](https://github.com/recurser/jquery-simple-color)
copy to `/libraries/jquery-simple-color` so that `jquery.simple-color.min.js`
is in that folder. Required for the Color Grid widget.
- [Spectrum](https://github.com/bgrins/spectrum) copy to `/libraries/spectrum`
so that `spectrum.js` exists in that folder. Required for the Spectrum widget.
## USAGE
Field
1. Add the field to an node/entity
2. Select the 'Color Field' field type
3. Select the 'Color' widget you want
## CREDIT
Original Creator: [targoo](https://www.drupal.org/u/targoo).
Maintainers:
- [targoo](https://www.drupal.org/u/targoo)
- [Nick Wilde](https://www.drupal.org/u/nickwilde)
Original development sponsored by Marique Calcus and written by Calcus David.
For professional support and development services contact targoo@gmail.com.
## More info
http://www.w3.org/TR/css3-color/#color
https://github.com/mikeemoo/ColorJizz-PHP
http://www.colorhexa.com/ff0000
https://github.com/PrimalPHP/Color/blob/master/lib/Primal/Color/Parser.php
https://github.com/matthewbaggett/php-color/blob/master/Color.php
@@ -1,66 +0,0 @@
-----------------------------------------------------------------------------
CURRENT FEATURES
-----------------------------------------------------------------------------
Formatter
Plain text HEX code (#FFFFFF)
Css Declaration (color/background-color)
Widget
Plain Text
Pre-selected Color Boxes
Simple Query Color
(http://recursive-design.com/projects/jquery-simple-color/)
-----------------------------------------------------------------------------
ROAD MAP
-----------------------------------------------------------------------------
1) Make this module a base that could be used by any color picker.
2) include http://www.eyecon.ro/colorpicker/
3) include http://www.dematte.at/colorPicker/
4) include http://acko.net/blog/farbtastic-jquery-color-picker-plug-in/
-----------------------------------------------------------------------------
REQUIREMENTS
-----------------------------------------------------------------------------
No specific requirement
-----------------------------------------------------------------------------
INSTALLATION
-----------------------------------------------------------------------------
To use this module, simply enable it.
-----------------------------------------------------------------------------
INSTALLATION - jQuery simple color
-----------------------------------------------------------------------------
If you want to use the jquery simple color plugin you need to download it and
place it in your libraries folder (this will usually be "sites/all/libraries/").
You can download the plugin by using the following links or by Drush.
http://recursive-design.com/projects/jquery-simple-color/
https://github.com/recurser/jquery-simple-color
-----------------------------------------------------------------------------
USAGE
-----------------------------------------------------------------------------
Field
1. Add the field to an node/entity
2. Select the 'Color Field' field type
3. Select the 'Color' widget you want
-----------------------------------------------------------------------------
CREDIT
-----------------------------------------------------------------------------
Maintainer and developer: targoo
Development sponsored by Marique Calcus and written by Calcus David.
For professional support and development services contact targoo@gmail.com.
-----------------------------------------------------------------------------
More info
-----------------------------------------------------------------------------
http://www.w3.org/TR/css3-color/#color
https://github.com/mikeemoo/ColorJizz-PHP
http://www.colorhexa.com/ff0000
https://github.com/PrimalPHP/Color/blob/master/lib/Primal/Color/Parser.php
https://github.com/matthewbaggett/php-color/blob/master/Color.php
@@ -1,26 +0,0 @@
From ef19dd13dceeb972e9b0fe1920d846901a076dd4 Mon Sep 17 00:00:00 2001
From: kristiaanvandeneynde <kristiaanvandeneynde@1345130.no-reply.drupal.org>
Date: Thu, 26 Oct 2017 14:24:28 +0200
Subject: [PATCH] Issue #2854199 by pclaitte, kristiaanvandeneynde: Color Boxes
Widget default values doesn't works
---
src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php b/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php
index 8268704..ad05958 100644
--- a/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php
+++ b/src/Plugin/Field/FieldWidget/ColorFieldWidgetBox.php
@@ -96,7 +96,7 @@ class ColorFieldWidgetBox extends WidgetBase {
$default_colors = $this->getSetting('default_colors');
preg_match_all("/#[0-9a-fA-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER);
foreach ($default_colors as $color) {
- $settings['palette'][] = $color[0];
+ $settings['default_colors'][] = $color[0];
}
$element['#attached']['drupalSettings']['color_field']['color_field_widget_box']['settings'] = $settings;
--
2.4.9 (Apple Git-60)
@@ -4,10 +4,12 @@ description: 'Provides a color field type to store the color value and opacity'
# core: 8.x
package: Field types
dependencies:
- field
- drupal:field
test_dependencies:
- token:token
# Information added by Drupal.org packaging script on 2017-04-13
version: '8.x-2.0-rc1+11-dev'
# Information added by Drupal.org packaging script on 2018-09-05
version: '8.x-2.0'
core: '8.x'
project: 'color_field'
datestamp: 1492097733
datestamp: 1536168814
@@ -0,0 +1,53 @@
<?php
/**
* @file
* Install, update and uninstall functions for the Color Fields module.
*/
/**
* If the JavaScript Libraries don't exist, show a warning on the status page.
*/
function color_field_requirements($phase) {
$requirements = [];
if ($phase === 'runtime') {
if (!file_exists(DRUPAL_ROOT . '/libraries/jquery-simple-color/jquery.simple-color.js')) {
$requirements['color_field_simple'] = [
'title' => t('Color Field library: jQuery Simple Color'),
'value' => t('Missing'),
'description' => t('Download the <a href=":url">jQuery Simple Color library</a> and copy it to :library', [
':url' => 'https://github.com/recurser/jquery-simple-color',
':library' => DRUPAL_ROOT . '/libraries/jquery-simple-color/',
]),
'severity' => REQUIREMENT_WARNING,
];
}
else {
$requirements['color_field_simple'] = [
'title' => t('Color Field library: jQuery Simple Color'),
'value' => t('Installed'),
'severity' => REQUIREMENT_OK,
];
}
if (!file_exists(DRUPAL_ROOT . '/libraries/spectrum/spectrum.js')) {
$requirements['color_field_spectrum'] = [
'title' => t('Color Field library: Spectrum'),
'value' => t('Missing'),
'description' => t('Download the <a href=":url">Spectrum library</a> and copy it to :library', [
':url' => 'https://github.com/bgrins/spectrum',
':library' => DRUPAL_ROOT . '/libraries/spectrum/',
]),
'severity' => REQUIREMENT_WARNING,
];
}
else {
$requirements['color_field_spectrum'] = [
'title' => t('Color Field library: Spectrum'),
'value' => t('Installed'),
'severity' => REQUIREMENT_OK,
];
}
}
return $requirements;
}
@@ -1,4 +1,5 @@
<?php
/**
* @file
* A color field with a custom color picker using the Field Types API.
@@ -15,11 +16,15 @@ function color_field_help($route_name, RouteMatchInterface $route_match) {
case 'help.page.color_field':
$output = '';
$output .= '<h3>' . t('About') . '</h3>';
$output .= '<p>' . t('Color Field is simple field that use a hexadecimal notation (HEX) for the combination of Red, Green, and Blue color values (RGB). See the <a href="!field">Field module help</a> and the <a href="!field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href="!link_documentation">online documentation for the Link module</a>.', array('!field' => Url::fromRoute('help.page', array('name' => 'field')), '!field_ui' => Url::fromRoute('help.page', array('name' => 'field_ui')), '!link_documentation' => 'https://drupal.org/documentation/modules/link')) . '</p>';
$output .= '<p>' . t('Color Field is simple field that use a hexadecimal notation (HEX) for the combination of Red, Green, and Blue color values (RGB). See the <a href="!field">Field module help</a> and the <a href="!field_ui">Field UI help</a> pages for general information on fields and how to create and manage them. For more information, see the <a href="!link_documentation">online documentation for the Link module</a>.', [
'!field' => Url::fromRoute('help.page', ['name' => 'field']),
'!field_ui' => Url::fromRoute('help.page', ['name' => 'field_ui']),
'!link_documentation' => 'https://drupal.org/documentation/modules/link',
]) . '</p>';
$output .= '<h3>' . t('Uses') . '</h3>';
$output .= '<dl>';
$output .= '<dt>' . t('Managing and displaying color fields') . '</dt>';
$output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the link field can be configured separately. See the <a href="!field_ui">Field UI help</a> for more information on how to manage fields and their display.', array('!field_ui' => Url::fromRoute('help.page', array('name' => 'field_ui')))) . '</dd>';
$output .= '<dd>' . t('The <em>settings</em> and the <em>display</em> of the link field can be configured separately. See the <a href="!field_ui">Field UI help</a> for more information on how to manage fields and their display.', ['!field_ui' => Url::fromRoute('help.page', ['name' => 'field_ui'])]) . '</dd>';
$output .= '<dt>' . t('Adding link text') . '</dt>';
$output .= '<dd>' . t('In the field settings you can define additional link text to be <em>optional</em> or <em>required</em> in any link field.') . '</dd>';
$output .= '<dt>' . t('Displaying link text') . '</dt>';
@@ -39,22 +44,14 @@ function color_field_help($route_name, RouteMatchInterface $route_match) {
function color_field_theme() {
$theme = [];
$theme['color_field_formatter_swatch'] = array(
'variables' => array(
'shape' => NULL,
'color' => NULL,
'width' => NULL,
'height' => NULL,
),
);
$theme['color_field_widget_box'] = array(
'render element' => 'element',
);
$theme['color_field_widget_spectrum'] = array(
'render element' => 'element',
);
$theme['color_field_formatter_swatch'] = [
'variables' => [
'shape' => NULL,
'color' => NULL,
'width' => NULL,
'height' => NULL,
],
];
return $theme;
}
@@ -73,88 +70,5 @@ function color_field_theme() {
* - width: The width of the color swatch.
* - height: The height of the color swatch.
*/
function template_preprocess_color_field_formatter_swatch(&$variables) {
}
/**
* Prepares variables for color_field widget box wrapper template.
*
* Default template: color-field-widget-box.html.twig.
*
* @param array $variables
* An associative array containing:
* - element: An associative array containing the properties of the element.
* Properties used: #title, #children, #required, #attributes.
*/
function template_preprocess_color_field_widget_box(&$variables) {
$element = $variables['element'];
if (!empty($element['#title'])) {
$variables['title'] = $element['#title'];
}
if (!empty($element['#description'])) {
$variables['description'] = $element['#description'];
}
$variables['color'] = $element['color'];
if (!empty($element['opacity'])) {
$variables['opacity'] = $element['opacity'];
}
// Suppress error messages.
$variables['errors'] = NULL;
if (!empty($element['#description'])) {
$variables['description'] = $element['#description'];
}
$variables['required'] = FALSE;
if (!empty($element['#required'])) {
$variables['required'] = TRUE;
}
}
/**
* Prepares variables for color_field widget box wrapper template.
*
* Default template: color-field-widget-box.html.twig.
*
* @param array $variables
* An associative array containing:
* - element: An associative array containing the properties of the element.
* Properties used: #title, #children, #required, #attributes.
*/
function template_preprocess_color_field_widget_spectrum(&$variables) {
$element = $variables['element'];
if (!empty($element['#title'])) {
$variables['title'] = $element['#title'];
}
if (!empty($element['#description'])) {
$variables['description'] = $element['#description'];
}
$variables['color'] = $element['color'];
if (!empty($element['opacity'])) {
$variables['opacity'] = $element['opacity'];
}
// Suppress error messages.
$variables['errors'] = NULL;
if (!empty($element['#description'])) {
$variables['description'] = $element['#description'];
}
$variables['required'] = FALSE;
if (!empty($element['#required'])) {
$variables['required'] = TRUE;
}
function template_preprocess_color_field_formatter_swatch(array &$variables) {
}
@@ -0,0 +1,37 @@
<?php
/**
* @file
* Contains post update functionality for the color field module.
*/
use Drupal\Core\Entity\Entity\EntityFormDisplay;
/**
* Update spectrum widget configuration to allow multiple palettes.
*/
function color_field_post_update_spectrum_palette() {
/** @var \Drupal\Core\Entity\Entity\EntityFormDisplay $entity_form_display */
foreach (EntityFormDisplay::loadMultiple() as $entity_form_display) {
$changed = FALSE;
foreach ($entity_form_display->getComponents() as $name => $options) {
if (isset($options['type']) && $options['type'] === 'color_field_widget_spectrum') {
if ($options['settings']['palette']) {
$palette = explode(',', $options['settings']['palette']);
foreach ($palette as &$color) {
$color = '"' . trim($color) . '"';
}
$options['settings']['palette'] = '[' . implode(',', $palette) . ']';
$entity_form_display->setComponent($name, $options);
$changed = TRUE;
}
}
}
if ($changed) {
$entity_form_display->save();
}
}
return t('The new palette format for spectrum color field widgets has been applied.');
}
@@ -0,0 +1,36 @@
{
"name": "drupal/color_field",
"require": {
"drupal/core": "*"
},
"require-dev": {
"drupal/token": "~1.3"
},
"suggest": {
"bower-asset/jquery-simple-color": "^v1.2.2: Provides JavaScript library necessary for the Color Grid widget",
"bower-asset/spectrum": "^1.8: Provides JavaScript library necessary for Spectrum widget."
},
"type": "drupal-module",
"notification-url": "https://packages.drupal.org/8/downloads",
"license": [
"GPL-2.0-or-later"
],
"authors": [
{
"name": "targoo",
"homepage": "https://www.drupal.org/user/431910",
"role": "Maintainer"
},
{
"name": "Nick Wilde",
"homepage": "https://www.drupal.org/user/nickwilde",
"role": "Maintainer"
}
],
"description": "Provides a color field type to store the color value and opacity",
"homepage": "https://www.drupal.org/project/color_field",
"support": {
"issues": "https://www.drupal.org/project/issues/color_field?version=8.x",
"source": "http://cgit.drupalcode.org/color_field"
}
}
@@ -1,5 +1,29 @@
# Schema for the configuration files of the color field module.
field.storage_settings.color_field_type:
type: mapping
mapping:
format:
type: label
label: 'Format'
field.field_settings.color_field_type:
type: mapping
mapping:
opacity:
type: integer
label: 'Display opacity'
field.value.color_field_type:
type: mapping
mapping:
color:
type: string
label: 'The hex color code'
opacity:
type: float
label: 'The opacity'
field.formatter.settings.color_field_formatter_text:
type: mapping
label: 'Color text format settings'
@@ -1,7 +1,7 @@
.color_field {}
.color_field__swatch {}
.color_field__swatch--square {
.color_field__swatch {
display: inline-block;
}
.color_field__swatch--circle {
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
@@ -12,4 +12,5 @@
-webkit-transform: skew(20deg);
-moz-transform: skew(20deg);
-o-transform: skew(20deg);
transform: skew(20deg);
}
@@ -1,32 +1,30 @@
.color_field_widget_box {
}
.color_field_widget_box__square {
border: 1px solid #ffffff;
cursor: pointer;
font-family: monospace;
font-size: 1.2em;
margin: 0 3px;
padding: 1px 8px;
border: 1px solid #000;
box-shadow: 0 0 1px #000;
height: 16px;
margin: 2px;
width: 16px;
}
.color_field_widget_box__square.active,
.color_field_widget_box__square:hover {
padding: 9px 16px;
height: 32px;
width: 32px;
}
.color_field_widget_box__square--transparent {
background-image: url("../images/transparent_box16.gif");
background-position: 0 3px;
background-repeat: no-repeat;
margin: 0 3px;
padding: 2px 8px;
border: 1px solid #000;
box-shadow: 0 0 1px #000;
height: 16px;
margin: 2px;
width: 16px;
}
.color_field_widget_box__square--transparent.active,
.color_field_widget_box__square--transparent:hover {
background-image: url(../images/transparent_box32.gif);
background-position: 0 3px;
background-repeat: no-repeat;
padding: 10px 16px;
height: 32px;
width: 32px;
}
@@ -1,12 +1,4 @@
.simpleColorDisplay {
float: left;
}
.simpleColorContainer {
float: left;
}
.simpleColorChooser {
z-index: 1;
max-width: 100%;
}
@@ -0,0 +1,50 @@
build:
assessment:
validate_codebase:
phplint: { }
container_composer: { }
container_command:
commands:
- cd ${SOURCE_DIR}
- sudo -u www-data composer config repositories.asset {"composer","https://asset-packagist.org"}
- sudo -u www-data composer config extra.installer-types.0 "npm-asset"
- sudo -u www-data composer config extra.installer-types.1 "bower-asset"
- sudo -u www-data composer config extra.installer-paths.libraries\/\{\$name\} "[type:bower-asset]"
- sudo -u www-data sed -i 's/"\[type:bower-asset\]"/\["type:bower-asset"\]/' composer.json
- sudo -u www-data composer require "oomphinc/composer-installers-extender:^1.1"
- sudo -u www-data composer require "bower-asset/spectrum:^1.8" "bower-asset/jquery-simple-color:^v1.2.2"
- dir libraries
csslint:
halt-on-fail: false
eslint:
halt-on-fail: false
phpcs:
sniff-all-files: false
halt-on-fail: false
coder-version: ^8.2@stable
testing:
run_tests.standard:
types: 'Simpletest,PHPUnit-Unit,PHPUnit-Kernel,PHPUnit-Functional'
testgroups: '--all'
color: true
die-on-fail: false
keep-results: true
keep-results-table: false
verbose: false
concurrency: 0
halt-on-fail: false
repeat: 1
suppress-deprecations: true
run_tests.js:
concurrency: 1
types: PHPUnit-FunctionalJavascript
testgroups: '--all'
color: true
die-on-fail: false
keep-results: true
keep-results-table: false
verbose: false
halt-on-fail: false
repeat: 1
suppress-deprecations: true
nightwatchjs: { }
@@ -20,17 +20,19 @@
var $context = $(context);
var default_colors = settings.color_field.color_field_widget_box.settings.default_colors;
$context.find('.color-field-widget-box-form').each(function (index, element) {
var $element = $(element);
var $input = $element.prev().find('input');
$input.hide();
var props = settings.color_field.color_field_widget_box.settings[$element.prop('id')];
$element.empty().addColorPicker({
currentColor: $input.val(),
colors: default_colors,
colors: props.palette,
blotchClass:'color_field_widget_box__square',
blotchTransparentClass:'color_field_widget_box__square--transparent',
clickCallback: function(color) {
addTransparentBlotch: !props.required,
clickCallback: function (color) {
$input.val(color).trigger('change');
}
});
@@ -1,16 +1,25 @@
/**
* Color Field jQuery
* @file
* Color Field jQuery.
*/
(function ($) {
jQuery.fn.addColorPicker = function (props) {
if (!props) { props = []; }
'use strict';
if (!props) {
props = [];
}
props = jQuery.extend({
currentColor:'',
blotchElemType: 'span',
blotchElemType: 'button',
blotchClass:'colorBox',
blotchTransparentClass:'transparentBox',
clickCallback: function(ignoredColor) {},
addTransparentBlotch: true,
clickCallback: function (ignoredColor) {},
iterationCallback: null,
fillString: '&nbsp;',
fillStringX: '?',
@@ -23,20 +32,20 @@ jQuery.fn.addColorPicker = function (props) {
]
}, props);
var count = props.colors.length;
for (var i = 0; i < count; ++i) {
var color = props.colors[i];
this.addBlotchElement = function(color, blotchClass) {
var elem = jQuery('<' + props.blotchElemType + '/>')
.addClass(props.blotchClass)
.addClass(blotchClass)
.attr('color',color)
.attr('title', color)
.css('background-color',color);
// jq bug: chaining here fails if color is null b/c .css() returns (new String('transparent'))!
// Jq bug: chaining here fails if color is null b/c .css() returns (new String('transparent'))!
if (props.currentColor == color) {
elem.addClass('active');
}
if (props.clickCallback) {
elem.click(function() {
jQuery(this).parent().children('.' + props.blotchClass).removeClass('active');
elem.click(function (event) {
event.preventDefault();
jQuery(this).parent().children().removeClass('active');
jQuery(this).addClass('active');
props.clickCallback(jQuery(this).attr('color'));
});
@@ -47,25 +56,13 @@ jQuery.fn.addColorPicker = function (props) {
}
}
var elem = jQuery('<' + props.blotchElemType + '/>')
.addClass(props.blotchTransparentClass)
.attr('color', '')
.css('background-color', '');
if (props.currentColor == '') {
elem.addClass('active');
for (var i = 0; i < props.colors.length; ++i) {
var color = props.colors[i];
this.addBlotchElement(color, props.blotchClass);
}
if (props.clickCallback) {
elem.click(function() {
jQuery(this).parent().children('.' + props.blotchClass).removeClass('active');
jQuery(this).addClass('active');
props.clickCallback(jQuery(this).attr('color'));
});
}
this.append(elem);
if (props.iterationCallback) {
props.iterationCallback(this, elem, color, i);
if (props.addTransparentBlotch) {
this.addBlotchElement('', props.blotchTransparentClass);
}
return this;
@@ -2,6 +2,7 @@
* @file
* Javascript for Color Field.
*/
(function ($, Drupal) {
'use strict';
@@ -17,19 +18,18 @@
Drupal.behaviors.color_field_jquery_simple_color = {
attach: function (context, settings) {
var $context = $(context);
var settings = settings.color_field.color_field_widget_grid;
$context.find('.js-color-field-widget-grid__color').each(function (index, element) {
var $element = $(element);
var widgetSettings = settings.color_field.color_field_widget_grid[$(this).attr('id')];
$element.simpleColor({
cellWidth: settings.cell_width,
cellHeight: settings.cell_height,
cellMargin: settings.cell_margin,
boxWidth: settings.box_width,
boxHeight: settings.box_height
cellWidth: widgetSettings.cell_width,
cellHeight: widgetSettings.cell_height,
cellMargin: widgetSettings.cell_margin,
boxWidth: widgetSettings.box_width,
boxHeight: widgetSettings.box_height
});
});
}
@@ -2,6 +2,7 @@
* @file
* Javascript for Color Field.
*/
(function ($, Drupal) {
'use strict';
@@ -19,12 +20,18 @@
var $context = $(context);
var spectrum_settings = settings.color_field.color_field_widget_spectrum;
$context.find('.js-color-field-widget-spectrum').each(function (index, element) {
var $element = $(element);
var $element_color = $element.find('.js-color-field-widget-spectrum__color');
var $element_opacity = $element.find('.js-color-field-widget-spectrum__opacity');
var spectrum_settings = settings.color_field.color_field_widget_spectrum[$element.attr('id')];
// Hide the widget labels if the widgets are being shown.
if (!spectrum_settings.show_input) {
$('.js-color-field-widget-spectrum').find('label').hide();
$element_opacity.hide();
}
$element_color.spectrum({
showInitial: true,
@@ -32,14 +39,22 @@
showInput: spectrum_settings.show_input,
showAlpha: spectrum_settings.show_alpha,
showPalette: spectrum_settings.show_palette,
showPaletteOnly: !!spectrum_settings.show_palette_only,
palette: [spectrum_settings.palette],
showPaletteOnly: spectrum_settings.show_palette_only,
palette: JSON.parse('[' + spectrum_settings.palette + ']'),
showButtons: spectrum_settings.show_buttons,
allowEmpty: spectrum_settings.allow_empty,
change: function(tinycolor) {
$element_color.val(tinycolor.toHexString());
$element_opacity.val(tinycolor._roundA);
var hexColor = '';
var opacity = '';
if (tinycolor) {
hexColor = tinycolor.toHexString();
opacity = tinycolor._roundA;
}
$element_color.val(hexColor);
$element_opacity.val(opacity);
}
});
@@ -2,58 +2,36 @@
namespace Drupal\color_field;
/**
* Base color class to ease implementations.
*/
abstract class ColorBase implements ColorInterface {
/**
* @var
* The opacity of the color.
*
* @var float
*/
protected $opacity;
/**
* Convert the color to Hex format
*
* @return ColorHex
* The color in Hex format.
*/
abstract function toHex();
/**
* Convert the color to RGB format
*
* @return ColorRGB
* The color in RGB format.
*/
abstract function toRGB();
/**
* Convert the color to a string format
*
* @return String
* The color in string format.
*/
abstract function toString();
/**
* Get the opacity
* Get the opacity.
*
* @return float
* The opacity value between 0 and 1.
* The opacity value between 0 and 1.
*/
public function getOpacity() {
return $this->opacity;;
return $this->opacity;
}
/**
* Set the opacity
*
* @return float
* The opacity value between 0 and 1.
* Set the opacity.
*/
public function setOpacity($opacity) {
$this->opacity = $opacity;
}
static $patterns = array(
public static $patterns = [
'cmyk' => '/^(?:device-)?cmyk\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d+(?:\.\d+)?|\.\d+)\s*\)/',
'rgba' => '/^rgba\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3}),\s*(\d+(?:\.\d+)?|\.\d+)\s*\)/',
'rgb' => '/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/',
@@ -62,10 +40,10 @@ abstract class ColorBase implements ColorInterface {
'hsva' => '/^hsva\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%,\s*(\d+(?:\.\d+)?|\.\d+)\s*\)$/',
'hsv' => '/^hsv\((\d{1,3}),\s*(\d{1,3})%,\s*(\d{1,3})%\)$/',
'hex6' => '/^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/',
'hex3' => '/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/'
);
'hex3' => '/^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/',
];
static $named_colors = array(
public static $namedColors = [
"aliceblue" => "f0f8ff",
"antiquewhite" => "faebd7",
"aqua" => "00ffff",
@@ -208,7 +186,7 @@ abstract class ColorBase implements ColorInterface {
"white" => "ffffff",
"whitesmoke" => "f5f5f5",
"yellow" => "ffff00",
"yellowgreen" => "9acd32"
);
"yellowgreen" => "9acd32",
];
}
@@ -8,34 +8,37 @@ namespace Drupal\color_field;
class ColorCMY extends ColorBase {
/**
* The cyan
* The cyan.
*
* @var float
*/
private $cyan;
/**
* The magenta
* The magenta.
*
* @var float
*/
private $magenta;
/**
* The yellow
* The yellow.
*
* @var float
*/
private $yellow;
/**
* Create a new CMYK color
* Create a new CMYK color.
*
* @param float $cyan
* The cyan
* The cyan.
* @param float $magenta
* The magenta
* The magenta.
* @param float $yellow
* The yellow
* The yellow.
* @param float $opacity
* The opacity
* The opacity.
*/
public function __construct($cyan, $magenta, $yellow, $opacity) {
$this->cyan = $cyan;
@@ -45,42 +48,46 @@ class ColorCMY extends ColorBase {
}
/**
* Get the amount of Cyan
* Get the amount of Cyan.
*
* @return int The amount of cyan
* @return int
* The amount of cyan.
*/
public function getCyan() {
return $this->cyan;
}
/**
* Get the amount of Magenta
* Get the amount of Magenta.
*
* @return int The amount of magenta
* @return int
* The amount of magenta.
*/
public function getMagenta() {
return $this->magenta;
}
/**
* Get the amount of Yellow
* Get the amount of Yellow.
*
* @return int The amount of yellow
* @return int
* The amount of yellow.
*/
public function getYellow() {
return $this->yellow;
}
/**
* A string representation of this color in the current format
* A string representation of this color in the current format.
*
* @param bool $opacity
* Whether or not to display the opacity.
*
* @return string
* The color in format: #RRGGBB
* The color in format: #RRGGBB.
*/
public function toString($opacity = TRUE) {
return $this->toHex()->toString($opacity);
}
/**
@@ -8,38 +8,46 @@ namespace Drupal\color_field;
class ColorCMYK extends ColorBase {
/**
* The cyan
* The cyan.
*
* @var float
*/
private $cyan;
/**
* The magenta
* The magenta.
*
* @var float
*/
private $magenta;
/**
* The yellow
* The yellow.
*
* @var float
*/
private $yellow;
/**
* The key (black)
* The key (black).
*
* @var float
*/
private $key;
/**
* Create a new CMYK color
* Create a new CMYK color.
*
* @param float $cyan The cyan
* @param float $magenta The magenta
* @param float $yellow The yellow
* @param float $key The key (black)
* @param float $cyan
* The cyan.
* @param float $magenta
* The magenta.
* @param float $yellow
* The yellow.
* @param float $key
* The key (black).
* @param float $opacity
* The opacity
* The opacity.
*/
public function __construct($cyan, $magenta, $yellow, $key, $opacity) {
$this->cyan = $cyan;
@@ -50,51 +58,56 @@ class ColorCMYK extends ColorBase {
}
/**
* Get the amount of Cyan
* Get the amount of Cyan.
*
* @return int The amount of cyan
* @return int
* The amount of cyan.
*/
public function getCyan() {
return $this->cyan;
}
/**
* Get the amount of Magenta
* Get the amount of Magenta.
*
* @return int The amount of magenta
* @return int
* The amount of magenta.
*/
public function getMagenta() {
return $this->magenta;
}
/**
* Get the amount of Yellow
* Get the amount of Yellow.
*
* @return int The amount of yellow
* @return int
* The amount of yellow.
*/
public function getYellow() {
return $this->yellow;
}
/**
* Get the key (black)
* Get the key (black).
*
* @return int The amount of black
* @return int
* The amount of black.
*/
public function getKey() {
return $this->key;
}
/**
* A string representation of this color in the current format
* A string representation of this color in the current format.
*
* @param bool $opacity
* Whether or not to display the opacity.
*
* @return string
* The color in format: #RRGGBB
* The color in format: #RRGGBB.
*/
public function toString($opacity = TRUE) {
return $this->toHex()->toString($opacity);
}
/**
@@ -3,12 +3,13 @@
namespace Drupal\color_field;
/**
* Hex represents the Hex color format
* Hex represents the Hex color format.
*/
class ColorHex extends ColorBase {
/**
* The Hex triplet of the color.
*
* @var int
*/
private $color;
@@ -20,8 +21,7 @@ class ColorHex extends ColorBase {
* The string hex value (i.e. "FFFFFF").
* @param string $opacity
* The opacity value.
* @return ColorHex
* The ColorHex object.
*
* @throws Exception
*/
public function __construct($color, $opacity) {
@@ -46,13 +46,13 @@ class ColorHex extends ColorBase {
}
/**
* A string representation of this color in the current format
* A string representation of this color in the current format.
*
* @param bool $opacity
* Whether or not to display the opacity.
*
* @return string
* The color in format: #RRGGBB
* The color in format: #RRGGBB.
*/
public function toString($opacity = TRUE) {
$rgb = $this->toRGB();
@@ -7,20 +7,33 @@ namespace Drupal\color_field;
*/
interface ColorInterface {
/**
* Get the color as a string.
*
* @return string
* The color as a string.
*/
public function toString();
/**
* Get the color as a hex instance.
*
* @return \Drupal\color_field\ColorHex
* The color as a hex instance.
*/
public function toHex();
/**
* Get the color as a RGB instance.
*
* @return \Drupal\color_field\ColorRGB
* The color as a RGB instance.
*/
public function toRGB();
//public function toHSV();
//public function toHSL();
//public function toRGB();
//public function toCMYK();
//public function toCSS();
// Public function toHSV();
// public function toHSL();
// public function toRGB();
// public function toCMYK();
// public function toCSS();
}
@@ -3,30 +3,33 @@
namespace Drupal\color_field;
/**
* RGB represents the RGB color format
* RGB represents the RGB color format.
*/
class ColorRGB extends ColorBase {
/**
* The red value (0-255)
* The red value (0-255).
*
* @var float
*/
private $red;
/**
* The green value (0-255)
* The green value (0-255).
*
* @var float
*/
private $green;
/**
* The blue value (0-255)
* The blue value (0-255).
*
* @var float
*/
private $blue;
/**
* Create a new RGB color
* Create a new RGB color.
*
* @param int $red
* The red (0-255)
@@ -35,7 +38,7 @@ class ColorRGB extends ColorBase {
* @param int $blue
* The blue (0-255)
* @param float $opacity
* The opacity
* The opacity.
*
* @throws Exception
*/
@@ -58,34 +61,37 @@ class ColorRGB extends ColorBase {
}
/**
* Get the red value (rounded)
* Get the red value (rounded).
*
* @return int The red value
* @return int
* The red value
*/
public function getRed() {
return (0.5 + $this->red) | 0;
}
/**
* Get the green value (rounded)
* Get the green value (rounded).
*
* @return int The green value
* @return int
* The green value
*/
public function getGreen() {
return (0.5 + $this->green) | 0;
}
/**
* Get the blue value (rounded)
* Get the blue value (rounded).
*
* @return int The blue value
* @return int
* The blue value
*/
public function getBlue() {
return (0.5 + $this->blue) | 0;
}
/**
* A string representation of this color in the current format
* A string representation of this color in the current format.
*
* @param bool $opacity
* Whether or not to display the opacity.
@@ -1,17 +1,16 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldFormatter\ColorFieldFormatterCss.
*/
namespace Drupal\color_field\Plugin\Field\FieldFormatter;
use Drupal\color_field\Plugin\Field\FieldType\ColorFieldType;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\color_field\ColorHex;
use Drupal\color_field\Plugin\Field\FieldType\ColorFieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Utility\Token;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Plugin implementation of the color_field css declaration formatter.
@@ -25,66 +24,110 @@ use Drupal\color_field\ColorHex;
* }
* )
*/
class ColorFieldFormatterCss extends FormatterBase {
class ColorFieldFormatterCss extends FormatterBase implements ContainerFactoryPluginInterface {
/**
* The token service.
*
* @var \Drupal\token\TokenInterface
*/
protected $tokenService;
/**
* Constructs an ColorFieldFormatterCss object.
*
* @param string $plugin_id
* The plugin_id for the formatter.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Field\FieldDefinitionInterface $field_definition
* The definition of the field to which the formatter is associated.
* @param array $settings
* The formatter settings.
* @param string $label
* The formatter label display setting.
* @param string $view_mode
* The view mode.
* @param array $third_party_settings
* Any third party settings.
* @param \Drupal\Core\Utility\Token $token_service
* The token service.
*/
public function __construct($plugin_id, $plugin_definition, FieldDefinitionInterface $field_definition, array $settings, $label, $view_mode, array $third_party_settings, Token $token_service) {
parent::__construct($plugin_id, $plugin_definition, $field_definition, $settings, $label, $view_mode, $third_party_settings);
$this->tokenService = $token_service;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
// @see \Drupal\Core\Field\FormatterPluginManager::createInstance().
return new static(
$plugin_id,
$plugin_definition,
$configuration['field_definition'],
$configuration['settings'],
$configuration['label'],
$configuration['view_mode'],
$configuration['third_party_settings'],
$container->get('token')
);
}
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'selector' => 'body',
'property' => 'background-color',
'important' => TRUE,
'opacity' => TRUE,
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$opacity = $this->getFieldSetting('opacity');
$elements = [];
$elements['selector'] = array(
'#title' => t('Selector'),
'#description' => t('A valid CSS selector such as <code>.links > li > a, #logo</code>.'),
$elements['selector'] = [
'#title' => $this->t('Selector'),
'#description' => $this->t('A valid CSS selector such as <code>.links > li > a, #logo</code>.'),
'#type' => 'textarea',
'#rows' => '1',
'#default_value' => $this->getSetting('selector'),
'#required' => TRUE,
'#placeholder' => 'body > div > a',
);
//$element['token'] = array(
// '#theme' => 'token_tree',
// '#token_types' => array($instance['entity_type']),
// '#dialog' => TRUE,
//);
$elements['property'] = array(
'#title' => t('Property'),
'#description' => t(''),
];
$elements['token_help'] = [
'#theme' => 'token_tree_link',
'#token_types' => [$this->fieldDefinition->getTargetEntityTypeId()],
];
$elements['property'] = [
'#title' => $this->t('Property'),
'#type' => 'select',
'#default_value' => $this->getSetting('property'),
'#required' => TRUE,
'#options' => array(
'background-color' => t('Background color'),
'color' => t('Text color'),
),
);
$elements['important'] = array(
'#title' => t('Important'),
'#description' => t('Whenever this declaration is more important than others.'),
'#options' => [
'background-color' => $this->t('Background color'),
'color' => $this->t('Text color'),
],
];
$elements['important'] = [
'#title' => $this->t('Important'),
'#description' => $this->t('Whenever this declaration is more important than others.'),
'#type' => 'checkbox',
'#default_value' => $this->getSetting('important'),
);
];
if ($opacity) {
$elements['opacity'] = array(
if ($this->getFieldSetting('opacity')) {
$elements['opacity'] = [
'#type' => 'checkbox',
'#title' => t('Display opacity'),
'#title' => $this->t('Display opacity'),
'#default_value' => $this->getSetting('opacity'),
);
];
}
return $elements;
@@ -99,12 +142,18 @@ class ColorFieldFormatterCss extends FormatterBase {
$summary = [];
$summary[] = t('CSS selector : @css_selector', array('@css_selector' => $settings['selector']));
$summary[] = t('CSS property : @css_property', array('@css_property' => $settings['property']));
$summary[] = t('!important declaration : @important_declaration', array('@important_declaration' => (($settings['important']) ? t('Yes') : t('No'))));
$summary[] = $this->t('CSS selector : @css_selector', [
'@css_selector' => $settings['selector'],
]);
$summary[] = $this->t('CSS property : @css_property', [
'@css_property' => $settings['property'],
]);
$summary[] = $this->t('!important declaration : @important_declaration', [
'@important_declaration' => (($settings['important']) ? $this->t('Yes') : $this->t('No')),
]);
if ($opacity && $settings['opacity']) {
$summary[] = t('Display with opacity.');
$summary[] = $this->t('Display with opacity.');
}
return $summary;
@@ -118,10 +167,16 @@ class ColorFieldFormatterCss extends FormatterBase {
$elements = [];
$entity = $items->getEntity();
$tokens = [
$entity->getEntityType()->id() => $entity,
];
foreach ($items as $delta => $item) {
$value = $this->viewValue($item);
$selector = $settings['selector'];
$selector = $this->tokenService->replace(
$settings['selector'],
$tokens
);
$important = ($settings['important']) ? ' !important' : '';
$property = $settings['property'];
@@ -133,7 +188,8 @@ class ColorFieldFormatterCss extends FormatterBase {
$elements['#attached']['html_head'][] = [[
'#tag' => 'style',
'#value' => $inline_css,
], 'colorfield_css'];
], sha1($inline_css),
];
}
return $elements;
@@ -150,7 +206,8 @@ class ColorFieldFormatterCss extends FormatterBase {
if ($opacity && $settings['opacity']) {
$rgbtext = $color_hex->toRGB()->toString(TRUE);
} else {
}
else {
$rgbtext = $color_hex->toRGB()->toString(FALSE);
}
@@ -1,15 +1,9 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldFormatter\ColorFieldFormatterSwatch.
*/
namespace Drupal\color_field\Plugin\Field\FieldFormatter;
use Drupal\color_field\Plugin\Field\FieldType\ColorFieldType;
use Drupal\Core\Field\FormatterBase;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\color_field\ColorHex;
@@ -32,12 +26,12 @@ class ColorFieldFormatterSwatch extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'shape' => 'square',
'width' => 50,
'height' => 50,
'opacity' => TRUE,
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
@@ -48,42 +42,47 @@ class ColorFieldFormatterSwatch extends FormatterBase {
$elements = [];
$elements['shape'] = array(
$elements['shape'] = [
'#type' => 'select',
'#title' => t('Shape'),
'#title' => $this->t('Shape'),
'#options' => $this->getShape(),
'#default_value' => $this->getSetting('shape'),
'#description' => t(''),
);
$elements['width'] = array(
'#description' => '',
];
$elements['width'] = [
'#type' => 'number',
'#title' => t('Width'),
'#title' => $this->t('Width'),
'#default_value' => $this->getSetting('width'),
'#min' => 1,
'#description' => t(''),
);
$elements['height'] = array(
'#description' => '',
];
$elements['height'] = [
'#type' => 'number',
'#title' => t('Height'),
'#title' => $this->t('Height'),
'#default_value' => $this->getSetting('height'),
'#min' => 1,
'#description' => t(''),
);
'#description' => '',
];
if ($opacity) {
$elements['opacity'] = array(
$elements['opacity'] = [
'#type' => 'checkbox',
'#title' => t('Display opacity'),
'#title' => $this->t('Display opacity'),
'#default_value' => $this->getSetting('opacity'),
);
];
}
return $elements;
}
/**
* @param string $shape
* This is used to get the shape.
*
* @param string|null $shape
* The specific shape name to get.
*
* @return array|string
* An array of shape ids/names or translated name of the specified shape.
*/
protected function getShape($shape = NULL) {
$formats = [];
@@ -106,17 +105,17 @@ class ColorFieldFormatterSwatch extends FormatterBase {
$summary = [];
$summary[] = t('@shape', array(
$summary[] = $this->t('@shape', [
'@shape' => $this->getShape($settings['shape']),
));
]);
$summary[] = t('Width: @width Height: @height', array(
$summary[] = $this->t('Width: @width Height: @height', [
'@width' => $settings['width'],
'@height' => $settings['height']
));
'@height' => $settings['height'],
]);
if ($opacity && $settings['opacity']) {
$summary[] = t('Display with opacity.');
$summary[] = $this->t('Display with opacity.');
}
return $summary;
@@ -133,13 +132,13 @@ class ColorFieldFormatterSwatch extends FormatterBase {
$elements['#attached']['library'][] = 'color_field/color-field-formatter-swatch';
foreach ($items as $delta => $item) {
$elements[$delta] = array(
$elements[$delta] = [
'#theme' => 'color_field_formatter_swatch',
'#color' => $this->viewValue($item),
'#shape' => $settings['shape'],
'#width' => $settings['width'],
'#height' => $settings['height'],
);
];
}
return $elements;
@@ -156,7 +155,8 @@ class ColorFieldFormatterSwatch extends FormatterBase {
if ($opacity && $settings['opacity']) {
$rgbtext = $color_hex->toRGB()->toString(TRUE);
} else {
}
else {
$rgbtext = $color_hex->toRGB()->toString(FALSE);
}
@@ -1,10 +1,5 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldFormatter\ColorFieldFormatterText.
*/
namespace Drupal\color_field\Plugin\Field\FieldFormatter;
use Drupal\color_field\Plugin\Field\FieldType\ColorFieldType;
@@ -31,10 +26,10 @@ class ColorFieldFormatterText extends FormatterBase {
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'format' => 'hex',
'opacity' => TRUE,
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
@@ -45,27 +40,32 @@ class ColorFieldFormatterText extends FormatterBase {
$elements = [];
$elements['format'] = array(
$elements['format'] = [
'#type' => 'select',
'#title' => t('Format'),
'#title' => $this->t('Format'),
'#options' => $this->getColorFormat(),
'#default_value' => $this->getSetting('format'),
);
];
if ($opacity) {
$elements['opacity'] = array(
$elements['opacity'] = [
'#type' => 'checkbox',
'#title' => t('Display opacity'),
'#title' => $this->t('Display opacity'),
'#default_value' => $this->getSetting('opacity'),
);
];
}
return $elements;
}
/**
* This function is used to get the color format.
*
* @param string $format
* Format is of string type.
*
* @return array|string
* Returns array or string.
*/
protected function getColorFormat($format = NULL) {
$formats = [];
@@ -87,12 +87,12 @@ class ColorFieldFormatterText extends FormatterBase {
$summary = [];
$summary[] = t('@format', array(
$summary[] = $this->t('@format', [
'@format' => $this->getColorFormat($settings['format']),
));
]);
if ($opacity && $settings['opacity']) {
$summary[] = t('Display with opacity.');
$summary[] = $this->t('Display with opacity.');
}
return $summary;
@@ -124,7 +124,8 @@ class ColorFieldFormatterText extends FormatterBase {
case 'hex':
if ($opacity && $settings['opacity']) {
$output = $color_hex->toString(TRUE);
} else {
}
else {
$output = $color_hex->toString(FALSE);
}
break;
@@ -132,7 +133,8 @@ class ColorFieldFormatterText extends FormatterBase {
case 'rgb':
if ($opacity && $settings['opacity']) {
$output = $color_hex->toRGB()->toString(TRUE);
} else {
}
else {
$output = $color_hex->toRGB()->toString(FALSE);
}
break;
@@ -1,10 +1,5 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldType\ColorFieldType.
*/
namespace Drupal\color_field\Plugin\Field\FieldType;
use Drupal\Core\Field\FieldDefinitionInterface;
@@ -13,7 +8,6 @@ use Drupal\Core\Field\FieldStorageDefinitionInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\StringTranslation\TranslatableMarkup;
use Drupal\Core\TypedData\DataDefinition;
use Drupal\color_field\ColorHex;
/**
* Plugin implementation of the 'color_type' field type.
@@ -28,22 +22,29 @@ use Drupal\color_field\ColorHex;
*/
class ColorFieldType extends FieldItemBase {
/**
* {@inheritdoc}
*/
public static function mainPropertyName() {
return 'color';
}
/**
* {@inheritdoc}
*/
public static function defaultFieldSettings() {
return array(
return [
'opacity' => TRUE,
) + parent::defaultFieldSettings();
] + parent::defaultFieldSettings();
}
/**
* {@inheritdoc}
*/
public static function defaultStorageSettings() {
return array(
return [
'format' => '#HEXHEX',
) + parent::defaultStorageSettings();
] + parent::defaultStorageSettings();
}
/**
@@ -52,18 +53,18 @@ class ColorFieldType extends FieldItemBase {
public function storageSettingsForm(array &$form, FormStateInterface $form_state, $has_data) {
$element = [];
$element['format'] = array(
$element['format'] = [
'#type' => 'select',
'#title' => t('Format storage'),
'#description' => t('Choose how to store the color.'),
'#title' => $this->t('Format storage'),
'#description' => $this->t('Choose how to store the color.'),
'#default_value' => $this->getSetting('format'),
'#options' => array(
'#HEXHEX' => t('#123ABC'),
'HEXHEX' => t('123ABC'),
'#hexhex' => t('#123abc'),
'hexhex' => t('123abc'),
),
);
'#options' => [
'#HEXHEX' => $this->t('#123ABC'),
'HEXHEX' => $this->t('123ABC'),
'#hexhex' => $this->t('#123abc'),
'hexhex' => $this->t('123abc'),
],
];
$element += parent::storageSettingsForm($form, $form_state, $has_data);
@@ -76,12 +77,12 @@ class ColorFieldType extends FieldItemBase {
public function fieldSettingsForm(array $form, FormStateInterface $form_state) {
$element = [];
$element['opacity'] = array(
$element['opacity'] = [
'#type' => 'checkbox',
'#title' => t('Record opacity'),
'#description' => t('Whether or not to record.'),
'#title' => $this->t('Record opacity'),
'#description' => $this->t('Whether or not to record.'),
'#default_value' => $this->getSetting('opacity'),
);
];
return $element;
}
@@ -91,26 +92,26 @@ class ColorFieldType extends FieldItemBase {
*/
public static function schema(FieldStorageDefinitionInterface $field_definition) {
$format = $field_definition->getSetting('format');
$color_length = isset($format) ? strlen($format) : 7 ;
return array(
'columns' => array(
'color' => array(
$color_length = isset($format) ? strlen($format) : 7;
return [
'columns' => [
'color' => [
'description' => 'The color value',
'type' => 'varchar',
'length' => $color_length,
'not null' => FALSE,
),
'opacity' => array(
],
'opacity' => [
'description' => 'The opacity/alphavalue property',
'type' => 'float',
'size' => 'tiny',
'not null' => FALSE,
),
),
'indexes' => array(
'color' => array('color'),
),
);
],
],
'indexes' => [
'color' => ['color'],
],
];
}
/**
@@ -144,34 +145,34 @@ class ColorFieldType extends FieldItemBase {
$label = $this->getFieldDefinition()->getLabel();
$constraints[] = $constraint_manager->create('ComplexData', array(
'color' => array(
'Regex' => array(
$constraints[] = $constraint_manager->create('ComplexData', [
'color' => [
'Regex' => [
'pattern' => '/^#?(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$/i',
)
),
));
],
],
]);
if ($opacity = $this->getSetting('opacity')) {
$min = 0;
$constraints[] = $constraint_manager->create('ComplexData', array(
'opacity' => array(
'Range' => array(
$constraints[] = $constraint_manager->create('ComplexData', [
'opacity' => [
'Range' => [
'min' => $min,
'minMessage' => t('%name: the opacity may be no less than %min.', array('%name' => $label, '%min' => $min)),
)
),
));
'minMessage' => $this->t('%name: the opacity may be no less than %min.', ['%name' => $label, '%min' => $min]),
],
],
]);
$max = 1;
$constraints[] = $constraint_manager->create('ComplexData', array(
'opacity' => array(
'Range' => array(
$constraints[] = $constraint_manager->create('ComplexData', [
'opacity' => [
'Range' => [
'max' => $max,
'maxMessage' => t('%name: the opacity may be no greater than %max.', array('%name' => $label, '%max' => $max)),
)
),
));
'maxMessage' => $this->t('%name: the opacity may be no greater than %max.', ['%name' => $label, '%max' => $max]),
],
],
]);
}
return $constraints;
@@ -188,12 +189,15 @@ class ColorFieldType extends FieldItemBase {
case '#HEXHEX':
$values['color'] = '#111AAA';
break;
case 'HEXHEX':
$values['color'] = '111111';
break;
case '#hexhex':
$values['color'] = '#111aaa';
break;
case 'hexhex':
$values['color'] = '111111';
break;
@@ -225,12 +229,15 @@ class ColorFieldType extends FieldItemBase {
case '#HEXHEX':
$color = '#' . strtoupper($color);
break;
case 'HEXHEX':
$color = strtoupper($color);
break;
case '#hexhex':
$color = '#' . strtolower($color);
break;
case 'hexhex':
$color = strtolower($color);
break;
@@ -238,6 +245,10 @@ class ColorFieldType extends FieldItemBase {
$this->color = $color;
}
if (!$this->getSetting('opacity')) {
unset($this->opacity);
}
}
}
@@ -0,0 +1,61 @@
<?php
namespace Drupal\color_field\Plugin\Field\FieldWidget;
use Drupal\Component\Utility\Html;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
* Base class for color_field widgets.
*/
abstract class ColorFieldWidgetBase extends WidgetBase {
/**
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element['#uid'] = Html::getUniqueId('color-field-' . $this->fieldDefinition->getName());
// Prepare color.
$color = NULL;
if (isset($items[$delta]->color)) {
$color = $items[$delta]->color;
if (substr($color, 0, 1) !== '#') {
$color = '#' . $color;
}
}
$input = [
'#type' => 'textfield',
'#maxlength' => 7,
'#size' => 7,
'#required' => $element['#required'],
'#default_value' => $color,
];
if ($this->getFieldSetting('opacity')) {
$element['color'] = $input;
$element['color']['#title'] = $this->t('Color');
$element['#type'] = 'fieldset';
$element['opacity'] = [
'#title' => $this->t('Opacity'),
'#type' => 'number',
'#min' => 0,
'#max' => 1,
'#step' => 0.01,
'#required' => $element['#required'],
'#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL,
'#placeholder' => $this->getSetting('placeholder_opacity'),
];
}
else {
$element['color'] = $element + $input;
}
return $element;
}
}
@@ -1,14 +1,8 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldWidget\ColorFieldWidgetBox.
*/
namespace Drupal\color_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
@@ -23,36 +17,62 @@ use Drupal\Core\Form\FormStateInterface;
* }
* )
*/
class ColorFieldWidgetBox extends WidgetBase {
class ColorFieldWidgetBox extends ColorFieldWidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'default_colors' => '
#AC725E,#D06B64,#F83A22,#FA573C,#FF7537,#FFAD46
#42D692,#16A765,#7BD148,#B3DC6C,#FBE983
#92E1C0,#9FE1E7,#9FC6E7,#4986E7,#9A9CFF
#B99AFF,#C2C2C2,#CABDBF,#CCA6AC,#F691B2
#CD74E6,#A47AE2',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['default_colors'] = array(
$element['default_colors'] = [
'#type' => 'textarea',
'#title' => t('Default colors'),
'#title' => $this->t('Default colors'),
'#default_value' => $this->getSetting('default_colors'),
'#required' => TRUE,
'#description' => t('Default colors for pre-selected color boxes'),
);
'#element_validate' => [
[$this, 'settingsColorValidate'],
],
'#description' => $this->t('Default colors for pre-selected color boxes. Enter as 6 digit upper case hex - such as #FF0000.'),
];
return $element;
}
/**
* Use element validator to make sure that hex values are in correct format.
*
* @param array $element
* The Default colors element.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The current state of the form.
*/
public function settingsColorValidate(array $element, FormStateInterface $form_state) {
$default_colors = $form_state->getValue($element['#parents']);
$colors = '';
if (!empty($default_colors)) {
preg_match_all("/#[0-9a-fA-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER);
foreach ($default_colors as $color) {
if (!empty($colors)) {
$colors .= ',';
}
$colors .= strtoupper($color[0]);
}
}
$form_state->setValue($element['#parents'], $colors);
}
/**
* {@inheritdoc}
*/
@@ -62,7 +82,7 @@ class ColorFieldWidgetBox extends WidgetBase {
$default_colors = $this->getSetting('default_colors');
if (!empty($default_colors)) {
preg_match_all("/#[0-9a-fA-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER);
preg_match_all("/#[0-9A-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER);
foreach ($default_colors as $color) {
$colors = $color[0];
$summary[] = $colors;
@@ -70,7 +90,7 @@ class ColorFieldWidgetBox extends WidgetBase {
}
if (empty($summary)) {
$summary[] = t('No default colors');
$summary[] = $this->t('No default colors');
}
return $summary;
@@ -80,58 +100,29 @@ class ColorFieldWidgetBox extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
// We are nesting some sub-elements inside the parent, so we need a wrapper.
// We also need to add another #title attribute at the top level for ease in
// identifying this item in error messages. We do not want to display this
// title because the actual title display is handled at a higher level by
// the Field module.
$element['#theme_wrappers'] = array('color_field_widget_box');
$element['#attributes']['class'][] = 'container-inline';
$element = parent::formElement($items, $delta, $element, $form, $form_state);
// Ensure the default value is the required format.
if ($element['color']['#default_value']) {
$element['color']['#default_value'] = strtoupper($element['color']['#default_value']);
if (strlen($element['color']['#default_value']) === 6) {
$element['color']['#default_value'] = '#' . $element['color']['#default_value'];
}
}
$element['#attached']['library'][] = 'color_field/color-field-widget-box';
// Set Drupal settings.
$settings = [];
$settings[$element['#uid']] = [
'required' => $this->fieldDefinition->isRequired(),
];
$default_colors = $this->getSetting('default_colors');
preg_match_all("/#[0-9a-fA-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER);
preg_match_all("/#[0-9A-F]{6}/", $default_colors, $default_colors, PREG_SET_ORDER);
foreach ($default_colors as $color) {
$settings['default_colors'][] = $color[0];
$settings[$element['#uid']]['palette'][] = $color[0];
}
$element['#attached']['drupalSettings']['color_field']['color_field_widget_box']['settings'] = $settings;
// Retrieve field label and description.
$element['#title'] = $this->fieldDefinition->getLabel();;
$element['#description'] = $this->fieldDefinition->getDescription();
// Prepare color.
$color = NULL;
if (isset($items[$delta]->color)) {
$color = $items[$delta]->color;
if (substr($color, 0, 1) !== '#') {
$color = '#' . $color;
}
}
$element['color'] = array(
'#maxlength' => 7,
'#size' => 7,
'#type' => 'textfield',
'#default_value' => $color,
'#attributes' => array('class' => array('visually-hidden')),
);
$element['color']['#suffix'] = "<div class='color-field-widget-box-form'></div>";
if ($this->getFieldSetting('opacity')) {
$element['opacity'] = array(
'#title' => t('Opacity'),
'#type' => 'textfield',
'#maxlength' => 4,
'#size' => 4,
'#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL,
'#placeholder' => $this->getSetting('placeholder_opacity'),
);
}
$element['color']['#suffix'] = "<div class='color-field-widget-box-form' id='" . $element['#uid'] . "'></div>";
return $element;
}
@@ -1,14 +1,8 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldWidget\ColorFieldWidgetDefault.
*/
namespace Drupal\color_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
@@ -23,34 +17,34 @@ use Drupal\Core\Form\FormStateInterface;
* }
* )
*/
class ColorFieldWidgetDefault extends WidgetBase {
class ColorFieldWidgetDefault extends ColorFieldWidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'placeholder_color' => '',
'placeholder_opacity' => '',
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
* {@inheritdoc}
*/
public function settingsForm(array $form, FormStateInterface $form_state) {
$element['placeholder_color'] = array(
$element['placeholder_color'] = [
'#type' => 'textfield',
'#title' => t('Color placeholder'),
'#title' => $this->t('Color placeholder'),
'#default_value' => $this->getSetting('placeholder_color'),
'#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
);
$element['placeholder_opacity'] = array(
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
];
$element['placeholder_opacity'] = [
'#type' => 'textfield',
'#title' => t('Opacity placeholder'),
'#title' => $this->t('Opacity placeholder'),
'#default_value' => $this->getSetting('placeholder_opacity'),
'#description' => t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
);
'#description' => $this->t('Text that will be shown inside the field until a value is entered. This hint is usually a sample value or a brief description of the expected format.'),
];
return $element;
}
@@ -64,15 +58,15 @@ class ColorFieldWidgetDefault extends WidgetBase {
$placeholder_opacity = $this->getSetting('placeholder_opacity');
if (!empty($placeholder_color)) {
$summary[] = t('Color placeholder: @placeholder_color', array('@placeholder_color' => $placeholder_color));
$summary[] = $this->t('Color placeholder: @placeholder_color', ['@placeholder_color' => $placeholder_color]);
}
if (!empty($placeholder_opacity)) {
$summary[] = t('Opacity placeholder: @placeholder_opacity', array('@placeholder_opacity' => $placeholder_opacity));
$summary[] = $this->t('Opacity placeholder: @placeholder_opacity', ['@placeholder_opacity' => $placeholder_opacity]);
}
if (empty($summary)) {
$summary[] = t('No placeholder');
$summary[] = $this->t('No placeholder');
}
return $summary;
@@ -82,32 +76,11 @@ class ColorFieldWidgetDefault extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$label = $this->fieldDefinition->getLabel();
$element['color'] = array(
'#title' => t($label),
'#type' => 'textfield',
'#maxlength' => 7,
'#size' => 7,
'#required' => $element['#required'],
'#placeholder' => $this->getSetting('placeholder_color'),
'#default_value' => isset($items[$delta]->color) ? $items[$delta]->color : NULL,
);
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$element['color']['#placeholder'] = $this->getSetting('placeholder_color');
if ($this->getFieldSetting('opacity')) {
$element['color']['#prefix'] = '<div class="container-inline">';
$element['opacity'] = array(
'#title' => t('Opacity'),
'#type' => 'textfield',
'#maxlength' => 4,
'#size' => 4,
'#required' => $element['#required'],
'#placeholder' => $this->getSetting('placeholder_opacity'),
'#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL,
'#suffix' => '</div>',
);
$element['opacity']['#placeholder'] = $this->getSetting('placeholder_opacity');
}
return $element;
@@ -1,14 +1,8 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldWidget\ColorFieldWidgetGrid.
*/
namespace Drupal\color_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
@@ -23,20 +17,20 @@ use Drupal\Core\Form\FormStateInterface;
* }
* )
*/
class ColorFieldWidgetGrid extends WidgetBase {
class ColorFieldWidgetGrid extends ColorFieldWidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'cell_width' => 10,
'cell_height' => 10,
'cell_margin' => 1,
'box_width' => 115,
'box_height' => 20,
'columns' => 16,
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
@@ -45,48 +39,48 @@ class ColorFieldWidgetGrid extends WidgetBase {
public function settingsForm(array $form, FormStateInterface $form_state) {
$element = [];
$element['cell_width'] = array(
$element['cell_width'] = [
'#type' => 'textfield',
'#title' => t('Cell width'),
'#title' => $this->t('Cell width'),
'#default_value' => $this->getSetting('cell_width'),
'#required' => TRUE,
'#description' => t('Width of each individual color cell.'),
);
$element['cell_height'] = array(
'#description' => $this->t('Width of each individual color cell.'),
];
$element['cell_height'] = [
'#type' => 'textfield',
'#title' => t('Height width'),
'#title' => $this->t('Height width'),
'#default_value' => $this->getSetting('cell_height'),
'#required' => TRUE,
'#description' => t('Height of each individual color cell.'),
);
$element['cell_margin'] = array(
'#description' => $this->t('Height of each individual color cell.'),
];
$element['cell_margin'] = [
'#type' => 'textfield',
'#title' => t('Cell margin'),
'#title' => $this->t('Cell margin'),
'#default_value' => $this->getSetting('cell_margin'),
'#required' => TRUE,
'#description' => t('Margin of each individual color cell.'),
);
$element['box_width'] = array(
'#description' => $this->t('Margin of each individual color cell.'),
];
$element['box_width'] = [
'#type' => 'textfield',
'#title' => t('Box width'),
'#title' => $this->t('Box width'),
'#default_value' => $this->getSetting('box_width'),
'#required' => TRUE,
'#description' => t('Width of the color display box.'),
);
$element['box_height'] = array(
'#description' => $this->t('Width of the color display box.'),
];
$element['box_height'] = [
'#type' => 'textfield',
'#title' => t('Box height'),
'#title' => $this->t('Box height'),
'#default_value' => $this->getSetting('box_height'),
'#required' => TRUE,
'#description' => t('Height of the color display box.'),
);
$element['columns'] = array(
'#description' => $this->t('Height of the color display box.'),
];
$element['columns'] = [
'#type' => 'textfield',
'#title' => t('Columns number'),
'#title' => $this->t('Columns number'),
'#default_value' => $this->getSetting('columns'),
'#required' => TRUE,
'#description' => t('Number of columns to display. Color order may look strange if this is altered.'),
);
'#description' => $this->t('Number of columns to display. Color order may look strange if this is altered.'),
];
return $element;
}
@@ -104,31 +98,31 @@ class ColorFieldWidgetGrid extends WidgetBase {
$columns = $this->getSetting('columns');
if (!empty($cell_width)) {
$summary[] = t('Cell width: @cell_width', array('@cell_width' => $cell_width));
$summary[] = $this->t('Cell width: @cell_width', ['@cell_width' => $cell_width]);
}
if (!empty($cell_height)) {
$summary[] = t('Cell height: @cell_height', array('@cell_height' => $cell_height));
$summary[] = $this->t('Cell height: @cell_height', ['@cell_height' => $cell_height]);
}
if (!empty($cell_margin)) {
$summary[] = t('Cell margin: @cell_margin', array('@cell_margin' => $cell_margin));
$summary[] = $this->t('Cell margin: @cell_margin', ['@cell_margin' => $cell_margin]);
}
if (!empty($box_width)) {
$summary[] = t('Box width: @box_width', array('@box_width' => $box_width));
$summary[] = $this->t('Box width: @box_width', ['@box_width' => $box_width]);
}
if (!empty($box_height)) {
$summary[] = t('Box height: @box_height', array('@box_height' => $box_height));
$summary[] = $this->t('Box height: @box_height', ['@box_height' => $box_height]);
}
if (!empty($columns)) {
$summary[] = t('Columns: @columns', array('@columns' => $columns));
$summary[] = $this->t('Columns: @columns', ['@columns' => $columns]);
}
if (empty($summary)) {
$summary[] = t('No placeholder');
$summary[] = $this->t('No placeholder');
}
return $summary;
@@ -138,52 +132,23 @@ class ColorFieldWidgetGrid extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
$element = parent::formElement($items, $delta, $element, $form, $form_state);
// We are nesting some sub-elements inside the parent, so we need a wrapper.
// We also need to add another #title attribute at the top level for ease in
// identifying this item in error messages. We do not want to display this
// title because the actual title display is handled at a higher level by
// the Field module.
//$element['#theme_wrappers'] = array('color_field_widget_grid');
// $element['#theme_wrappers'] = array('color_field_widget_grid');.
$element['#attached']['library'][] = 'color_field/color-field-widget-grid';
// Set Drupal settings.
$settings = $this->getSettings();
$element['#attached']['drupalSettings']['color_field']['color_field_widget_grid'] = $settings;
$element['#attached']['drupalSettings']['color_field']['color_field_widget_grid'][$element['#uid']] = $settings;
// Prepare color.
$color = NULL;
if (isset($items[$delta]->color)) {
$color = $items[$delta]->color;
if (substr($color, 0, 1) !== '#') {
$color = '#' . $color;
}
}
$element['color'] = array(
'#title' => t('Color'),
'#type' => 'textfield',
'#maxlength' => 7,
'#size' => 7,
'#required' => $element['#required'],
'#default_value' => $color,
'#attributes' => array('class' => array('js-color-field-widget-grid__color')),
);
if ($this->getFieldSetting('opacity')) {
$element['color']['#prefix'] = '<div class="container-inline">';
$element['opacity'] = array(
'#title' => t('Opacity'),
'#type' => 'textfield',
'#maxlength' => 4,
'#size' => 4,
'#required' => $element['#required'],
'#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL,
'#suffix' => '</div>',
);
}
$element['color']['#attributes']['class'][] = 'js-color-field-widget-grid__color';
$element['color']['#attributes']['id'] = $element['#uid'];
$element['color']['#wrapper_attributes']['class'][] = 'clearfix';
return $element;
}
@@ -1,14 +1,8 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldWidget\ColorFieldWidgetSpectrum.
*/
namespace Drupal\color_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
@@ -23,14 +17,13 @@ use Drupal\Core\Form\FormStateInterface;
* }
* )
*/
class ColorFieldWidgetHTML5 extends WidgetBase {
class ColorFieldWidgetHTML5 extends ColorFieldWidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
) + parent::defaultSettings();
return [] + parent::defaultSettings();
}
/**
@@ -46,7 +39,7 @@ class ColorFieldWidgetHTML5 extends WidgetBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary = [];
return $summary;
}
@@ -55,37 +48,8 @@ class ColorFieldWidgetHTML5 extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
// Prepare color.
$color = NULL;
if (isset($items[$delta]->color)) {
$color = $items[$delta]->color;
if (substr($color, 0, 1) !== '#') {
$color = '#' . $color;
}
}
$element['color'] = array(
'#title' => t('Color'),
'#type' => 'color',
'#maxlength' => 7,
'#size' => 7,
'#required' => $element['#required'],
'#default_value' => $color,
);
if ($this->getFieldSetting('opacity')) {
$element['color']['#prefix'] = '<div class="container-inline">';
$element['opacity'] = array(
'#title' => t('Opacity'),
'#type' => 'textfield',
'#maxlength' => 4,
'#size' => 4,
'#required' => $element['#required'],
'#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL,
'#suffix' => '</div>',
);
}
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$element['color']['#type'] = 'color';
return $element;
}
@@ -1,14 +1,8 @@
<?php
/**
* @file
* Contains Drupal\color_field\Plugin\Field\FieldWidget\ColorFieldWidgetSpectrum.
*/
namespace Drupal\color_field\Plugin\Field\FieldWidget;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\WidgetBase;
use Drupal\Core\Form\FormStateInterface;
/**
@@ -23,20 +17,20 @@ use Drupal\Core\Form\FormStateInterface;
* }
* )
*/
class ColorFieldWidgetSpectrum extends WidgetBase {
class ColorFieldWidgetSpectrum extends ColorFieldWidgetBase {
/**
* {@inheritdoc}
*/
public static function defaultSettings() {
return array(
return [
'show_input' => FALSE,
'show_palette' => FALSE,
'palette' => '',
'show_palette_only' => TRUE,
'show_palette_only' => FALSE,
'show_buttons' => FALSE,
'allow_empty' => FALSE,
) + parent::defaultSettings();
] + parent::defaultSettings();
}
/**
@@ -45,47 +39,52 @@ class ColorFieldWidgetSpectrum extends WidgetBase {
public function settingsForm(array $form, FormStateInterface $form_state) {
$element = [];
$element['show_input'] = array(
$element['show_input'] = [
'#type' => 'checkbox',
'#title' => t('Show Input'),
'#title' => $this->t('Show Input'),
'#default_value' => $this->getSetting('show_input'),
'#description' => t('Allow free form typing.'),
);
$element['show_palette'] = array(
'#description' => $this->t('Allow free form typing.'),
];
$element['show_palette'] = [
'#type' => 'checkbox',
'#title' => t('Show Palette'),
'#title' => $this->t('Show Palette'),
'#default_value' => $this->getSetting('show_palette'),
'#description' => t('Show or hide Palette in Spectrum Widget'),
);
$element['palette'] = array(
'#description' => $this->t('Show or hide Palette in Spectrum Widget'),
];
$element['palette'] = [
'#type' => 'textarea',
'#title' => t('Color Palette'),
'#title' => $this->t('Color Palette'),
'#default_value' => $this->getSetting('palette'),
'#description' => t('Selectable color palette to accompany the Spectrum Widget'),
'#states' => array(
'visible' => array(
':input[name="field[settings][show_palette]"]' => array('checked' => TRUE),
),
),
);
$element['show_palette_only'] = array(
'#description' => $this->t('Selectable color palette to accompany the Spectrum Widget. Separate values with a comma, and group them with square brackets. Ex: <br> ["#fff","#aaa","#f00","#00f"],<br>["#414141","#242424","#0a8db9"]'),
'#states' => [
'visible' => [
':input[name="fields[' . $this->fieldDefinition->getName() . '][settings_edit_form][settings][show_palette]"]' => ['checked' => TRUE],
],
],
];
$element['show_palette_only'] = [
'#type' => 'checkbox',
'#title' => t('Show Palette Only'),
'#title' => $this->t('Show Palette Only'),
'#default_value' => $this->getSetting('show_palette_only'),
'#description' => t('Only show thePalette in Spectrum Widget and nothing else'),
);
$element['show_buttons'] = array(
'#description' => $this->t('Only show the palette in Spectrum Widget and nothing else'),
'#states' => [
'visible' => [
':input[name="fields[' . $this->fieldDefinition->getName() . '][settings_edit_form][settings][show_palette]"]' => ['checked' => TRUE],
],
],
];
$element['show_buttons'] = [
'#type' => 'checkbox',
'#title' => t('Show Buttons'),
'#title' => $this->t('Show Buttons'),
'#default_value' => $this->getSetting('show_buttons'),
'#description' => t('Add Cancel/Confirm Button.'),
);
$element['allow_empty'] = array(
'#description' => $this->t('Add Cancel/Confirm Button.'),
];
$element['allow_empty'] = [
'#type' => 'checkbox',
'#title' => t('Allow Empty'),
'#title' => $this->t('Allow Empty'),
'#default_value' => $this->getSetting('allow_empty'),
'#description' => t('Allow empty value.'),
);
'#description' => $this->t('Allow empty value.'),
];
return $element;
}
@@ -93,7 +92,7 @@ class ColorFieldWidgetSpectrum extends WidgetBase {
* {@inheritdoc}
*/
public function settingsSummary() {
$summary = array();
$summary = [];
return $summary;
}
@@ -102,50 +101,43 @@ class ColorFieldWidgetSpectrum extends WidgetBase {
* {@inheritdoc}
*/
public function formElement(FieldItemListInterface $items, $delta, array $element, array &$form, FormStateInterface $form_state) {
// We are nesting some sub-elements inside the parent, so we need a wrapper.
// We also need to add another #title attribute at the top level for ease in
// identifying this item in error messages. We do not want to display this
// title because the actual title display is handled at a higher level by
// the Field module.
$element['#theme_wrappers'] = array('color_field_widget_spectrum');
$element = parent::formElement($items, $delta, $element, $form, $form_state);
$element['#attached']['library'][] = 'color_field/color-field-widget-spectrum';
// Set Drupal settings.
$settings = $this->getSettings();
$settings['show_alpha'] = $this->getFieldSetting('opacity');
$element['#attached']['drupalSettings']['color_field']['color_field_widget_spectrum'] = $settings;
// Prepare color.
$color = NULL;
if (isset($items[$delta]->color)) {
$color = $items[$delta]->color;
if (substr($color, 0, 1) !== '#') {
$color = '#' . $color;
// Compare with default settings make sure they are the same datatype.
$defaults = self::defaultSettings();
foreach ($settings as $key => $value) {
if (is_bool($defaults[$key])) {
$settings[$key] = boolval($value);
}
}
$element['color'] = array(
'#type' => 'textfield',
'#maxlength' => 7,
'#size' => 7,
'#required' => $element['#required'],
'#default_value' => $color,
'#attributes' => array('class' => array('js-color-field-widget-spectrum__color')),
);
// Parsing Palette data so that it works with spectrum color picker.
// This will create a multidimensional array of hex values.
if (!empty($settings['palette'])) {
// Remove any whitespace.
$settings['palette'] = str_replace(' ', '', $settings['palette']);
if ($this->getFieldSetting('opacity')) {
$element['opacity'] = array(
'#type' => 'textfield',
'#maxlength' => 4,
'#size' => 4,
'#required' => $element['#required'],
'#default_value' => isset($items[$delta]->opacity) ? $items[$delta]->opacity : NULL,
'#attributes' => array('class' => array('js-color-field-widget-spectrum__opacity', 'visually-hidden')),
);
// Parse each row first and reset the palette.
$rows = explode("\n", $settings['palette']);
$settings['palette'] = [];
foreach ($rows as $row) {
// Next explode each row into an array of values.
$settings['palette'][] = $columns = explode(',', $row);
}
}
$settings['show_alpha'] = (bool) $this->getFieldSetting('opacity');
$element['#attributes']['id'] = $element['#uid'];
$element['#attributes']['class'][] = 'js-color-field-widget-spectrum';
$element['#attached']['drupalSettings']['color_field']['color_field_widget_spectrum'][$element['#uid']] = $settings;
$element['color']['#attributes']['class'][] = 'js-color-field-widget-spectrum__color';
$element['opacity']['#attributes']['class'][] = 'js-color-field-widget-spectrum__opacity';
return $element;
}
@@ -16,4 +16,4 @@
*/
#}
<div class='color_field__swatch--{{ shape }}' style="background-color: {{ color }}; width: {{ width }}px; height: {{ height }}px;"></div>
<div class='color_field__swatch color_field__swatch--{{ shape }}' style="background-color: {{ color }}; width: {{ width }}px; height: {{ height }}px;"></div>
@@ -1,41 +0,0 @@
{#
/**
* @file
* Default theme implementation of a color box form wrapper.
*
* Available variables:
* - content: The form element to be output, usually a datelist, or datetime.
* - title: The title of the form element.
* - title_attributes: HTML attributes for the title wrapper.
* - description: Description text for the form element.
* - required: An indicator for whether the associated form element is required.
*
* @see template_preprocess()
* @see template_preprocess_color_field_widget_box()
*
* @ingroup themeable
*/
#}
{%
set title_classes = [
required ? 'js-form-required',
required ? 'form-required',
]
%}
{% if title %}
<h4{{ title_attributes.addClass(title_classes) }}>{{ title }}</h4>
{% endif %}
<div class="container-inline">
{{ color }}
{{ opacity }}
</div>
{% if errors %}
<div>
{{ errors }}
</div>
{% endif %}
{{ description }}
@@ -1,41 +0,0 @@
{#
/**
* @file
* Default theme implementation of a color box form wrapper.
*
* Available variables:
* - content: The form element to be output, usually a datelist, or datetime.
* - title: The title of the form element.
* - title_attributes: HTML attributes for the title wrapper.
* - description: Description text for the form element.
* - required: An indicator for whether the associated form element is required.
*
* @see template_preprocess()
* @see template_preprocess_color_field_widget_box()
*
* @ingroup themeable
*/
#}
{%
set title_classes = [
required ? 'js-form-required',
required ? 'form-required',
]
%}
{% if title %}
<h4{{ title_attributes.addClass(title_classes) }}>{{ title }}</h4>
{% endif %}
<div class="js-color-field-widget-spectrum">
{{ color }}
{{ opacity }}
</div>
{% if errors %}
<div>
{{ errors }}
</div>
{% endif %}
{{ description }}
@@ -0,0 +1,203 @@
<?php
namespace Drupal\Tests\color_field\Functional;
/**
* Tests color field formatters.
*
* @group color_field
*/
class ColorFieldFormatterTest extends ColorFieldFunctionalTestBase {
/**
* Test color_field_formatter_text formatter.
*/
public function testColorFieldFormatterText() {
$this->form->setComponent('field_color', [
'type' => 'color_field_widget_default',
'settings' => [
'placeholder_color' => '#ABC123',
'placeholder_opacity' => '1.0',
],
])->save();
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_text',
'weight' => 1,
'label' => 'hidden',
])->save();
// Display creation form.
$this->drupalGet('node/add/article');
$session = $this->assertSession();
$session->fieldExists("field_color[0][color]");
$session->fieldExists("field_color[0][opacity]");
$session->responseContains('placeholder="#ABC123"');
$session->responseContains('placeholder="1.0"');
$session->responseContains('Freeform Color');
$session->responseContains('Color field description');
// Test basic entry of color field.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#E70000",
'field_color[0][opacity]' => 1,
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$this->assertSession()->responseContains('#E70000 1</div>');
// Ensure alternate hex format works.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "FF8C00",
'field_color[0][opacity]' => 0.5,
];
// Render without opacity value.
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_text',
'weight' => 1,
'settings' => [
'opacity' => FALSE,
],
])->save();
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('#FF8C00</div>');
// Test RGBA Render mode.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#FFEF00",
'field_color[0][opacity]' => 0.9,
];
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_text',
'weight' => 1,
'settings' => [
'format' => 'rgb',
'opacity' => TRUE,
],
])->save();
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('RGBA(255,239,0,0.9)');
// Test RGB render mode.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#00811F",
'field_color[0][opacity]' => 0.8,
];
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_text',
'weight' => 1,
'settings' => [
'format' => 'rgb',
'opacity' => FALSE,
],
])->save();
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('RGB(0,129,31)');
}
/**
* Test color_field_formatter_swatch formatter.
*/
public function testColorFieldFormatterSwatch() {
$this->form->setComponent('field_color', [
'type' => 'color_field_widget_default',
'settings' => [
'placeholder_color' => '#ABC123',
'placeholder_opacity' => '1.0',
],
])->save();
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_swatch',
'weight' => 1,
'label' => 'hidden',
])->save();
// Test square with opacity.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#0044FF",
'field_color[0][opacity]' => 0.9,
];
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('background-color: rgba(0,68,255,0.9)');
$this->assertSession()->responseContains('color_field__swatch--square');
// Test circle without opacity.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#760089",
'field_color[0][opacity]' => 1,
];
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_swatch',
'weight' => 1,
'settings' => [
'shape' => 'circle',
'opacity' => FALSE,
],
])->save();
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('background-color: rgb(118,0,137)');
$this->assertSession()->responseContains('color_field__swatch--circle');
}
/**
* Test color_field_formatter_css formatter.
*/
public function testColorFieldFormatterCss() {
$this->form->setComponent('field_color', [
'type' => 'color_field_widget_default',
'settings' => [
'placeholder_color' => '#ABC123',
'placeholder_opacity' => '1.0',
],
])->save();
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_css',
'weight' => 1,
'label' => 'hidden',
])->save();
// Test default options.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#FFF430",
'field_color[0][opacity]' => 0.9,
];
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('body { background-color: RGBA(255,244,48,0.9) !important; }');
// Test without opacity and not important.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#FFFFFF",
'field_color[0][opacity]' => 1,
];
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_css',
'weight' => 1,
'settings' => [
'selector' => 'body',
'property' => 'background-color',
'important' => FALSE,
'opacity' => FALSE,
],
'label' => 'hidden',
])->save();
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('body { background-color: RGB(255,255,255); }');
}
}
@@ -0,0 +1,95 @@
<?php
namespace Drupal\Tests\color_field\Functional;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests color field formatters.
*
* @group color_field
*/
class ColorFieldFormatterTokenTest extends ColorFieldFunctionalTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'field',
'node',
'color_field',
'token',
];
/**
* Test color_field_formatter_css formatter.
*/
public function testTokens() {
$this->form->setComponent('field_color', [
'type' => 'color_field_widget_default',
])->save();
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#9C59D1",
'field_color[0][opacity]' => 0.95,
];
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_css',
'weight' => 1,
'settings' => [
'selector' => '.node-[node:content-type]',
'property' => 'background-color',
'important' => FALSE,
'opacity' => TRUE,
],
'label' => 'hidden',
])->save();
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('.node-article { background-color: RGBA(156,89,209,0.95); }');
// Ensure 2 fields on the same entity are both rendered properly.
FieldStorageConfig::create([
'field_name' => 'field_text_color',
'entity_type' => 'node',
'type' => 'color_field_type',
])->save();
FieldConfig::create([
'field_name' => 'field_text_color',
'label' => 'Text Color',
'entity_type' => 'node',
'bundle' => 'article',
])->save();
$this->display->setComponent('field_text_color', [
'type' => 'color_field_formatter_css',
'weight' => 1,
'settings' => [
'selector' => '.node-[node:content-type]',
'property' => 'color',
'important' => FALSE,
'opacity' => TRUE,
],
'label' => 'hidden',
])->save();
$this->form->setComponent('field_text_color', [
'type' => 'color_field_widget_default',
])->save();
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#000000",
'field_color[0][opacity]' => 0.1,
'field_text_color[0][color]' => "#000000",
'field_text_color[0][opacity]' => 1,
];
$this->drupalPostForm('node/add/article', $edit, t('Save'));
$this->assertSession()->responseContains('.node-article { background-color: RGBA(0,0,0,0.1); }');
$this->assertSession()->responseContains('.node-article { color: RGBA(0,0,0,1); }');
}
}
@@ -0,0 +1,69 @@
<?php
namespace Drupal\Tests\color_field\Functional;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\BrowserTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Provide basic setup for all color field functional tests.
*
* @group color_field
*/
abstract class ColorFieldFunctionalTestBase extends BrowserTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'field',
'node',
'color_field',
];
/**
* The Entity View Display for the article node type.
*
* @var \Drupal\Core\Entity\Entity\EntityViewDisplay
*/
protected $display;
/**
* The Entity Form Display for the article node type.
*
* @var \Drupal\Core\Entity\Entity\EntityFormDisplay
*/
protected $form;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(['type' => 'article']);
$user = $this->drupalCreateUser(['create article content', 'edit own article content']);
$this->drupalLogin($user);
$entityTypeManager = $this->container->get('entity_type.manager');
FieldStorageConfig::create([
'field_name' => 'field_color',
'entity_type' => 'node',
'type' => 'color_field_type',
])->save();
FieldConfig::create([
'field_name' => 'field_color',
'label' => 'Freeform Color',
'description' => 'Color field description',
'entity_type' => 'node',
'bundle' => 'article',
])->save();
$this->form = $entityTypeManager->getStorage('entity_form_display')
->load('node.article.default');
$this->display = $entityTypeManager->getStorage('entity_view_display')
->load('node.article.default');
}
}
@@ -0,0 +1,45 @@
<?php
namespace Drupal\Tests\color_field\Functional;
/**
* Tests color field widgets.
*
* @group color_field
*/
class ColorFieldWidgetTest extends ColorFieldFunctionalTestBase {
/**
* Test color_field_widget_html5.
*/
public function testColorFieldWidgetHtml5() {
$this->form->setComponent('field_color', [
'type' => 'color_field_widget_html5',
])->save();
$this->display->setComponent('field_color', [
'type' => 'color_field_formatter_text',
'weight' => 1,
])->save();
$session = $this->assertSession();
// Confirm field label and description are rendered.
$this->drupalGet('node/add/article');
$session->fieldExists("field_color[0][color]");
$session->fieldExists("field_color[0][opacity]");
$session->responseContains('Freeform Color');
$session->responseContains('Color field description');
// Test basic entry of color field.
$edit = [
'title[0][value]' => $this->randomMachineName(),
'field_color[0][color]' => "#E70000",
'field_color[0][opacity]' => 1,
];
$this->drupalPostForm(NULL, $edit, t('Save'));
$session->responseContains('#E70000 1</div>');
}
}
@@ -0,0 +1,260 @@
<?php
namespace Drupal\Tests\color_field\FunctionalJavascript;
use Drupal\field\Entity\FieldConfig;
use Drupal\field\Entity\FieldStorageConfig;
use Drupal\FunctionalJavascriptTests\WebDriverTestBase;
/**
* Tests for form grouping elements.
*
* @group form
*/
class ColorFieldWidgetJavascriptTests extends WebDriverTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = [
'field',
'node',
'color_field',
];
/**
* The Entity View Display for the article node type.
*
* @var \Drupal\Core\Entity\Entity\EntityViewDisplay
*/
protected $display;
/**
* The Entity Form Display for the article node type.
*
* @var \Drupal\Core\Entity\Entity\EntityFormDisplay
*/
protected $form;
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
$this->drupalCreateContentType(['type' => 'article']);
$user = $this->drupalCreateUser(['create article content', 'edit own article content']);
$this->drupalLogin($user);
$entityTypeManager = $this->container->get('entity_type.manager');
FieldStorageConfig::create([
'field_name' => 'field_color',
'entity_type' => 'node',
'type' => 'color_field_type',
])->save();
FieldConfig::create([
'field_name' => 'field_color',
'label' => 'Freeform Color',
'description' => 'Color field description',
'entity_type' => 'node',
'bundle' => 'article',
'required' => TRUE,
'default_value' => [
[
'color' => 'ffb81c',
'opacity' => 0.5,
],
],
])->save();
FieldStorageConfig::create([
'field_name' => 'field_color_repeat',
'entity_type' => 'node',
'type' => 'color_field_type',
])->save();
FieldConfig::create([
'field_name' => 'field_color_repeat',
'label' => 'Repeat Color',
'description' => 'Color repeat description',
'entity_type' => 'node',
'bundle' => 'article',
'required' => FALSE,
])->save();
$this->form = $entityTypeManager->getStorage('entity_form_display')
->load('node.article.default');
$this->display = $entityTypeManager->getStorage('entity_view_display')
->load('node.article.default');
}
/**
* Test color_field_widget_box.
*/
public function testColorFieldWidgetBox() {
$this->form
->setComponent('field_color_repeat', [
'type' => 'color_field_widget_box',
'settings' => [
'default_colors' => '#FF0000,#FFFFFF',
],
])
->setComponent('field_color', [
'type' => 'color_field_widget_box',
'settings' => [
'default_colors' => '#007749,#000000,#FFFFFF,#FFB81C,#E03C31,#001489',
],
])
->save();
$session = $this->getSession();
$web_assert = $this->assertSession();
$this->drupalGet('node/add/article');
$page = $session->getPage();
// Wait for elements to be generated.
$web_assert->waitForElementVisible('css', '#color-field-field-color_repeat button');
$boxes = $page->findAll('css', '#color-field-field-color-repeat button');
$this->assertEquals(3, count($boxes));
// Confirm that help text/label are present.
$web_assert->responseContains('Freeform Color');
$web_assert->responseContains('Color field description');
// Confirm that two fields aren't sharing settings.
$boxes = $page->findAll('css', '#color-field-field-color button');
$this->assertEquals(6, count($boxes));
/** @var \Behat\Mink\Element\NodeElement $box */
$box = $boxes[0];
$this->assertEquals('#007749', $box->getAttribute('color'));
// Only one of the fields has a default, so it is the only one that should
// have a box that is selected. This also confirms that even if the storage
// setting isn't uppercase hash prefixed hex that it still correctly selects
// the right color in the color box widget.
$active = $page->findAll('css', 'button.color_field_widget_box__square.active');
$this->assertEquals(1, count($active));
// Confirm that clicking the swatch sets the field value.
$box->click();
$field = $page->findField('field_color[0][color]');
$this->assertEquals('#007749', $field->getValue());
}
/**
* Test color_field_widget_spectrum widget.
*
* Unfortunately since the spectrum library uses clickable divs instead of
* buttons, we can't use full interaction of clicks with elements. So instead
* we just confirm that the right html has been generated and assume that the
* library tests itself.
*/
public function testColorFieldSpectrum() {
$this->form
->setComponent('field_color_repeat', [
'type' => 'color_field_widget_spectrum',
'settings' => [
'palette' => '["#0678BE","#53B0EB", "#96BC44"]',
'show_palette' => FALSE,
],
])
->setComponent('field_color', [
'type' => 'color_field_widget_spectrum',
'settings' => [
'palette' => '["#005493","#F5AA1C","#C63527","002754"]',
'show_palette' => TRUE,
],
])
->save();
// Disable alpha on second field.
FieldConfig::load('node.article.field_color_repeat')
->setSetting('opacity', 0)
->save();
$session = $this->getSession();
$web_assert = $this->assertSession();
$this->drupalGet('node/add/article');
$page = $session->getPage();
// Confirm that help text/label are present.
$web_assert->responseContains('Freeform Color');
$web_assert->responseContains('Color field description');
// Wait for elements to be generated.
$web_assert->waitForElementVisible('css', '.sp-preview');
// Confirm that two fields aren't sharing settings.
// Also confirms that custom palette is being used correctly and that the
// one field's palette isn't shown. 4 for the one palette plus one each for
// the widget and the current color value.
$boxes = $page->findAll('css', '.sp-thumb-el');
$this->assertEquals(6, count($boxes));
// Confirm that alpha slider is hidden if the field doesn't support opacity.
$alpha = $page->findAll('css', '.sp-alpha-enabled');
$this->assertEquals(1, count($alpha));
}
/**
* Test color_field_widget_grid widget.
*
* Unfortunately since the grid library ALSO uses clickable divs instead of
* buttons. We could use $session->evaluateScript() to do it but we'll
* presume it is tested internally and just test the basic integration.
*/
public function testColorFieldWidgetGrid() {
$this->form
->setComponent('field_color_repeat', [
'type' => 'color_field_widget_grid',
'settings' => [
'cell_width' => '20',
'cell_height' => '20',
'cell_margin' => '1',
'box_width' => '250',
'box_height' => '100',
'columns' => '16',
],
])
->setComponent('field_color', [
'type' => 'color_field_widget_grid',
'settings' => [
'cell_width' => '10',
'cell_height' => '10',
'cell_margin' => '1',
'box_width' => '115',
'box_height' => '20',
'columns' => '16',
],
])
->save();
$session = $this->getSession();
$web_assert = $this->assertSession();
$this->drupalGet('node/add/article');
$page = $session->getPage();
// Confirm that help text/label are present.
$web_assert->responseContains('Freeform Color');
$web_assert->responseContains('Color field description');
// Wait for elements to be generated.
$web_assert->waitForElementVisible('css', '.simpleColorDisplay');
// Confirm that two fields aren't sharing settings.
$boxes = $page->findAll('css', '.simpleColorDisplay');
$this->assertEquals(2, count($boxes));
$script = <<< HEREDOC
(function() {
fields = jQuery('.simpleColorDisplay');
return jQuery(fields[0]).width() == jQuery(fields[1]).width()
})()
HEREDOC;
$this->assertFalse($session->evaluateScript($script));
}
}
@@ -0,0 +1,113 @@
<?php
namespace Drupal\Tests\color_field\Kernel;
use Drupal\Core\Field\FieldItemListInterface;
use Drupal\Core\Field\FieldItemInterface;
use Drupal\entity_test\Entity\EntityTest;
use Drupal\field\Entity\FieldConfig;
use Drupal\Tests\field\Kernel\FieldKernelTestBase;
use Drupal\field\Entity\FieldStorageConfig;
/**
* Tests the new entity API for the color field type.
*
* @group color_field
*/
class ColorFieldTypeTest extends FieldKernelTestBase {
/**
* Modules to enable.
*
* @var array
*/
public static $modules = ['color_field'];
/**
* {@inheritdoc}
*/
protected function setUp() {
parent::setUp();
// Create a color field storage and field for validation.
FieldStorageConfig::create([
'field_name' => 'field_test',
'entity_type' => 'entity_test',
'type' => 'color_field_type',
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_test',
'bundle' => 'entity_test',
])->save();
// Create a second field with different options.
FieldStorageConfig::create([
'field_name' => 'field_hex',
'entity_type' => 'entity_test',
'type' => 'color_field_type',
'settings' => [
'format' => 'hexhex',
],
])->save();
FieldConfig::create([
'entity_type' => 'entity_test',
'field_name' => 'field_hex',
'bundle' => 'entity_test',
'settings' => [
'opacity' => FALSE,
],
])->save();
}
/**
* Tests using entity fields of the telephone field type.
*/
public function testTestItem() {
// Verify entity creation.
$entity = EntityTest::create();
$color = '#5BCEFA';
$lcolor = '5bcefa';
$opacity = 0.5;
$entity->field_test->color = $color;
$entity->field_test->opacity = $opacity;
$entity->field_hex->opacity = 5;
$entity->field_hex->color = $color;
$entity->name->value = $this->randomMachineName();
$entity->save();
// Verify entity has been created properly.
$id = $entity->id();
$entity = EntityTest::load($id);
$this->assertTrue($entity->field_test instanceof FieldItemListInterface, 'Field implements interface.');
$this->assertTrue($entity->field_test[0] instanceof FieldItemInterface, 'Field item implements interface.');
$this->assertEquals($color, $entity->field_test->color);
$this->assertEquals($opacity, $entity->field_test->opacity);
$this->assertEquals($color, $entity->field_test[0]->color);
// Verify field setting is respected.
$this->assertEquals($lcolor, $entity->field_hex->color);
$this->assertEquals('', $entity->field_hex->opacity);
// Verify changing the field value.
$new_value = '#FFFFFF';
$entity->field_test->color = $new_value;
$this->assertEquals($new_value, $entity->field_test->color);
// Read changed entity and assert changed values.
$entity->save();
$entity = EntityTest::load($id);
$this->assertEquals($new_value, $entity->field_test->color);
// Verify setting the color with one format will save as the desired format.
$new_value = 'F5A9B8';
$entity->field_test->color = $new_value;
$this->assertEquals($new_value, $entity->field_test->color);
// Test sample item generation.
$entity = EntityTest::create();
$entity->field_test->generateSampleItems();
$this->entityValidateAndSave($entity);
}
}