clean install

This commit is contained in:
matze committed 2024-12-10 15:08:16 +01:00
commit e14eb2d8fd
31193 files changed
+3555714

No files matched your search

@@ -0,0 +1,7 @@
name: farmOS UI Action
description: Provides default action links for farmOS entities.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- farm:farm_log
@@ -0,0 +1,2 @@
farm.actions:
deriver: 'Drupal\farm_ui_action\Plugin\Derivative\FarmActions'
@@ -0,0 +1,160 @@
<?php
namespace Drupal\farm_ui_action\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines farmOS action links.
*/
class FarmActions extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* The entity type bundle info.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $entityTypeBundleInfo;
/**
* Constructs a FarmActions object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle info.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, ModuleHandlerInterface $module_handler, EntityTypeBundleInfoInterface $entity_type_bundle_info) {
$this->entityTypeManager = $entity_type_manager;
$this->moduleHandler = $module_handler;
$this->entityTypeBundleInfo = $entity_type_bundle_info;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$container->get('entity_type.manager'),
$container->get('module_handler'),
$container->get('entity_type.bundle.info'),
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
// Load available entity types.
$entity_types = array_keys($this->entityTypeManager->getDefinitions());
// Define the farmOS entity types we care about.
$farm_types = [
'asset',
'log',
'plan',
];
// Iterate through the farmOS entity types.
foreach ($farm_types as $type) {
// If the entity type does not exist, skip it.
if (!in_array($type, $entity_types)) {
continue;
}
// Generate a link to [entity-type]/add.
$name = 'farm.add.' . $type;
$entity_type_label = $this->entityTypeManager->getStorage($type)->getEntityType()->getLabel();
$this->derivatives[$name] = $base_plugin_definition;
$this->derivatives[$name]['title'] = $this->t('Add :entity_type', [':entity_type' => $entity_type_label]);
$this->derivatives[$name]['route_name'] = 'entity.' . $type . '.add_page';
// Add it to entity Views, if the farm_ui_views module is enabled.
if ($this->moduleHandler->moduleExists('farm_ui_views')) {
$this->derivatives[$name]['appears_on'][] = 'view.farm_' . $type . '.page';
// If this is a log, also add it to view.farm_log.page_user.
if ($type == 'log') {
$this->derivatives[$name]['appears_on'][] = 'view.farm_log.page_user';
}
}
// Add it to farm.dashboard, if the farm_ui_dashboard module is enabled.
if ($this->moduleHandler->moduleExists('farm_ui_dashboard')) {
$this->derivatives[$name]['appears_on'][] = 'farm.dashboard';
}
// Generate a link to [entity-type]/add/[bundle].
$name = 'farm.add.' . $type . '.bundle';
$this->derivatives[$name] = $base_plugin_definition;
$this->derivatives[$name]['route_name'] = 'entity.' . $type . '.add_form';
$this->derivatives[$name]['class'] = 'Drupal\farm_ui_action\Plugin\Menu\LocalAction\AddEntity';
$this->derivatives[$name]['entity_type'] = $type;
// Add the entity_bundles cache tag so action links are recreated after
// new bundles are installed.
$this->derivatives[$name]['cache_tags'] = ['entity_bundles'];
// Add it to entity bundle Views, if the farm_ui_views module is enabled.
if ($this->moduleHandler->moduleExists('farm_ui_views')) {
$this->derivatives[$name]['appears_on'][] = 'view.farm_' . $type . '.page_type';
$this->derivatives[$name]['bundle_parameter'] = 'arg_0';
}
// Generate links to [entity-type]/add/[bundle]?asset=[id] on asset pages.
if ($type == 'log') {
$bundles = $this->entityTypeBundleInfo->getBundleInfo('log');
foreach ($bundles as $bundle => $bundle_info) {
$name = 'farm.asset.add.' . $type . '.' . $bundle;
$this->derivatives[$name] = $base_plugin_definition;
$this->derivatives[$name]['route_name'] = 'entity.' . $type . '.add_form';
$this->derivatives[$name]['class'] = 'Drupal\farm_ui_action\Plugin\Menu\LocalAction\AddEntity';
$this->derivatives[$name]['entity_type'] = $type;
$this->derivatives[$name]['bundle'] = $bundle;
$this->derivatives[$name]['appears_on'][] = 'entity.asset.canonical';
$this->derivatives[$name]['prepopulate'] = [
'asset' => [
'route_parameter' => 'asset',
],
];
$this->derivatives[$name]['cache_tags'] = ['entity_bundles'];
// Add it to the /asset/%asset/logs/%log_type View, if the
// farm_ui_views module is enabled.
if ($this->moduleHandler->moduleExists('farm_ui_views')) {
$this->derivatives[$name]['appears_on'][] = 'view.farm_log.page_asset';
}
}
}
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
}
@@ -0,0 +1,177 @@
<?php
namespace Drupal\farm_ui_action\Plugin\Menu\LocalAction;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Menu\LocalActionDefault;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\Routing\RouteProviderInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\asset\Entity\AssetInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Creates an action link to add entities.
*
* The 'entity_type' must be set in the action link configuration.
*/
class AddEntity extends LocalActionDefault {
use StringTranslationTrait;
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs an AddEntity object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Routing\RouteProviderInterface $route_provider
* The route provider to load routes by name.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, RouteProviderInterface $route_provider, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $route_provider);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('router.route_provider'),
$container->get('entity_type.manager'),
);
}
/**
* {@inheritdoc}
*/
public function getTitle(?Request $request = NULL) {
// Get the entity type.
$entity_type = $this->entityTypeManager->getDefinition($this->pluginDefinition['entity_type']);
// Get the entity type label.
$entity_type_label = $entity_type->getLabel();
// Get the bundle machine name.
$route_match = RouteMatch::createFromRequest($request);
$bundle = $this->getBundle($route_match);
// Get the bundle label.
$bundle_label = $this->entityTypeManager->getStorage($entity_type->getBundleEntityType())->load($bundle)->label();
// Build the link title.
return $this->t('Add @bundle @entity_type', ['@bundle' => $bundle_label, '@entity_type' => $entity_type_label]);
}
/**
* {@inheritdoc}
*/
public function getOptions(RouteMatchInterface $route_match) {
$options = parent::getOptions($route_match);
// Bail if there are no fields to prepopulate.
if (empty($this->pluginDefinition['prepopulate'])) {
return $options;
}
// Check if there is an asset field to prepopulate.
if (!empty($this->pluginDefinition['prepopulate']['asset'])) {
$asset_id = NULL;
// If an asset id is specified, use it.
if (!empty($this->pluginDefinition['prepopulate']['asset']['id'])) {
$asset_id = $this->pluginDefinition['prepopulate']['asset']['id'];
}
// If a route parameter is specified, use it instead.
if (!empty($this->pluginDefinition['prepopulate']['asset']['route_parameter'])) {
// Get the asset.
$asset_param = $this->pluginDefinition['prepopulate']['asset']['route_parameter'];
$asset = $route_match->getParameter($asset_param);
// If the parameter returned an entity, get its ID.
if ($asset instanceof AssetInterface) {
$asset_id = $asset->id();
}
// Else, assume the parameter is the asset ID.
else {
$asset_id = $asset;
}
}
// Continue if the asset_id was found.
if (!empty($asset_id)) {
// Build a query param to prepopulate the asset field in the log form.
$param = 'asset';
$options['query'][$param] = $asset_id;
}
}
return $options;
}
/**
* {@inheritdoc}
*/
public function getRouteParameters(RouteMatchInterface $route_match) {
// Get the entity type.
$entity_type = $this->pluginDefinition['entity_type'];
$entity_type_param = $entity_type . '_type';
// Get the bundle machine name.
$bundle = $this->getBundle($route_match);
// Set the entity_type parameter for the entity.type.add_form route.
return [
$entity_type_param => $bundle,
];
}
/**
* Get the bundle machine name.
*
* This will first look for an explicit bundle set in the plugin definition.
* If that fails, then it will look for a bundle parameter in the route.
*
* @param \Drupal\Core\Routing\RouteMatchInterface $route_match
* Route match object.
*
* @return string
* Bundle machine name.
*/
protected function getBundle(RouteMatchInterface $route_match) {
$bundle = NULL;
if (!empty($this->pluginDefinition['bundle'])) {
$bundle = $this->pluginDefinition['bundle'];
}
elseif (!empty($this->pluginDefinition['bundle_parameter'])) {
$bundle = $route_match->getParameter($this->pluginDefinition['bundle_parameter']);
}
return $bundle;
}
}
@@ -0,0 +1,7 @@
name: farmOS UI Breadcrumb
description: Provides default breadcrumbs in farmOS.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- farm:farm_ui_views
@@ -0,0 +1,7 @@
services:
farm_ui_breadcrumb.breadcrumb:
class: Drupal\farm_ui_breadcrumb\Breadcrumb\FarmBreadcrumbBuilder
arguments:
[ '@router.request_context', '@access_manager', '@router.no_access_checks', '@path_processor_manager', '@config.factory', '@title_resolver', '@current_user', '@path.current' ]
tags:
- { name: breadcrumb_builder, priority: 100 }
@@ -0,0 +1,84 @@
<?php
namespace Drupal\farm_ui_breadcrumb\Breadcrumb;
use Drupal\Core\Link;
use Drupal\Core\Routing\RouteMatchInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\system\PathBasedBreadcrumbBuilder;
/**
* Build farmOS breadcrumbs.
*/
class FarmBreadcrumbBuilder extends PathBasedBreadcrumbBuilder {
use StringTranslationTrait;
/**
* {@inheritdoc}
*/
public function applies(RouteMatchInterface $route_match) {
$routes = [
'entity.asset.canonical',
'entity.log.canonical',
'entity.plan.canonical',
'entity.user.canonical',
];
return in_array($route_match->getRouteName(), $routes);
}
/**
* {@inheritdoc}
*/
public function build(RouteMatchInterface $route_match) {
$breadcrumb = parent::build($route_match);
// Get parameters.
$parameters = $route_match->getParameters();
// Add links based on the route.
switch ($route_match->getRouteName()) {
// Asset pages.
case 'entity.asset.canonical':
/** @var \Drupal\asset\Entity\AssetInterface $asset */
$asset = $parameters->get('asset');
$breadcrumb->addCacheableDependency($asset);
$breadcrumb->addLink(Link::createFromRoute($this->t('Records'), '<front>'));
$breadcrumb->addLink(Link::createFromRoute($this->t('Assets'), 'view.farm_asset.page'));
$breadcrumb->addLink(Link::createFromRoute($asset->getBundleLabel(), 'view.farm_asset.page_type', ['arg_0' => $asset->bundle()]));
break;
// Log pages.
case 'entity.log.canonical':
/** @var \Drupal\log\Entity\LogInterface $log */
$log = $parameters->get('log');
$breadcrumb->addCacheableDependency($log);
$breadcrumb->addLink(Link::createFromRoute($this->t('Records'), '<front>'));
$breadcrumb->addLink(Link::createFromRoute($this->t('Logs'), 'view.farm_log.page'));
$breadcrumb->addLink(Link::createFromRoute($log->getBundleLabel(), 'view.farm_log.page_type', ['arg_0' => $log->bundle()]));
break;
// Plan pages.
case 'entity.plan.canonical':
/** @var \Drupal\plan\Entity\PlanInterface $plan */
$plan = $parameters->get('plan');
$breadcrumb->addCacheableDependency($plan);
$breadcrumb->addLink(Link::createFromRoute($this->t('Plans'), 'view.farm_plan.page'));
$breadcrumb->addLink(Link::createFromRoute($plan->getBundleLabel(), 'view.farm_plan.page_type', ['arg_0' => $plan->bundle()]));
break;
// User pages.
case 'entity.user.canonical':
$breadcrumb->addLink(Link::createFromRoute($this->t('People'), 'view.farm_people.page'));
break;
}
// This breadcrumb builder is based on a route parameter, and hence it
// depends on the 'route' cache context.
$breadcrumb->addCacheContexts(['route']);
return $breadcrumb;
}
}
@@ -0,0 +1,111 @@
<?php
/**
* @file
* Hooks provided by farm_ui_dashboard.
*
* This file contains no working PHP code; it exists to provide additional
* documentation for doxygen as well as to document hooks in the standard
* Drupal manner.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Defines farm dashboard panes.
*
* @return array
* Returns an array of farm dashboard pane configurations.
*/
function hook_farm_dashboard_panes() {
return [
// A pane is defined with an associative array, keyed with a unique pane
// machine name.
'my_pane' => [
// Specify a 'view' and 'view_display ID' to automatically load a View.
// This will take precedence over 'block' below.
'view' => 'my_view',
'view_display_id' => 'block_1',
// Specify a block plugin ID to automatically load a Block.
'block' => 'my_block',
// Optional arguments to pass to the view or block.
// This is useful if the view or block can be used in different contexts.
'args' => [
'arg1' => FALSE,
'arg2' => 'logs',
],
// Optionally specify a title. By default the view's title or the block's
// label will be used.
'title' => t('My pane title'),
// Optionally specify a layout region. Defaults to 'first'.
// Options are: top, first, second or bottom.
'region' => 'top',
// Optionally specify a group and weight for display sorting.
'group' => 'custom_group',
'weight' => 100,
],
];
}
/**
* Alter farm dashboard panes.
*
* @param array $panes
* An array of farm dashboard pane configurations to alter.
*/
function hook_farm_dashboard_panes_alter(array &$panes) {
// Remove all panes not provide by my_module.
foreach (array_keys($panes) as $pane) {
if (!str_contains($pane, 'my_module')) {
unset($panes[$pane]);
}
}
}
/**
* Defines farm dashboard groups.
*
* @return array
* Returns an array of farm dashboard groups keyed by layout region.
*/
function hook_farm_dashboard_groups() {
return [
// Returns an associate array keyed by the layout region.
// Options are top, first, second, or bottom.
'first' => [
// Groups are defined as a render array keyed with a unique group
// machine name.
'my_group' => [
// The type. Defaults to container.
'#type' => 'details',
// Optionally specify a title.
'#title' => t('My group title'),
// Optionally specify a weight for sorting.
'#weight' => 100,
],
],
'bottom' => [
// Define groups for the bottom layout region.
],
];
}
/**
* @} End of "addtogroup hooks".
*/
@@ -0,0 +1,9 @@
name: farmOS Dashboard
description: Provides a farmOS dashboard.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- drupal:block
- drupal:layout_discovery
- drupal:views
@@ -0,0 +1,15 @@
<?php
/**
* @file
* Install, update and uninstall functions for the farm_ui_dashboard module.
*/
/**
* Implements hook_install().
*/
function farm_ui_dashboard_install() {
// Set the front page to /dashboard.
\Drupal::configFactory()->getEditable('system.site')->set('page.front', '/dashboard')->save();
}
@@ -0,0 +1,3 @@
farm_ui_dashboard:
default_permissions:
- access farm dashboard
@@ -0,0 +1,17 @@
<?php
/**
* @file
* The farmOS Dashboard module.
*/
/**
* Implements hook_toolbar_alter().
*/
function farm_ui_dashboard_toolbar_alter(&$items) {
// Rename home item to "Dashboard".
if (!empty($items['home'])) {
$items['home']['tab']['#title'] = t('Dashboard');
}
}
@@ -0,0 +1,3 @@
access farm dashboard:
title: 'Access farmOS dashboard'
description: 'Access the farmOS dashboard'
@@ -0,0 +1,7 @@
farm.dashboard:
path: '/dashboard'
defaults:
_title: 'Dashboard'
_controller: '\Drupal\farm_ui_dashboard\Controller\DashboardController::dashboard'
requirements:
_permission: 'access farm dashboard'
@@ -0,0 +1,192 @@
<?php
namespace Drupal\farm_ui_dashboard\Controller;
use Drupal\Core\Block\BlockManagerInterface;
use Drupal\Core\Controller\ControllerBase;
use Drupal\Core\Layout\LayoutPluginManagerInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\views\Views;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Dashboard controller.
*
* @ingroup farm
*/
class DashboardController extends ControllerBase {
/**
* The layout plugin manager.
*
* @var \Drupal\Core\Layout\LayoutPluginManagerInterface
*/
protected $layoutPluginManager;
/**
* The block manager.
*
* @var \Drupal\Core\Block\BlockManagerInterface
*/
protected $blockManager;
/**
* The current user.
*
* @var \Drupal\Core\Session\AccountInterface
*/
protected $currentUser;
/**
* Class constructor.
*/
public function __construct(LayoutPluginManagerInterface $layout_plugin_manager, BlockManagerInterface $block_manager, AccountInterface $current_user) {
$this->layoutPluginManager = $layout_plugin_manager;
$this->blockManager = $block_manager;
$this->currentUser = $current_user;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('plugin.manager.core.layout'),
$container->get('plugin.manager.block'),
$container->get('current_user'),
);
}
/**
* Builds the farm dashboard page.
*
* @return array
* Render array.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
public function dashboard() {
// Start a build array.
// Ask modules for dashboard groups.
$build = $this->moduleHandler()->invokeAll('farm_dashboard_groups');
// Ask modules for dashboard panes.
$panes = $this->moduleHandler()->invokeAll('farm_dashboard_panes');
$this->moduleHandler()->alter('farm_dashboard_panes', $panes);
// Add each pane to the dashboard.
foreach ($panes as $id => $pane) {
// Set default values.
$args = [];
$output = '';
$title = '';
$region = 'first';
$group = 'default';
$weight = 0;
// Use any provided args.
if (!empty($pane['args'])) {
$args = $pane['args'];
}
// If 'view' and 'view_display_id' are provided, display the view.
if (!empty($pane['view']) && !empty($pane['view_display_id'])) {
// Load the view. Note that this
// returns a special ViewExecutable object, not a View entity.
$view = Views::getView($pane['view']);
// Skip if the view doesn't exist or access check fails.
if (empty($view) || !$view->access($pane['view_display_id'])) {
continue;
}
// Set the display so we get the correct title.
$view->setDisplay($pane['view_display_id']);
// Set the title.
$title = $view->getTitle();
// Build the views renderable output.
$output = $view->buildRenderable($pane['view_display_id'], $args);
}
// Or if a block is provided, display the block.
elseif (!empty($pane['block'])) {
// Render plugin block if is set.
$block = $this->blockManager->createInstance($pane['block'], $args);
if ($block) {
// Check block access.
$access_result = $block->access($this->currentUser);
if ($access_result == TRUE) {
// Builds renderable array of the block.
$output = $block->build();
}
}
}
// If a specific title was provided, use it.
if (!empty($pane['title'])) {
$title = $pane['title'];
}
// If a region was provided, use it.
if (!empty($pane['region'])) {
$region = $pane['region'];
}
// If a group was provided, use it.
if (!empty($pane['group'])) {
$group = $pane['group'];
}
// If a weight was provided, use it.
if (!empty($pane['weight'])) {
$weight = $pane['weight'];
}
// Create a container for the dashboard pane.
$container = [
'#type' => 'container',
'#weight' => $weight,
'#attributes' => [
'class' => ['dashboard-pane'],
],
];
// If a title is set, make it a fieldset.
if (!empty($title)) {
$container['#type'] = 'fieldset';
$container['#title'] = $title;
}
// Include output inside the container.
$container[] = $output;
// Add the container to the build array.
$build[$region][$group][$id] = $container;
}
// Get the layout.
$layoutInstance = $this->layoutPluginManager->createInstance('layout_twocol', []);
// Define the regions.
$region_names = ['top', 'first', 'second', 'bottom'];
$regions = [];
foreach ($region_names as $name) {
$regions[$name] = !empty($build[$name]) ? $build[$name] : [];
}
// Build the layout.
$render = $layoutInstance->build($regions);
return $render;
}
}
@@ -0,0 +1,130 @@
langcode: en
status: true
dependencies:
module:
- user
id: dashboard_test_view
label: dashboard_test_view
module: views
description: ''
tag: ''
base_table: users_field_data
base_field: uid
display:
default:
display_plugin: default
id: default
display_title: Master
position: 0
display_options:
access:
type: perm
options:
perm: 'access user profiles'
cache:
type: tag
options: { }
query:
type: views_query
options:
disable_sql_rewrite: false
distinct: false
replica: false
query_comment: ''
query_tags: { }
exposed_form:
type: basic
options:
submit_button: Apply
reset_button: false
reset_button_label: Reset
exposed_sorts_label: 'Sort by'
expose_sort_order: true
sort_asc_label: Asc
sort_desc_label: Desc
pager:
type: none
options:
offset: 0
style:
type: default
row:
type: fields
fields:
name:
id: name
table: users_field_data
field: name
entity_type: user
entity_field: name
label: ''
alter:
alter_text: false
make_link: false
absolute: false
trim: false
word_boundary: false
ellipsis: false
strip_tags: false
html: false
hide_empty: false
empty_zero: false
plugin_id: field
relationship: none
group_type: group
admin_label: ''
exclude: false
element_type: ''
element_class: ''
element_label_type: ''
element_label_class: ''
element_label_colon: true
element_wrapper_type: ''
element_wrapper_class: ''
element_default_classes: true
empty: ''
hide_alter_empty: true
click_sort_column: value
type: user_name
settings: { }
group_column: value
group_columns: { }
group_rows: true
delta_limit: 0
delta_offset: 0
delta_reversed: false
delta_first_last: false
multi_type: separator
separator: ', '
field_api_classes: false
filters: { }
sorts: { }
title: 'User list'
header: { }
footer: { }
empty: { }
relationships: { }
arguments: { }
display_extenders: { }
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- user.permissions
tags: { }
user_list:
display_plugin: block
id: user_list
display_title: 'Block: user list'
position: 1
display_options:
display_extenders: { }
display_description: ''
cache_metadata:
max-age: -1
contexts:
- 'languages:language_content'
- 'languages:language_interface'
- user.permissions
tags: { }
@@ -0,0 +1,7 @@
name: Farm UI Dashboard module tests
description: Support module for dashboard.
type: module
package: Testing
core_version_requirement: ^10
dependencies:
- farm:farm_ui_dashboard
@@ -0,0 +1,21 @@
<?php
/**
* @file
* The farm_ui_dashboard_test module.
*/
/**
* Implements hook_farm_dashboard_panes().
*/
function farm_ui_dashboard_test_farm_dashboard_panes() {
return [
'dashboard_block' => [
'block' => 'dashboard_test_block',
],
'dashboard_view' => [
'view' => 'dashboard_test_view',
'view_display_id' => 'user_list',
],
];
}
@@ -0,0 +1,24 @@
<?php
namespace Drupal\farm_ui_dashboard_test\Plugin\Block;
use Drupal\Core\Block\BlockBase;
/**
* Provides a dashboard test block.
*
* @Block(
* id = "dashboard_test_block",
* admin_label = @Translation("Dashboard test block")
* )
*/
class DashboardTestBlock extends BlockBase {
/**
* {@inheritdoc}
*/
public function build() {
return ['#markup' => '<span>' . $this->t('This is the dashboard test block.') . '</span>'];
}
}
@@ -0,0 +1,81 @@
<?php
namespace Drupal\Tests\farm_ui_dashboard\Functional;
use Drupal\Tests\farm_test\Functional\FarmBrowserTestBase;
/**
* Tests the farmOS dashboard functionality.
*
* @group farm
*/
class DashboardTest extends FarmBrowserTestBase {
/**
* Test user.
*
* @var \Drupal\user\Entity\User
*/
protected $user;
/**
* {@inheritdoc}
*/
protected static $modules = [
'farm_ui_dashboard',
'farm_ui_dashboard_test',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
// Create and login a user with necessary permissions.
$this->user = $this->createUser(['access farm dashboard']);
$this->drupalLogin($this->user);
}
/**
* Run all tests.
*/
public function testAll() {
$this->doTestDashboardBlock();
$this->doTestDashboardView();
}
/**
* Test that custom blocks are added to the dashboard.
*/
public function doTestDashboardBlock() {
$this->drupalGet('/dashboard');
$this->assertSession()->statusCodeEquals(200);
// Assert that the test block was added.
$this->assertSession()->pageTextContains('This is the dashboard test block.');
}
/**
* Test that custom views are added to the dashboard.
*/
public function doTestDashboardView() {
$this->drupalGet('/dashboard');
$this->assertSession()->statusCodeEquals(200);
// Assert that the test view was not added to the dashboard.
$this->assertSession()->pageTextNotContains('User list');
$this->assertSession()->pageTextNotContains($this->user->getAccountName());
$user = $this->createUser(['access farm dashboard', 'access user profiles']);
$this->drupalLogin($user);
$this->drupalGet('/dashboard');
$this->assertSession()->statusCodeEquals(200);
// Assert that the test view was added to the dashboard.
$this->assertSession()->pageTextContains('User list');
$this->assertSession()->pageTextContains($user->getAccountName());
}
}
@@ -0,0 +1,17 @@
name: farmOS UI
description: Provides default farmOS UI elements (organized into sub-modules by type).
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- farm:farm_ui_action
- farm:farm_ui_breadcrumb
- farm:farm_ui_dashboard
- farm:farm_ui_help
- farm:farm_ui_location
- farm:farm_ui_map
- farm:farm_ui_menu
- farm:farm_ui_metrics
- farm:farm_ui_theme
- farm:farm_ui_user
- farm:farm_ui_views
@@ -0,0 +1,7 @@
name: farmOS UI Help
description: Provides Help module integration for farmOS.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- drupal:help
@@ -0,0 +1,12 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_ui_location
id: locations
label: Locations
description: 'The farmOS locations map.'
behaviors:
- locations
options: { }
@@ -0,0 +1,10 @@
input#edit-save[disabled],
input#edit-save[disabled]:hover,
input#edit-reset[disabled],
input#edit-reset[disabled]:hover {
background-color: var(--gin-color-disabled);
border: 2px solid var(--gin-color-disabled) !important;
box-shadow: 0 1px 2px var(--gin-color-disabled);
pointer-events: none;
color: var(--gin-color-button-text);
}
@@ -0,0 +1,11 @@
name: farmOS UI Location
description: Provides UI for managing location assets in farmOS.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- farm:farm_entity
- farm:farm_location
- farm:farm_ui_map
- farm:farm_ui_menu
- inspire_tree:inspire_tree
@@ -0,0 +1,15 @@
<?php
/**
* @file
* Install, update and uninstall functions for the farm_ui_location module.
*/
/**
* Implements hook_install().
*/
function farm_ui_location_install() {
// Use light mode for inspire tree.
\Drupal::configFactory()->getEditable('inspire_tree.settings')->set('mode', 'light')->save();
}
@@ -0,0 +1,12 @@
locations-drag-and-drop:
version: 1.x
css:
theme:
css/locations_drag_and_drop.css: { }
js:
js/locations_drag_and_drop.js: {}
dependencies:
- core/drupal.message
- core/jquery
- inspire_tree/inspire_tree
- inspire_tree/inspire_tree_dom
@@ -0,0 +1,2 @@
farm.locations.add_asset:
deriver: Drupal\farm_ui_location\Plugin\Derivative\AddLocationAssetAction
@@ -0,0 +1,5 @@
farm.locations:
title: Locations
parent: farm.base
route_name: farm.locations
weight: 0
@@ -0,0 +1,5 @@
farm.asset.locations:
route_name: farm.asset.locations
title: 'Locations'
base_route: entity.asset.canonical
weight: 100
@@ -0,0 +1,3 @@
farm_ui_location:
default_permissions:
- access locations overview
@@ -0,0 +1,33 @@
<?php
/**
* @file
* The farmOS UI Locations module.
*/
use Drupal\Core\Routing\RouteMatchInterface;
/**
* Implements hook_help().
*/
function farm_ui_location_help($route_name, RouteMatchInterface $route_match) {
$output = '';
// Locations overview help text.
if ($route_name == 'farm.locations') {
$output .= '<p>' . t('Locations represent places of interest. They are assets, and assets can be moved to them. Logs can reference them.') . '</p>';
$output .= '<p>' . t('Locations can be organized into a hierarchy with parent relationships.') . '</p>';
}
// Child locations help text.
if ($route_name == 'farm.asset.locations') {
$output .= '<p>' . t('This page shows the sub-hierarchy of this location. It includes all location assets that list this location as their parent, as well as all of their children.') . '</p>';
}
// Drag and drop help text.
if (in_array($route_name, ['farm.locations', 'farm.asset.locations'])) {
$output .= '<p>' . t('To change the hierarchy, either click on individual assets and edit their parent, or click %toggle_button below to enable drag and drop editing on this page. The %save_button button will save changes, and %reset_button will reset them.', ['%toggle_button' => t('Toggle drag and drop'), '%save_button' => t('Save'), '%reset_button' => t('Reset')]) . '</p>';
}
return $output;
}
@@ -0,0 +1,2 @@
access locations overview:
title: 'Access locations overview'
@@ -0,0 +1,33 @@
<?php
/**
* @file
* Post update functions for farm_ui_location module.
*/
use Drupal\farm_map\Entity\MapType;
/**
* Add farmOS locations map type.
*/
function farm_ui_location_post_update_add_locations_map_type(&$sandbox = NULL) {
// Create locations map type.
$map_type = MapType::create([
'id' => 'locations',
'label' => 'Locations',
'description' => 'The farmOS locations map.',
'behaviors' => [
'location',
],
'options' => [],
'dependencies' => [
'enforced' => [
'module' => [
'farm_ui_location',
],
],
],
]);
$map_type->save();
}
@@ -0,0 +1,21 @@
farm.locations:
path: '/locations'
defaults:
_title_callback: '\Drupal\farm_ui_location\Form\LocationHierarchyForm::getTitle'
_form: '\Drupal\farm_ui_location\Form\LocationHierarchyForm'
requirements:
_permission: 'access locations overview'
farm.asset.locations:
path: '/asset/{asset}/locations'
defaults:
_title_callback: '\Drupal\farm_ui_location\Form\LocationHierarchyForm::getTitle'
_form: '\Drupal\farm_ui_location\Form\LocationHierarchyForm'
requirements:
_custom_access: '\Drupal\farm_ui_location\Form\LocationHierarchyForm::access'
_module_dependencies: 'asset'
asset: \d+
options:
parameters:
asset:
type: entity:asset
@@ -0,0 +1,94 @@
/**
* @file
* Locations drag and drop.
*/
(function ($, Drupal, settings) {
"use strict"
// @TODO drag and drop validate if exist.
// @TODO validate circular references.
Drupal.behaviors.locationsDragAndDrop = {
attach: function (context, settings) {
// Function for toggling drag and drop.
var toggleDragAndDrop = function() {
$('input#edit-save').attr('disabled', !dragAndDropEnabled)
$('input#edit-reset').attr('disabled', !dragAndDropEnabled)
domTree.config.dragAndDrop.enabled = dragAndDropEnabled
}
// Enable Inspire Tree.
var tree = new InspireTree({
data: settings.asset_tree,
})
var domTree = new InspireTreeDOM(tree, {
target: '.locations-tree',
dragAndDrop: true
})
tree.nodes().expand()
// Start with drag and drop disabled.
var dragAndDropEnabled = false
toggleDragAndDrop()
// Toggle drag and drop when the button is clicked.
$('input#edit-toggle').on('click', function(event) {
event.preventDefault()
dragAndDropEnabled = !dragAndDropEnabled
toggleDragAndDrop()
// Reattach the DOM tree to the locations tree jQuery object.
domTree.attach($('.locations-tree'));
})
// Maintain a list of hierarchy changes as items are moved.
var changes = {}
tree.on('node.drop', function(event, source, target, index) {
// Determine the new parent. If target is null, then it means that the
// child was moved to the root context, which either means the child
// will no longer have a parent, or if we are in the context of a
// specific asset's children, that asset will become the new parent.
var new_parent = (target === null) ? settings.asset_parent : target.asset_id
// Create a change record, if one doesn't already exist.
if (!changes.hasOwnProperty(source.id)) {
if (source.original_parent !== new_parent) {
changes[source.id] = {
'asset_id': source.asset_id,
'original_parent': source.original_parent,
'new_parent': new_parent,
}
}
}
// Otherwise, if a change record already exists, we will either update
// it, or delete it (if the child is changing back to its original
// parent, in which case a change is no longer necessary).
else {
if (changes[source.id].original_parent !== new_parent) {
changes[source.id].new_parent = new_parent
}
else {
delete changes[source.id]
}
}
// Save the change records as a JSON string in the hidden input field.
$('input[name=changes]').val(JSON.stringify(changes))
})
// Link to locations when drag and drop is disabled.
tree.on('node.click', function(event, node) {
event.preventDefault()
if (node.url && !dragAndDropEnabled) {
window.location.href = node.url
}
});
}
}
})(jQuery, Drupal, drupalSettings)
@@ -0,0 +1,356 @@
<?php
namespace Drupal\farm_ui_location\Form;
use Drupal\Component\Serialization\Json;
use Drupal\Core\Access\AccessResult;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Session\AccountInterface;
use Drupal\Core\Url;
use Drupal\asset\Entity\AssetInterface;
use Drupal\farm_location\AssetLocationInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Form for changing the hierarchy of location assets.
*
* @ingroup farm
*/
class LocationHierarchyForm extends FormBase {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The asset location service.
*
* @var \Drupal\farm_location\AssetLocationInterface
*/
protected $assetLocation;
/**
* Constructs a new LocationHierarchyForm.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager.
* @param \Drupal\farm_location\AssetLocationInterface $asset_location
* The asset location service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, AssetLocationInterface $asset_location) {
$this->entityTypeManager = $entity_type_manager;
$this->assetLocation = $asset_location;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity_type.manager'),
$container->get('asset.location')
);
}
/**
* {@inheritdoc}
*/
public function getFormId() {
return 'farm_ui_location_form';
}
/**
* Check access.
*
* @param \Drupal\Core\Session\AccountInterface $account
* The account to check.
* @param \Drupal\asset\Entity\AssetInterface|null $asset
* The asset to check (optional).
*
* @return \Drupal\Core\Access\AccessResultInterface
* The access result.
*/
public function access(AccountInterface $account, ?AssetInterface $asset = NULL) {
// If the asset is not a location, forbid access.
if (!$this->assetLocation->isLocation($asset)) {
return AccessResult::forbidden();
}
// If the asset does not have child locations, forbid access.
if (empty($this->getLocations($asset))) {
return AccessResult::forbidden();
}
// Allow access if the asset has child locations.
return AccessResult::allowedIf($asset->access('view', $account));
}
/**
* Generate the page title.
*
* @param \Drupal\asset\Entity\AssetInterface|null $asset
* Optionally specify the parent asset that this page is being built for.
*
* @return string
* Returns the translated page title.
*/
public function getTitle(?AssetInterface $asset = NULL) {
if (!empty($asset)) {
return $this->t('Locations in %location', ['%location' => $asset->label()]);
}
return $this->t('Locations');
}
/**
* {@inheritdoc}
*/
public function buildForm(array $form, FormStateInterface $form_state, ?AssetInterface $asset = NULL) {
// If no asset was specified, show a map of all locations.
if (is_null($asset)) {
$form['map'] = [
'#type' => 'farm_map',
'#map_type' => 'locations',
];
}
// Add a DIV for the JavaScript content.
$form['content'] = [
'#type' => 'html_tag',
'#tag' => 'div',
'#attributes' => [
'class' => [
'locations-tree',
],
],
];
// Create a hidden field to store hierarchy changes recorded client-side.
$form['changes'] = [
'#type' => 'hidden',
];
// Add buttons for toggling drag and drop, saving, and resetting.
$form['actions'] = ['#type' => 'actions'];
$form['actions']['toggle'] = [
'#type' => 'button',
'#value' => $this->t('Toggle drag and drop'),
'#attributes' => [
'class' => [
'button--secondary',
],
],
];
$form['actions']['save'] = [
'#type' => 'submit',
'#value' => $this->t('Save'),
'#attributes' => [
'class' => [
'button--primary',
],
],
];
$form['actions']['reset'] = [
'#type' => 'submit',
'#value' => $this->t('Reset'),
'#attributes' => [
'class' => [
'button--danger',
],
],
];
// Attach the location drag and drop JavaScript.
$form['#attached']['library'][] = 'farm_ui_location/locations-drag-and-drop';
$tree = [
[
'asset_id' => !empty($asset) ? $asset->id() : '',
'text' => !empty($asset) ? $asset->label() : $this->t('All locations'),
'children' => !empty($asset) ? $this->buildTree($asset) : $this->buildTree(),
'url' => !empty($asset) ? $asset->toUrl('canonical', ['absolute' => TRUE])->toString() : Url::fromRoute('farm.locations', [], ['absolute' => TRUE])->toString(),
],
];
$form['#attached']['drupalSettings']['asset_tree'] = $tree;
$form['#attached']['drupalSettings']['asset_parent'] = !empty($asset) ? $asset->id() : '';
// Return the form.
return $form;
}
/**
* Build the asset tree.
*
* @param \Drupal\asset\Entity\AssetInterface|null $asset
* Optionally specify the parent asset, to only build a sub-tree. If
* omitted, all assets will be included.
*
* @return array
* Returns the asset tree for use in Drupal JS settings.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
protected function buildTree(?AssetInterface $asset = NULL) {
$locations = $this->getLocations($asset);
$tree = [];
if ($locations) {
foreach ($locations as $location) {
$element = [
'asset_id' => $location->id(),
'text' => $location->label(),
'children' => $this->buildTree($location),
'url' => $location->toUrl('canonical', ['absolute' => TRUE])->toString(),
];
$element['original_parent'] = $asset ? $asset->id() : '';
$tree[] = $element;
}
}
return $tree;
}
/**
* Gets location assets.
*
* @param \Drupal\asset\Entity\AssetInterface|null $asset
* Optionally provide a parent asset to only retrieve its direct children.
*
* @return \Drupal\asset\Entity\AssetInterface[]
* An array of location assets.
*
* @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
* @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
*/
protected function getLocations(?AssetInterface $asset = NULL) {
// Query unarchived location assets.
$storage = $this->entityTypeManager->getStorage('asset');
$query = $storage->getQuery()
->accessCheck(TRUE)
->condition('is_location', TRUE)
->condition('status', 'archived', '!=');
// Limit to a specific parent or no parent.
if ($asset) {
$query->condition('parent', $asset->id());
}
else {
$query->condition('parent', NULL, 'IS NULL');
}
// Query and load the assets.
$asset_ids = $query->execute();
if (empty($asset_ids)) {
return [];
}
/** @var \Drupal\asset\Entity\AssetInterface[] $assets */
$assets = $storage->loadMultiple($asset_ids);
// Filter out assets that the user cannot view.
$assets = array_filter($assets, function ($asset) {
return $asset->access('view');
});
// Sort assets by name, using natural sort algorithm.
usort($assets, function ($a, $b) {
return strnatcmp($a->label(), $b->label());
});
return $assets;
}
/**
* {@inheritdoc}
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
// Only process the form if the "Save" button was clicked.
if ($form_state->getTriggeringElement()['#id'] != 'edit-save') {
return;
}
// Load hierarchy changes. If there are none, do nothing.
$changes = Json::decode($form_state->getValue('changes'));
if (empty($changes)) {
$this->messenger()->addStatus($this->t('No changes were made.'));
return;
}
// Get asset storage.
$storage = $this->entityTypeManager->getStorage('asset');
// Maintain a list of assets that need to be saved.
$save_assets = [];
// Maintain a list of assets that were not editable by the user.
$restricted_assets = [];
// Iterate through the changes.
foreach ($changes as $change) {
// Load the asset.
$asset = $storage->load($change['asset_id']);
// If the user does not have permission to update the asset, count it so
// that we can add a warning message later, and skip it.
if (!$asset->access('update')) {
$restricted_assets[] = $asset;
continue;
}
// Remove the original parent.
if (!empty($asset->get('parent'))) {
/** @var \Drupal\Core\Field\Plugin\Field\FieldType\EntityReferenceItem $parent */
foreach ($asset->get('parent') as $delta => $parent) {
$parent_id = $parent->getValue()['target_id'];
if ($change['original_parent'] == $parent_id) {
unset($asset->get('parent')[$delta]);
if (!array_key_exists($asset->id(), $save_assets)) {
$save_assets[$asset->id()] = $asset;
}
}
}
}
// Add the new parent, if applicable.
if (!empty($change['new_parent'])) {
$asset->get('parent')[] = ['target_id' => $change['new_parent']];
if (!array_key_exists($asset->id(), $save_assets)) {
$save_assets[$asset->id()] = $asset;
}
}
}
// Save assets with a revision message.
/** @var \Drupal\asset\Entity\AssetInterface[] $save_assets */
foreach ($save_assets as $asset) {
$message = $this->t('Parents removed via the Locations drag and drop editor.');
$parent_names = [];
foreach ($asset->get('parent') as $parent) {
$parent_names[] = $storage->load($parent->getValue()['target_id'])->label();
}
if (!empty($parent_names)) {
$message = $this->t('Parents changed to %parents via the Locations drag and drop editor.', ['%parents' => implode(', ', $parent_names)]);
}
$asset->setNewRevision(TRUE);
$asset->setRevisionLogMessage($message);
$asset->save();
}
// Show a summary of the results.
$message = $this->formatPlural(count($save_assets), 'Updated the parent hierarchy of %count asset.', 'Updated the parent hierarchy of %count assets.', ['%count' => count($save_assets)]);
$this->messenger()->addStatus($message);
// If any edits were restricted, show a warning.
if ($restricted_assets) {
$message = $this->formatPlural(count($restricted_assets), '%count asset could not be changed because you do not have permission.', '%count assets could not be changed because you do not have permission.', ['%count' => count($restricted_assets)]);
$this->messenger()->addWarning($message);
}
}
}
@@ -0,0 +1,76 @@
<?php
namespace Drupal\farm_ui_location\Plugin\Derivative;
use Drupal\Component\Plugin\Derivative\DeriverBase;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Plugin\Discovery\ContainerDeriverInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Defines actions to add location assets on locations page.
*/
class AddLocationAssetAction extends DeriverBase implements ContainerDeriverInterface {
use StringTranslationTrait;
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs a FarmActions object.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager) {
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, $base_plugin_id) {
return new static(
$container->get('entity_type.manager'),
);
}
/**
* {@inheritdoc}
*/
public function getDerivativeDefinitions($base_plugin_definition) {
// Get asset types that are locations by default.
$asset_storage = $this->entityTypeManager->getStorage('asset_type');
$asset_type_ids = $asset_storage->getQuery()
->accessCheck(TRUE)
->condition('status', TRUE)
->exists('third_party_settings.farm_location')
->condition('third_party_settings.farm_location.is_location', TRUE)
->execute();
// Bail if there are no asset types.
if (empty($asset_type_ids)) {
return parent::getDerivativeDefinitions($base_plugin_definition);
}
// Add links to asset/add/type for each asset type.
$asset_label = $this->entityTypeManager->getDefinition('asset')->getLabel();
foreach ($asset_storage->loadMultiple($asset_type_ids) as $asset_type_id => $asset_type) {
$this->derivatives[$asset_type_id] = $base_plugin_definition;
$this->derivatives[$asset_type_id]['title'] = $this->t('Add @bundle @entity_type', ['@bundle' => $asset_type->label(), '@entity_type' => $asset_label]);
$this->derivatives[$asset_type_id]['route_name'] = 'entity.asset.add_form';
$this->derivatives[$asset_type_id]['route_parameters'] = ['asset_type' => $asset_type_id];
$this->derivatives[$asset_type_id]['appears_on'][] = 'farm.locations';
$this->derivatives[$asset_type_id]['cache_tags'] = ['config:asset_type_list'];
}
return parent::getDerivativeDefinitions($base_plugin_definition);
}
}
@@ -0,0 +1,12 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_ui_map
module:
- asset
id: asset.map_popup
label: 'Map popup'
targetEntityType: asset
cache: true
@@ -0,0 +1,11 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_ui_map
id: asset_type_layers
label: Asset type layers
description: 'Displays asset geometries in layers by asset type.'
library: 'farm_ui_map/behavior_asset_type_layers'
settings: { }
@@ -0,0 +1,11 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_ui_map
id: locations
label: Location asset layers
description: 'Displays location asset geometries in layers by asset type.'
library: ''
settings: { }
@@ -0,0 +1,12 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_ui_map
id: asset_list
label: Asset list
description: 'The map displayed on lists of assets.'
behaviors:
- asset_type_layers
options: { }
@@ -0,0 +1,12 @@
langcode: en
status: true
dependencies:
enforced:
module:
- farm_ui_dashboard
id: dashboard
label: Dashboard
description: 'The farmOS dashboard map.'
behaviors:
- locations
options: { }
@@ -0,0 +1,13 @@
/*
Styling for iframe used within the map popup.
*/
.farm-map .ol-popup iframe {
display: block;
border: none;
width: 250px;
min-height: 125px;
}
.farm-map .ol-popup .ol-popup-content {
max-height: 300px;
}
@@ -0,0 +1,10 @@
name: farmOS UI Map
description: Provides default farmOS maps and behaviors.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- farm:asset
- farm:farm_location
- farm:farm_map
- farm:farm_ui_views
@@ -0,0 +1,14 @@
map_popup_iframe:
css:
theme:
css/map_popup_iframe.css: { }
dependencies:
- farm_map/behavior_popup
behavior_asset_type_layers:
js:
js/farmOS.map.behaviors.asset_type_layers.js: { }
dependencies:
- core/drupalSettings
- farm_ui_map/map_popup_iframe
- farm_map/farm_map
@@ -0,0 +1,15 @@
farm_ui_map.asset.map_popup.farm_asset.page_location:
route_name: view.farm_asset.page_location
title: 'View assets in this location'
appears_on:
- farm_ui_map.asset.map_popup
weight: -10
farm_ui_map.asset.map_popup.farm_log.page_asset:
route_name: view.farm_log.page_asset
route_parameters:
log_type: 'all'
title: 'View logs'
appears_on:
- farm_ui_map.asset.map_popup
weight: -5
@@ -0,0 +1,83 @@
<?php
/**
* @file
* The farmOS UI Map module.
*/
use Drupal\Core\Entity\Display\EntityViewDisplayInterface;
use Drupal\Core\Entity\EntityInterface;
/**
* Implements hook_farm_dashboard_panes().
*/
function farm_ui_map_farm_dashboard_panes() {
return [
'dashboard_map' => [
'block' => 'map_block',
'args' => [
'map_type' => 'dashboard',
],
'region' => 'top',
],
];
}
/**
* Implements hook_module_implements_alter().
*/
function farm_ui_map_module_implements_alter(&$implementations, $hook) {
// Ensure that this module's hook_views_pre_render() runs first.
if ($hook == 'views_pre_render') {
$module = 'farm_ui_map';
$group = $implementations[$module];
unset($implementations[$module]);
$implementations = array_merge([$module => $group], $implementations);
}
}
/**
* Implements hook_menu_local_actions_alter().
*/
function farm_ui_map_menu_local_actions_alter(&$local_actions) {
// Include asset.add.log.* location actions on the asset.map_popup route.
foreach ($local_actions as $id => $local_action) {
if (strpos($id, 'farm.actions:farm.asset.add.log.') === 0) {
$local_actions[$id]['appears_on'][] = 'farm_ui_map.asset.map_popup';
}
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_map_preprocess_block__farm_local_actions_block(&$variables, $block) {
if (\Drupal::routeMatch()->getRouteName() === 'farm_ui_map.asset.map_popup') {
$variables['content']['#dropbutton_type'] = 'small';
}
}
/**
* Implements hook_ENTITY_TYPE_view().
*/
function farm_ui_map_asset_view(array &$build, EntityInterface $entity, EntityViewDisplayInterface $display, $view_mode) {
/** @var \Drupal\farm_entity\Plugin\Asset\AssetType\AssetTypeInterface $entity */
// Bail if not the map_popup view mode.
if ($view_mode !== 'map_popup') {
return $build;
}
// The default view mode is used if a map_popup view mode is not provided.
// Alter the default view mode to only include common fields.
$view_mode_options = \Drupal::service('entity_display.repository')->getViewModeOptionsByBundle('asset', $entity->bundle());
if (!array_key_exists($view_mode, $view_mode_options)) {
$common_fields = ['name', 'type', 'flag', 'notes', 'location'];
$build = array_filter($build, function ($key) use ($common_fields) {
return strpos($key, '#') === 0 || in_array($key, $common_fields);
}, ARRAY_FILTER_USE_KEY);
}
return $build;
}
@@ -0,0 +1,39 @@
<?php
/**
* @file
* Post update functions for farm_ui_map module.
*/
use Drupal\farm_map\Entity\MapBehavior;
use Drupal\farm_map\Entity\MapType;
/**
* Create farmOS-map locations behavior, add it to dashboard map.
*/
function farm_ui_map_post_update_locations_behavior(&$sandbox = NULL) {
// Create locations behavior.
$behavior = MapBehavior::create([
'id' => 'locations',
'label' => 'Location asset layers',
'description' => 'Displays location asset geometries in layers by asset type.',
'library' => '',
'settings' => [],
'dependencies' => [
'enforced' => [
'module' => [
'farm_ui_map',
],
],
],
]);
$behavior->save();
// Add the locations behavior to the dashboard map type.
$dashboard = MapType::load('dashboard');
$behaviors = $dashboard->getMapBehaviors();
$behaviors[] = 'locations';
$dashboard->set('behaviors', $behaviors);
$dashboard->save();
}
@@ -0,0 +1,11 @@
farm_ui_map.asset.map_popup:
path: '/asset/{asset}/map-popup'
defaults:
_entity_view: 'asset.map_popup'
requirements:
_entity_access: asset.view
asset: \d+
options:
parameters:
asset:
type: entity:asset
@@ -0,0 +1,7 @@
services:
farm_ui_map.map_render_event_subscriber:
class: Drupal\farm_ui_map\EventSubscriber\MapRenderEventSubscriber
arguments:
[ '@entity_type.manager', '@farm_map.layer_style_loader' ]
tags:
- { name: 'event_subscriber' }
@@ -0,0 +1,144 @@
<?php
/**
* @file
* Provides Views runtime hooks for farm_ui_map.module.
*/
use Drupal\asset\Entity\AssetType;
use Drupal\views\Entity\View;
use Drupal\views\ViewExecutable;
/**
* Implements hook_views_pre_view().
*/
function farm_ui_map_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
// Alter the farm_asset_geojson View's full and centroid displays to add all
// exposed filters that are present in the farm_asset View.
if ($view->id() == 'farm_asset_geojson' && in_array($display_id, ['full', 'centroid'])) {
// Load the farm_asset View. Bail if unavailable.
$farm_asset_view = View::load('farm_asset');
if (empty($farm_asset_view)) {
return;
}
// Copy all exposed filters from the default display.
$display = $farm_asset_view->getDisplay('default');
if (!empty($display['display_options']['filters'])) {
foreach ($display['display_options']['filters'] as $field => $filter) {
$view->addHandler($display_id, 'filter', $filter['table'], $field, $filter, $filter['id']);
}
}
// If a type argument is present, add bundle-specific exposed filters.
if (!empty($args[0]) && $args[0] != 'all') {
farm_ui_views_add_bundle_handlers($view, $display_id, $args[0], 'filter');
}
}
}
/**
* Implements hook_views_pre_render().
*
* @see farm_ui_map_module_implements_alter()
*/
function farm_ui_map_views_pre_render(ViewExecutable $view) {
// Render a map attachment above views of assets.
if ($view->id() == 'farm_asset' && in_array($view->current_display, ['page', 'page_type'])) {
// Get all asset bundles.
$asset_bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo($view->getBaseEntityType()->id());
// Start array of filtered bundles.
$filtered_bundles = $asset_bundles;
// Start array of asset layers to add.
$asset_layers = [
'full' => [],
];
// Save the group labels.
$layer_group = $view->getBaseEntityType()->getCollectionLabel();
// Get exposed filters.
$exposed_filters = $view->getExposedInput();
// Add multiple asset layers to the page of all assets.
if ($view->current_display == 'page') {
// Limit to filtered asset types.
if (!empty($exposed_filters['type'])) {
$filtered_bundles = array_intersect_key($asset_bundles, array_flip($exposed_filters['type']));
}
}
// Determine if we are filtering by bundle.
// This may happen via contextual filter on the "page_type" display, or via
// the exposed "type" filter.
$bundle_filters = [];
if ($view->current_display == 'page_type' && !empty($view->args[0])) {
$bundle_filters[] = $view->args[0];
}
elseif (!empty($exposed_filters['type'])) {
foreach ($exposed_filters['type'] as $bundle) {
$bundle_filters[] = $bundle;
}
}
// Filter by bundle, if desired.
if (!empty($bundle_filters)) {
$filtered_bundles = [];
foreach ($bundle_filters as $bundle) {
$filtered_bundles[$bundle] = $asset_bundles[$bundle];
}
}
// Add a cluster layer for summarizing asset counts.
$asset_layers['cluster']['all'] = [
'label' => t('Asset counts'),
'cluster' => TRUE,
'filters' => $exposed_filters,
];
if (!empty($bundle_filters)) {
$asset_layers['cluster']['all']['asset_type'] = implode('+', $bundle_filters);
}
// Add a full asset geometry layer for each asset type.
foreach ($filtered_bundles as $bundle => $bundle_info) {
// Load the bundle entity.
$type = AssetType::load($bundle);
// Load the map layer style.
/** @var \Drupal\farm_map\Entity\LayerStyleInterface $layer_style */
$layer_style = \Drupal::service('farm_map.layer_style_loader')->load(['asset_type' => $bundle]);
if (!is_null($layer_style)) {
$color = $layer_style->get('color');
}
// Add layer for the asset type.
$asset_layers['full']['full_' . $bundle] = [
'group' => $type->getThirdPartySetting('farm_location', 'is_location', FALSE) ? t('Location assets') : $layer_group,
'label' => $bundle_info['label'],
'asset_type' => $bundle,
'filters' => $exposed_filters,
'color' => $color ?? 'orange',
'zoom' => TRUE,
];
}
// Build the map render array.
$map = [
'#type' => 'farm_map',
'#map_type' => 'asset_list',
];
$all_layers = array_merge($asset_layers['cluster'], $asset_layers['full']);
$map['#map_settings']['asset_type_layers'] = $all_layers;
// Render the map.
$view->attachment_before['asset_map'] = $map;
}
}
@@ -0,0 +1,113 @@
(function (drupalSettings) {
farmOS.map.behaviors.asset_type_layers = {
attach: function (instance) {
// Check if there are asset type layers to add.
if (instance.farmMapSettings.asset_type_layers !== undefined) {
// Add layers for each area type.
var layers = instance.farmMapSettings.asset_type_layers;
// Create any layer groups that were explicitly defined. We do this
// first to ensure that they are available to put asset type layers in.
// Skip any layers that are not a group.
Object.values(layers).reverse().forEach( layer => {
// If the layer is not a group, skip it.
if (!layer.is_group) {
return;
}
// Add the layer group.
var opts = {
title: layer.label,
}
if (!!layer.group) {
opts.group = layer.group;
}
instance.addLayer('group', opts);
});
// Add each asset type layer.
Object.values(layers).reverse().forEach( layer => {
// If the layer is a group, skip it.
if (!!layer.is_group) {
return;
}
// Determine if the layer should display full geometry or centroids.
let geomType = 'full';
let layerType = 'geojson';
if (!!layer.cluster && layer.cluster) {
geomType = 'centroid';
layerType = 'cluster';
}
// Build a url to the asset type geojson, default to all.
const assetType = layer.asset_type || 'all';
const url = new URL('assets/geojson/' + geomType + '/' + assetType, window.location.origin + drupalSettings.path.baseUrl);
// Include provided filters.
const filters = layer.filters || {};
Object.entries(filters).forEach( ([key, value]) => {
if (Array.isArray(value)) {
for (let i = 0; i < value.length; i++) {
url.searchParams.append(key + '[]', value[i]);
}
}
else {
url.searchParams.append(key, value);
}
});
// Build the layer.
var opts = {
title: layer.label,
url,
color: layer.color,
};
// Add the group if specified.
if (!!layer.group) {
opts.group = layer.group;
}
var newLayer = instance.addLayer(layerType, opts);
// If zoom is true, zoom to the layer vectors.
// Do not zoom to cluster layers.
if (layerType !== 'cluster' && layer.zoom !== undefined && layer.zoom) {
var source = newLayer.getSource();
source.on('change', function () {
instance.zoomToVectors();
});
}
});
}
// Load area details via AJAX when an area popup is displayed.
instance.popup.on('farmOS-map.popup', function (event) {
var link = event.target.element.querySelector('.ol-popup-name a');
if (link) {
var assetLink = link.getAttribute('href')
var description = event.target.element.querySelector('.ol-popup-description');
// Add loading text.
var loading = document.createTextNode('Loading asset details...');
description.appendChild(loading);
// Create an iframe linking to the map_popup view mode.
var frame = document.createElement('iframe');
frame.setAttribute('src', assetLink + '/map-popup');
frame.onload = function () {
description.removeChild(loading);
instance.popup.panIntoView();
}
description.appendChild(frame);
}
});
}
};
}(drupalSettings));
@@ -0,0 +1,132 @@
<?php
namespace Drupal\farm_ui_map\EventSubscriber;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\farm_map\Event\MapRenderEvent;
use Drupal\farm_map\LayerStyleLoaderInterface;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
/**
* An event subscriber for the MapRenderEvent.
*
* Adds the wkt and geofield behaviors to necessary maps.
*/
class MapRenderEventSubscriber implements EventSubscriberInterface {
use StringTranslationTrait;
/**
* Asset types.
*
* @var \Drupal\asset\Entity\AssetTypeInterface[]
*/
protected $assetTypes;
/**
* The layer style loader service.
*
* @var \Drupal\farm_map\layerStyleLoader
*/
protected $layerStyleLoader;
/**
* MapRenderEventSubscriber Constructor.
*
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\farm_map\LayerStyleLoaderInterface $layer_style_loader
* The layer style loader service.
*/
public function __construct(EntityTypeManagerInterface $entity_type_manager, LayerStyleLoaderInterface $layer_style_loader) {
$this->assetTypes = $entity_type_manager->getStorage('asset_type')->loadMultiple();
$this->layerStyleLoader = $layer_style_loader;
}
/**
* {@inheritdoc}
*/
public static function getSubscribedEvents() {
return [
MapRenderEvent::EVENT_NAME => 'onMapRender',
];
}
/**
* React to the MapRenderEvent.
*
* @param \Drupal\farm_map\Event\MapRenderEvent $event
* The MapRenderEvent.
*/
public function onMapRender(MapRenderEvent $event) {
// Add behaviors/settings to default and geofield maps.
if (in_array($event->getmapType()->id(), ['default', 'geofield'])) {
// Add "All locations" layers.
$event->addBehavior('asset_type_layers');
$settings[$event->getMapTargetId()]['asset_type_layers']['all_locations'] = [
'label' => $this->t('All locations'),
'filters' => [
'is_location' => 1,
],
'color' => 'grey',
'zoom' => TRUE,
];
$event->addSettings($settings);
// Prevent zooming to the "All locations" layer if WKT is provided.
if (!empty($event->element['#map_settings']['wkt'])) {
$settings[$event->getMapTargetId()]['asset_type_layers']['all_locations']['zoom'] = FALSE;
$event->addSettings($settings);
}
}
// If the "locations" behavior is added to the map, add layers for each
// location asset type.
if (in_array('locations', $event->getMapBehaviors())) {
$layers = [];
// Define common layer properties.
$group = $this->t('Locations');
$filters = [
'is_location' => 1,
];
// Add layer for all asset types are locations by default.
foreach ($this->assetTypes as $type) {
// Only add a layer if the asset type is a location by default.
if ($type->getThirdPartySetting('farm_location', 'is_location', FALSE)) {
// Load the map layer style.
/** @var \Drupal\farm_map\Entity\LayerStyleInterface $layer_style */
$layer_style = $this->layerStyleLoader->load(['asset_type' => $type->id()]);
if (!is_null($layer_style)) {
$color = $layer_style->get('color');
}
// Add layer for the asset type.
$layers[$type->id()] = [
'group' => $group,
'label' => $type->label(),
'asset_type' => $type->id(),
'filters' => $filters,
'color' => $color ?? 'orange',
'zoom' => TRUE,
];
}
}
// Add the asset_type_layers behavior.
$event->addBehavior('asset_type_layers');
// Add map specific settings.
$settings[$event->getMapTargetId()]['asset_type_layers'] = $layers;
$event->addSettings($settings);
}
}
}
@@ -0,0 +1,8 @@
name: farmOS UI Menu
description: Provides farmOS menu and toolbar overrides.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- admin_toolbar:admin_toolbar
- drupal:toolbar
@@ -0,0 +1,17 @@
<?php
/**
* @file
* Install, update and uninstall functions for the farm_ui_menu module.
*/
/**
* Implements hook_install().
*/
function farm_ui_menu_install() {
// Delete system menus.
\Drupal::configFactory()->getEditable('system.menu.footer')->delete();
\Drupal::configFactory()->getEditable('system.menu.main')->delete();
\Drupal::configFactory()->getEditable('system.menu.tools')->delete();
}
@@ -0,0 +1,9 @@
farm.base:
title: farmOS
menu_name: admin
route_name: '<nolink>'
farm.records:
title: Records
parent: farm.base
route_name: '<front>'
weight: 0
@@ -0,0 +1,3 @@
farm_ui_menu:
default_permissions:
- access toolbar
@@ -0,0 +1,97 @@
<?php
/**
* @file
* The farmOS UI Menu module.
*/
use Drupal\farm_ui_menu\Menu\DefaultSecondaryLocalTaskProvider;
use Drupal\farm_ui_menu\Render\Element\FarmAdminToolbar;
/**
* Implements hook_menu_links_discovered_alter().
*/
function farm_ui_menu_menu_links_discovered_alter(&$links) {
// Move the root system.admin menu link to the farm.base parent.
if (!empty($links['system.admin'])) {
$links['system.admin']['parent'] = 'farm.base';
$links['system.admin']['weight'] = 100;
}
// Move the farm.report menu link to the farm.base parent.
if (!empty($links['farm.report'])) {
$links['farm.report']['parent'] = 'farm.base';
$links['farm.report']['weight'] = 90;
}
// Move the farm.quick:farm.quick menu link to the farm.base parent.
if (!empty($links['farm.quick:farm.quick'])) {
$links['farm.quick:farm.quick']['parent'] = 'farm.base';
}
// Move the farm.setup menu link to the farm.base parent.
if (!empty($links['farm.setup'])) {
$links['farm.setup']['parent'] = 'farm.base';
$links['farm.setup']['weight'] = 95;
// Add a setup menu item for taxonomy.
if (\Drupal::service('module_handler')->moduleExists('taxonomy')) {
$links['farm.setup.taxonomy'] = [
'title' => t('Taxonomy'),
'description' => t('Manage the taxonomy terms used for flagging, categorization and organization of farmOS records.'),
'parent' => 'farm.setup',
'route_name' => 'entity.taxonomy_vocabulary.collection',
'weight' => 50,
];
}
}
}
/**
* Implements hook_toolbar_alter().
*/
function farm_ui_menu_toolbar_alter(&$items) {
// Override the toolbar tray prerender method to use farm.base root.
$items['administration']['tray']['toolbar_administration']['#pre_render'] = [[FarmAdminToolbar::class, 'preRenderTray']];
}
/**
* Implements hook_entity_type_build().
*/
function farm_ui_menu_entity_type_build(array &$entity_types) {
// Override the default local task provider to use secondary tasks.
$target_entity_types = ['asset', 'data_stream', 'log', 'plan', 'taxonomy_term'];
foreach ($target_entity_types as $entity_type) {
if (isset($entity_types[$entity_type])) {
$handlers = $entity_types[$entity_type]->getHandlerClasses();
$handlers['local_task_provider']['default'] = DefaultSecondaryLocalTaskProvider::class;
$entity_types[$entity_type]->setHandlerClass('local_task_provider', $handlers['local_task_provider']);
}
}
}
/**
* Implements hook_local_tasks_alter().
*/
function farm_ui_menu_local_tasks_alter(&$local_tasks) {
// Disable Drupal core revisions local tasks.
$target_entity_types = ['asset', 'data_stream', 'log', 'plan', 'taxonomy_term'];
foreach ($target_entity_types as $entity_type) {
unset($local_tasks['entity.version_history:' . $entity_type . '.version_history']);
}
// Remove local tasks provided by core taxonomy module.
$taxonomy_term_tasks = [
'entity.taxonomy_term.canonical',
'entity.taxonomy_term.edit_form',
'entity.taxonomy_term.delete_form',
];
foreach ($taxonomy_term_tasks as $task_id) {
unset($local_tasks[$task_id]);
}
}
@@ -0,0 +1,123 @@
<?php
namespace Drupal\farm_ui_menu\Menu;
use Drupal\Core\Entity\EntityHandlerInterface;
use Drupal\Core\Entity\EntityTypeInterface;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Drupal\Core\StringTranslation\TranslationInterface;
use Drupal\entity\Menu\EntityLocalTaskProviderInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides default entity tasks as secondary local tasks.
*/
class DefaultSecondaryLocalTaskProvider implements EntityLocalTaskProviderInterface, EntityHandlerInterface {
use StringTranslationTrait;
/**
* The entity type.
*
* @var \Drupal\Core\Entity\EntityTypeInterface
*/
protected $entityType;
/**
* Constructs a DefaultEntityLocalTaskProvider object.
*
* @param \Drupal\Core\Entity\EntityTypeInterface $entity_type
* The entity type.
* @param \Drupal\Core\StringTranslation\TranslationInterface $string_translation
* The string translation.
*/
public function __construct(EntityTypeInterface $entity_type, TranslationInterface $string_translation) {
$this->entityType = $entity_type;
$this->setStringTranslation($string_translation);
}
/**
* {@inheritdoc}
*/
public static function createInstance(ContainerInterface $container, EntityTypeInterface $entity_type) {
return new static($entity_type, $container->get('string_translation'));
}
/**
* {@inheritdoc}
*/
public function buildLocalTasks(EntityTypeInterface $entity_type) {
// Convert templates labels for task IDs.
// Note: delete-form was intentionally omitted, to match core. See #1834002.
$link_templates = [];
foreach (['canonical', 'edit-form', 'duplicate-form', 'version-history'] as $rel) {
if ($entity_type->hasLinkTemplate($rel)) {
$link_templates[] = str_replace('-', '_', $rel);
}
}
// Build local tasks.
// The entity type must provide a canonical template and at least one
// additional template to continue.
$tasks = [];
if (in_array('canonical', $link_templates) && count($link_templates) > 1) {
// Build the parent route and ID for secondary tabs.
$entity_type_id = $entity_type->id();
$parent_route = "entity.$entity_type_id.canonical";
$parent = "entity.entity_tasks:$parent_route";
$titles = [
'canonical' => $this->t('View'),
'edit_form' => $this->t('Edit'),
'duplicate_form' => $this->t('Duplicate'),
'version_history' => $this->t('Revisions'),
];
// Build local tasks for each template.
$weight = 0;
foreach ($link_templates as $rel) {
$route_name = "entity.$entity_type_id.$rel";
// Add a base and secondary task for canonical templates.
if ($rel == 'canonical') {
// Primary task with special class to use the bundle label.
$tasks[$route_name] = [
'class' => EntityTypeLabelLocalTask::class,
'options' => [
'entity_type' => $entity_type_id,
],
'title' => $entity_type->getLabel(),
'route_name' => $route_name,
'base_route' => $route_name,
'weight' => $weight,
];
// Secondary task for the "View" tab.
$tasks["entity.$entity_type_id.canonical.secondary"] = [
'title' => $this->t('View'),
'route_name' => $route_name,
'parent_id' => $parent,
'weight' => $weight,
];
}
// Add secondary tabs for all other templates.
else {
$tasks[$route_name] = [
'title' => $titles[$rel],
'route_name' => $route_name,
'parent_id' => $parent,
'weight' => $weight,
];
}
$weight += 10;
}
}
return $tasks;
}
}
@@ -0,0 +1,92 @@
<?php
namespace Drupal\farm_ui_menu\Menu;
use Drupal\Core\Entity\EntityInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Menu\LocalTaskDefault;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Drupal\Core\Routing\RouteMatch;
use Drupal\Core\StringTranslation\StringTranslationTrait;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpFoundation\Request;
/**
* Builds a local task with the entity type or bundle label.
*/
class EntityTypeLabelLocalTask extends LocalTaskDefault implements ContainerFactoryPluginInterface {
use StringTranslationTrait;
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* Constructs an AddEntity object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
);
}
/**
* {@inheritdoc}
*/
public function getTitle(?Request $request = NULL) {
// Bail if no entity type option is provided.
$entity_type = $this->pluginDefinition['options']['entity_type'] ?? NULL;
if (!$entity_type) {
return $this->t('View');
}
// Get the entity from the route match.
$route_match = RouteMatch::createFromRequest($request);
$entity = $route_match->getParameter($entity_type);
// Assume the parameter is the entity ID if not the entity object.
if (!$entity instanceof EntityInterface) {
$entity = $this->entityTypeManager->getStorage($entity_type)->load($entity);
}
// Default to "View" if no entity is loaded.
if (!$entity instanceof EntityInterface) {
return $this->t('View');
}
// For entity types with bundles, return the bundle label.
$entity->bundle();
if ($bundle_type = $entity->getEntityType()->getBundleEntityType()) {
return $this->entityTypeManager->getStorage($bundle_type)->load($entity->bundle())->label();
}
// Otherwise return the entity type label.
return $entity->getEntityType()->getLabel();
}
}
@@ -0,0 +1,51 @@
<?php
namespace Drupal\farm_ui_menu\Render\Element;
use Drupal\Core\Menu\MenuTreeParameters;
use Drupal\Core\Security\TrustedCallbackInterface;
/**
* Provides a preRenderTray() method for the toolbar that uses farm.base.
*
* @package Drupal\farm_ui_menu\Render\Element
*/
class FarmAdminToolbar implements TrustedCallbackInterface {
/**
* {@inheritdoc}
*/
public static function trustedCallbacks() {
return ['preRenderTray'];
}
/**
* Renders the farmOS toolbar's administration tray.
*
* This is a clone of AdminToolbar::preRenderTray() method, which sets the
* menu root to farm.base instead of system.admin.
*
* @param array $build
* A renderable array.
*
* @return array
* The updated renderable array.
*
* @see \Drupal\admin_toolbar\Render\Element\AdminToolbar::preRenderTray()
*/
public static function preRenderTray(array $build) {
$menu_tree = \Drupal::service('toolbar.menu_tree');
$parameters = new MenuTreeParameters();
$parameters->setRoot('farm.base')->excludeRoot()->setMaxDepth(4)->onlyEnabledLinks();
$tree = $menu_tree->load(NULL, $parameters);
$manipulators = [
['callable' => 'menu.default_tree_manipulators:checkAccess'],
['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
['callable' => 'toolbar_tools_menu_navigation_links'],
];
$tree = $menu_tree->transform($tree, $manipulators);
$build['administration_menu'] = $menu_tree->build($tree);
return $build;
}
}
@@ -0,0 +1,103 @@
<?php
namespace Drupal\Tests\farm_ui_menu\Kernel;
use Drupal\KernelTests\KernelTestBase;
use Drupal\farm_ui_menu\Menu\EntityTypeLabelLocalTask;
/**
* Tests farmOS secondary task links.
*
* @group farm
*/
class FarmSecondaryTaskTest extends KernelTestBase {
/**
* {@inheritdoc}
*/
protected $profile = 'farm';
/**
* {@inheritdoc}
*/
protected static $modules = [
'asset',
'data_stream',
'entity',
'farm_entity',
'farm_ui_menu',
'log',
'plan',
'state_machine',
'system',
'taxonomy',
'text',
'user',
];
/**
* {@inheritdoc}
*/
protected function setUp(): void {
parent::setUp();
$this->installEntitySchema('asset');
$this->installEntitySchema('data_stream');
$this->installEntitySchema('log');
$this->installEntitySchema('plan');
$this->installEntitySchema('taxonomy_term');
$this->installEntitySchema('user');
$this->installEntitySchema('user_role');
$this->installConfig([
'system',
]);
}
/**
* Test farmOS fields defined in hook_entity_base_field_info().
*/
public function testSecondaryTaskDefinitions() {
/** @var \Drupal\Core\Menu\LocalTaskManagerInterface $local_task_manager */
$local_task_manager = \Drupal::service('plugin.manager.menu.local_task');
$definitions = $local_task_manager->getDefinitions();
$entity_types_revisions = [
'asset' => TRUE,
'data_stream' => FALSE,
'log' => TRUE,
'plan' => TRUE,
'taxonomy_term' => FALSE,
];
foreach ($entity_types_revisions as $entity_type_id => $supports_revision) {
// Build the expected parent ID.
$parent_id = "entity.entity_tasks:entity.$entity_type_id.canonical";
// Assert correct primary canonical task.
$this->assertIsArray($definitions[$parent_id]);
$this->assertEquals("entity.$entity_type_id.canonical", $definitions[$parent_id]['route_name']);
$this->assertEquals(EntityTypeLabelLocalTask::class, $definitions[$parent_id]['class']);
// Assert correct secondary default task.
$secondary_id = "entity.entity_tasks:entity.$entity_type_id.canonical.secondary";
$this->assertIsArray($definitions[$secondary_id]);
$this->assertEquals("entity.$entity_type_id.canonical", $definitions[$secondary_id]['route_name']);
$this->assertEquals($parent_id, $definitions[$secondary_id]['parent_id']);
// Assert correct secondary edit task.
$edit_id = "entity.entity_tasks:entity.$entity_type_id.edit_form";
$this->assertIsArray($definitions[$edit_id]);
$this->assertEquals("entity.$entity_type_id.edit_form", $definitions[$edit_id]['route_name']);
$this->assertEquals($parent_id, $definitions[$edit_id]['parent_id']);
// Assert correct secondary revision task.
if ($supports_revision) {
$revision_id = "entity.entity_tasks:entity.$entity_type_id.version_history";
$this->assertIsArray($definitions[$revision_id]);
$this->assertEquals("entity.$entity_type_id.version_history", $definitions[$revision_id]['route_name']);
$this->assertEquals($parent_id, $definitions[$revision_id]['parent_id']);
}
}
}
}
@@ -0,0 +1,10 @@
.metrics-container ul {
display: flex;
flex-flow: row wrap;
gap: .25em .5em;
}
.metrics-container a.metric {
flex-basis: 20%;
white-space: nowrap;
}
@@ -0,0 +1,7 @@
name: farmOS UI Metrics
description: Adds a dashboard pane with high-level farm metrics.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- farm:farm_ui_dashboard
@@ -0,0 +1,4 @@
metrics_block:
css:
theme:
css/metrics_block.css: { }
@@ -0,0 +1,19 @@
<?php
/**
* @file
* The farmOS UI Metrics module.
*/
/**
* Implements hook_farm_dashboard_panes().
*/
function farm_ui_metrics_farm_dashboard_panes() {
return [
'metrics' => [
'block' => 'farm_metrics_block',
'title' => t('Metrics'),
'region' => 'second',
],
];
}
@@ -0,0 +1,152 @@
<?php
namespace Drupal\farm_ui_metrics\Plugin\Block;
use Drupal\Core\Block\BlockBase;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\EntityTypeManagerInterface;
use Drupal\Core\Link;
use Drupal\Core\Plugin\ContainerFactoryPluginInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Provides a 'Metrics' block.
*
* @Block(
* id = "farm_metrics_block",
* admin_label = @Translation("Farm Metrics")
* )
*/
class FarmMetricsBlock extends BlockBase implements ContainerFactoryPluginInterface {
/**
* The entity type manager service.
*
* @var \Drupal\Core\Entity\EntityTypeManagerInterface
*/
protected $entityTypeManager;
/**
* The bundle info service.
*
* @var \Drupal\Core\Entity\EntityTypeBundleInfoInterface
*/
protected $bundleInfo;
/**
* Constructs a \Drupal\Component\Plugin\PluginBase object.
*
* @param array $configuration
* A configuration array containing information about the plugin instance.
* @param string $plugin_id
* The plugin_id for the plugin instance.
* @param mixed $plugin_definition
* The plugin implementation definition.
* @param \Drupal\Core\Entity\EntityTypeManagerInterface $entity_type_manager
* The entity type manager service.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $bundle_info
* The bundle info service.
*/
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, EntityTypeBundleInfoInterface $bundle_info) {
parent::__construct($configuration, $plugin_id, $plugin_definition);
$this->entityTypeManager = $entity_type_manager;
$this->bundleInfo = $bundle_info;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
return new static(
$configuration,
$plugin_id,
$plugin_definition,
$container->get('entity_type.manager'),
$container->get('entity_type.bundle.info')
);
}
/**
* {@inheritdoc}
*/
public function build() {
$output = [];
// Create a list of asset metrics.
$assets_label = $this->entityTypeManager->getStorage('asset')->getEntityType()->getCollectionLabel() . ' (' . $this->t('active') . ')';
$output['asset'] = [
'#theme' => 'item_list',
'#title' => Link::createFromRoute($assets_label, 'view.farm_asset.page')->toRenderable(),
'#items' => $this->getEntityMetrics('asset'),
'#empty' => $this->t('No assets found.'),
'#wrapper_attributes' => [
'class' => ['assets', 'metrics-container'],
],
'#cache' => [
'tags' => [
'asset_list',
'config:asset_type_list',
],
],
];
// Create a list of log metrics.
$logs_label = $this->entityTypeManager->getStorage('log')->getEntityType()->getCollectionLabel();
$output['log'] = [
'#theme' => 'item_list',
'#title' => Link::createFromRoute($logs_label, 'view.farm_log.page')->toRenderable(),
'#items' => $this->getEntityMetrics('log'),
'#empty' => $this->t('No logs found.'),
'#wrapper_attributes' => [
'class' => ['logs', 'metrics-container'],
],
'#cache' => [
'tags' => [
'log_list',
'config:log_type_list',
],
],
];
// Attach CSS.
$output['#attached']['library'][] = 'farm_ui_metrics/metrics_block';
// Return the output.
return $output;
}
/**
* Gather metrics for rendering in the block.
*
* @param string $entity_type
* The entity type machine name.
*
* @return array
* Returns an array of metric information.
*/
protected function getEntityMetrics($entity_type) {
$metrics = [];
// Load bundles.
$bundles = $this->bundleInfo->getBundleInfo($entity_type);
// Count records by type.
foreach ($bundles as $bundle => $bundle_info) {
$query = $this->entityTypeManager->getStorage($entity_type)->getAggregateQuery()
->accessCheck(TRUE)
->condition('type', $bundle);
// Only include active assets.
if ($entity_type == 'asset') {
$query->condition('status', 'active');
}
$count = $query->count()->execute();
$route_name = "view.farm_$entity_type.page_type";
$metrics[] = Link::createFromRoute($bundle_info['label'] . ': ' . $count, $route_name, ['arg_0' => $bundle], ['attributes' => ['class' => ['metric']]])->toRenderable();
}
return $metrics;
}
}
@@ -0,0 +1,8 @@
# Schema for form display third party settings.
core.entity_form_display.*.*.*.third_party.farm_ui_theme:
type: mapping
label: 'Farm Theme Settings'
mapping:
use_field_group:
type: boolean
label: 'Use field group'
@@ -0,0 +1,31 @@
/*
Styling for the asset map_popup view mode page.
*/
/* Remove the page background color and body top padding. */
body.path-asset {
--gin-toolbar-y-offset: 0;
background: unset !important;
}
/* Remove extra space on the left. */
.toolbar-tray-open:not(.toolbar-vertical) .layout-container {
margin: 0 !important;
}
/* Remove extra space from the bottom. */
.layout-container .page-content {
margin-bottom: 0;
}
/* Remove background and top/bottom padding from header */
.region-sticky {
background: unset !important;
padding: 0 !important;
}
/* Make dropbutton items align to the left. */
.dropbutton .dropbutton__items {
left: 0 !important;
right: auto !important;
}
@@ -0,0 +1,37 @@
/*
Improve styling of comments. This includes the comment on
the entity and comment reply page.
*/
article.comment {
background: var(--gin-bg-layer);
border: 1px solid var(--gin-border-color-layer);
border-radius: var(--gin-border-m);
padding: var(--space-m);
margin-top: var(--space-m);
margin-bottom: var(--space-m);
}
article.comment p {
margin: 0 0 var(--space-xs);
}
article.comment p.comment__submitted {
font-size: var(--gin-font-size-s);
color: var(--gin-color-text-light);
}
article.comment ul.links.inline {
margin-inline: 0;
}
article.comment ul.links.inline li:first-child {
padding: 0;
}
/* Decrease size of comments when rendered on entity page. */
section.comment-wrapper {
padding: 0 var(--space-m);
}
section.comment-wrapper article.comment {
padding: 0 0 0 var(--space-s);
margin: 0 0 var(--space-s);
border: none;
border-radius: 0;
border-left: 5px solid var(--gin-border-color-secondary);
}
@@ -0,0 +1,16 @@
/* Decrease spacing in gin node edit form. */
.block-system-main-block > form.gin-node-edit-form {
padding: var(--gin-spacing-m);
}
.block-system-main-block > form.gin-node-edit-form .form-type--vertical-tabs,
.block-system-main-block > form.gin-node-edit-form .vertical-tabs {
margin-top: 0;
}
/* Decrease width of vertical tabs in node edit form. */
form .layout-node-form .vertical-tabs .vertical-tabs__menu {
width: 10em;
}
form .layout-node-form .vertical-tabs .vertical-tabs__items.vertical-tabs__panes {
margin-left: 10em;
}
@@ -0,0 +1,47 @@
/* Add a gap between layout regions. */
.layout--twocol {
--dashboard-spacing: var(--gin-spacing-s);
gap: var(--dashboard-spacing);
}
/* Use flexbox within each region. */
.layout--twocol .layout__region,
.layout--twocol .layout__region {
flex-basis: 100%;
display: flex;
flex-direction: column;
gap: var(--dashboard-spacing);
}
/* Split first and second regions to two columns on large screens. */
@media (min-width: 48em) {
.layout--twocol .layout__region--first,
.layout--twocol .layout__region--second {
flex-basis: 50%;
max-width: calc(50% - var(--dashboard-spacing)*.5);
}
}
/* Style dashboard fieldsets similar to gin-layer-wrapper. */
.layout__region > fieldset.dashboard-pane {
margin: 0;
padding-top: var(--gin-spacing-m);
background: var(--gin-bg-layer);
border: 1px solid var(--gin-border-color-layer);
box-shadow: var(--gin-shadow-l1);
border-radius: var(--gin-border-l);
}
/* Reduce spacing within dashboard fieldsets. */
.layout__region > fieldset.dashboard-pane .fieldset__label {
padding: 0 var(--gin-spacing-m);
}
.layout__region > fieldset.dashboard-pane .fieldset__wrapper {
margin: 0 var(--gin-spacing-m) var(--gin-spacing-m) var(--gin-spacing-m);
}
/* Increase fieldset font. */
.layout__region > fieldset.dashboard-pane .fieldset__label {
font-size: var(--gin-font-size-l);
font-weight: var(--gin-font-weight-bold);
}
@@ -0,0 +1,43 @@
/**
* @file
* Styling for farmOS flags.
*/
/*
* Default style for flags.
*
* Based on the Claro + Gin button--small.
*/
.flag {
display: inline-block;
margin: 0.25rem 0;
padding: .3rem .5rem;
text-align: center;
text-decoration: none;
color: var(--gin-color-button-text);
border: 2px solid var(--gin-color-primary);
border-radius: 12px;
background-color: var(--gin-color-primary);
font-size: .79rem;
font-weight: 700;
line-height: 1rem;
-webkit-appearance: none;
-webkit-font-smoothing: antialiased;
}
.flag.flag--monitor {
background-color: var(--gin-color-primary);
border-color: var(--gin-color-primary);
}
.flag.flag--priority {
background-color: var(--gin-color-danger);
border-color: var(--gin-color-danger);
}
.flag.flag--review {
background-color: var(--gin-color-warning);
border-color: var(--gin-color-warning);
}
/* Hide the "Flags" label from views table rows. */
td.views-field-flag-value .field__label {
display: none;
}
@@ -0,0 +1,11 @@
/**
* @file
* Styling for farmOS footer.
*/
.block-farm-powered-by-block {
margin-top: 45px;
padding: 30px 0;
border-top: 1px solid var(--gin-border-color);
text-align: center;
}
@@ -0,0 +1,3 @@
.help .block-help-block p:not(:last-child) {
margin-bottom: var(--gin-spacing-xs);
}
@@ -0,0 +1,6 @@
div.field--name-image.field--type-image div.field__items {
display: flex;
flex-wrap: wrap;
align-content: center;
gap: var(--gin-spacing-m);
}
@@ -0,0 +1,10 @@
/* Add some vertical padding to layout regions. */
.layout--twocol .layout__region {
margin-bottom: 1em;
}
/* Hide geometry field label in asset and log page top region. */
body.path-asset .layout__region--top .field--name-geometry .field__label,
body.path-log .layout__region--top .field--name-geometry .field__label {
display: none;
}
@@ -0,0 +1,32 @@
/* Set farmOS-map accent color to match Gin. */
.farm-map {
--farmos-map-accent-color: var(--gin-color-primary);
border-radius: var(--gin-border-s);
}
/* Move map buttons to the top when focused. Prevents surrounding control
buttons from covering up the :focus box-shadow. A position is required. */
.farm-map button:focus {
position: relative;
z-index: 1000;
}
/* Override the geocoder input to work with Gin :focus bos-shadow. */
.farm-map input#gcd-input-query {
height: 1.75em;
top: 0.5em;
box-shadow: 0 0 0 2px var(--gin-bg-layer), 0 0 0 4px var(--gin-color-focus);
-webkit-box-shadow: 0 0 0 2px var(--gin-bg-layer), 0 0 0 4px var(--gin-color-focus);
}
/* Adjust map ui elements background colors for the Gin theme dark mode. */
.gin--dark-mode .farm-map .ol-control,
.gin--dark-mode .farm-map .ol-scale-line {
background-color: rgba(var(--gin-bg-app-rgb), .25);
}
.gin--dark-mode .farm-map .ol-control:hover {
background-color: rgba(var(--gin-bg-app-rgb), .6);
}
.gin--dark-mode .farm-map .ol-control button {
background-color: rgba(var(--gin-bg-app-rgb), .8);
}
@@ -0,0 +1,13 @@
/* Collapse secondary tabs. */
@media(max-width: 48em) {
/* Display inactive secondary tabs when expanded. */
.tabs--secondary.is-open .tabs__tab:not(.is-active) {
display: flex !important;
}
/* Hide inactive secondary tabs. */
.tabs--secondary .tabs__tab:not(.is-active) {
display: none !important;
}
}
@@ -0,0 +1,5 @@
form.quick-form .inline-container {
display: flex;
flex-wrap: wrap;
column-gap: 2em;
}
@@ -0,0 +1,16 @@
/* Decrease the horizontal margin on medium to large screens. Gin uses xxl. */
@media (min-width: 48em) {
.toolbar-tray-open:not(.toolbar-vertical) .layout-container,
body:not(.toolbar-tray-open) .layout-container {
margin-left: var(--gin-spacing-m) !important;
margin-right: var(--gin-spacing-m) !important;
}
}
/*
Override gin style that moves user toolbar icon to the right.
With our narrower margins this overflows and adds a horizontal scroll bar.
*/
.toolbar-id--toolbar-icon-user {
margin-right: 0 !important;
}
@@ -0,0 +1,58 @@
/**
* @file
* Styling for farmOS toolbar.
*/
/* Add padding to the wrapper around the logo. */
.toolbar .toolbar-bar #toolbar-item-administration-tray .toolbar-logo {
padding: .5em !important;
}
/* Logo size and spacing. */
.toolbar .toolbar-bar #toolbar-item-administration-tray .toolbar-logo img.toolbar-icon-home {
max-width: 100px;
margin: 20px auto;
}
/* Locations icon. */
.toolbar .toolbar-bar .toolbar-menu-administration .toolbar-icon-farm-locations::before {
-webkit-mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' cx='12' cy='12' r='10'%3e%3c/circle%3e%3cline fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' x1='2' y1='12' x2='22' y2='12'%3e%3c/line%3e%3cpath fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' d='M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z'%3e%3c/path%3e%3c/svg%3e");
mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3ccircle fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' cx='12' cy='12' r='10'%3e%3c/circle%3e%3cline fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' x1='2' y1='12' x2='22' y2='12'%3e%3c/line%3e%3cpath fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' d='M12 2a15.3 15.3 0 0 1 4 10 15.3 15.3 0 0 1-4 10 15.3 15.3 0 0 1-4-10 15.3 15.3 0 0 1 4-10z'%3e%3c/path%3e%3c/svg%3e");
}
/* Plans icon. */
.toolbar .toolbar-bar .toolbar-menu-administration .toolbar-icon-views-viewviews-farm-plan-page::before {
-webkit-mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='none' d='M4 19.5C4 18.837 4.26339 18.2011 4.73223 17.7322C5.20107 17.2634 5.83696 17 6.5 17H20' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M4 14.5C4 13.837 4.26339 13.2011 4.73223 12.7322C5.20107 12.2634 5.83696 12 6.5 12H20' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M6.5 2H20V22H6.5C5.83696 22 5.20107 21.7366 4.73223 21.2678C4.26339 20.7989 4 20.163 4 19.5V4.5C4 3.83696 4.26339 3.20107 4.73223 2.73223C5.20107 2.26339 5.83696 2 6.5 2V2Z' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e");
mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='none' d='M4 19.5C4 18.837 4.26339 18.2011 4.73223 17.7322C5.20107 17.2634 5.83696 17 6.5 17H20' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M4 14.5C4 13.837 4.26339 13.2011 4.73223 12.7322C5.20107 12.2634 5.83696 12 6.5 12H20' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M6.5 2H20V22H6.5C5.83696 22 5.20107 21.7366 4.73223 21.2678C4.26339 20.7989 4 20.163 4 19.5V4.5C4 3.83696 4.26339 3.20107 4.73223 2.73223C5.20107 2.26339 5.83696 2 6.5 2V2Z' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e");
}
/* Records icon. */
.toolbar .toolbar-bar .toolbar-menu-administration .toolbar-icon-farm-records::before {
-webkit-mask-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='8' y1='6' x2='21' y2='6'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='8' y1='12' x2='21' y2='12'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='8' y1='18' x2='21' y2='18'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='3' y1='6' x2='3.01' y2='6'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='3' y1='12' x2='3.01' y2='12'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='3' y1='18' x2='3.01' y2='18'%3e%3c/line%3e%3c/svg%3e");
mask-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='8' y1='6' x2='21' y2='6'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='8' y1='12' x2='21' y2='12'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='8' y1='18' x2='21' y2='18'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='3' y1='6' x2='3.01' y2='6'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='3' y1='12' x2='3.01' y2='12'%3e%3c/line%3e%3cline fill='none' stroke='currentColor' stroke-width='3' stroke-linecap='round' stroke-linejoin='round' x1='3' y1='18' x2='3.01' y2='18'%3e%3c/line%3e%3c/svg%3e");
}
/* People icon. */
.toolbar .toolbar-bar .toolbar-menu-administration .toolbar-icon-farm-people::before {
-webkit-mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='none' fill-rule='evenodd' clip-rule='evenodd' d='M12 12.5C15.0376 12.5 17.5 10.0376 17.5 7C17.5 3.96243 15.0376 1.5 12 1.5C8.96243 1.5 6.5 3.96243 6.5 7C6.5 10.0376 8.96243 12.5 12 12.5Z' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M1.5 22V21C1.5 17.5 7.59563 16 12 16C16.4044 16 22.5 17.5 22.5 21V22' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M22.5 22C22.5 22 16.1052 22.5 12 22.5C7.89485 22.5 1.5 22 1.5 22' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e");
mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='none' fill-rule='evenodd' clip-rule='evenodd' d='M12 12.5C15.0376 12.5 17.5 10.0376 17.5 7C17.5 3.96243 15.0376 1.5 12 1.5C8.96243 1.5 6.5 3.96243 6.5 7C6.5 10.0376 8.96243 12.5 12 12.5Z' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M1.5 22V21C1.5 17.5 7.59563 16 12 16C16.4044 16 22.5 17.5 22.5 21V22' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M22.5 22C22.5 22 16.1052 22.5 12 22.5C7.89485 22.5 1.5 22 1.5 22' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e");
}
/* Reports icon. */
.toolbar .toolbar-bar .toolbar-menu-administration .toolbar-icon-farm-report::before {
-webkit-mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='none' d='M5.75 14.5V21.4913C5.75104 21.7589 5.55139 22.0092 5.218 22.1581C4.17743 22.6201 2.82257 22.6201 1.782 22.1581C1.44861 22.0092 1.24896 21.7589 1.25 21.4913V14.5' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M5.75 14.5C5.75 13.6716 4.74264 13 3.5 13C2.25736 13 1.25 13.6716 1.25 14.5' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M14.25 3V20.985C14.251 21.3863 14.0514 21.7616 13.718 21.985C12.6774 22.6778 11.3226 22.6778 10.282 21.985C9.94861 21.7616 9.74896 21.3863 9.75 20.985V3' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M14.25 3C14.25 2.17157 13.2426 1.5 12 1.5C10.7574 1.5 9.75 2.17157 9.75 3' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M22.75 7.5C22.75 8.08579 22.75 9 22.75 9M18.25 7.5C18.25 14.7471 18.25 21.0573 18.25 21.0573C18.249 21.4395 18.4486 21.797 18.782 22.0097C19.8226 22.6696 21.1774 22.6696 22.218 22.0097C22.5514 21.797 22.751 21.4395 22.75 21.0573C22.75 21.0573 22.75 17.7945 22.75 12.5' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M22.75 7.5C22.75 6.67157 21.7426 6 20.5 6C19.2574 6 18.25 6.67157 18.25 7.5' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e");
mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='none' d='M5.75 14.5V21.4913C5.75104 21.7589 5.55139 22.0092 5.218 22.1581C4.17743 22.6201 2.82257 22.6201 1.782 22.1581C1.44861 22.0092 1.24896 21.7589 1.25 21.4913V14.5' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M5.75 14.5C5.75 13.6716 4.74264 13 3.5 13C2.25736 13 1.25 13.6716 1.25 14.5' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M14.25 3V20.985C14.251 21.3863 14.0514 21.7616 13.718 21.985C12.6774 22.6778 11.3226 22.6778 10.282 21.985C9.94861 21.7616 9.74896 21.3863 9.75 20.985V3' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M14.25 3C14.25 2.17157 13.2426 1.5 12 1.5C10.7574 1.5 9.75 2.17157 9.75 3' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M22.75 7.5C22.75 8.08579 22.75 9 22.75 9M18.25 7.5C18.25 14.7471 18.25 21.0573 18.25 21.0573C18.249 21.4395 18.4486 21.797 18.782 22.0097C19.8226 22.6696 21.1774 22.6696 22.218 22.0097C22.5514 21.797 22.751 21.4395 22.75 21.0573C22.75 21.0573 22.75 17.7945 22.75 12.5' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M22.75 7.5C22.75 6.67157 21.7426 6 20.5 6C19.2574 6 18.25 6.67157 18.25 7.5' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e");
}
/* Quick icon. */
.toolbar .toolbar-bar .toolbar-menu-administration .toolbar-icon-farm-quickfarm-quick::before {
-webkit-mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='none' fill-rule='evenodd' clip-rule='evenodd' d='M13.045 14.136L9.33301 14.667L9.86301 10.954L19.409 1.40804C20.2877 0.529352 21.7123 0.529352 22.591 1.40804C23.4697 2.28672 23.4697 3.71135 22.591 4.59004L13.045 14.136Z' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M18.75 14.25V21.75C18.75 22.5784 18.0784 23.25 17.25 23.25H2.25C1.42157 23.25 0.75 22.5784 0.75 21.75V6.75C0.75 5.92157 1.42157 5.25 2.25 5.25H9.75' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e");
mask-image: url("data:image/svg+xml,%3csvg viewBox='0 0 24 24' xmlns='http://www.w3.org/2000/svg'%3e%3cpath fill='none' fill-rule='evenodd' clip-rule='evenodd' d='M13.045 14.136L9.33301 14.667L9.86301 10.954L19.409 1.40804C20.2877 0.529352 21.7123 0.529352 22.591 1.40804C23.4697 2.28672 23.4697 3.71135 22.591 4.59004L13.045 14.136Z' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3cpath fill='none' d='M18.75 14.25V21.75C18.75 22.5784 18.0784 23.25 17.25 23.25H2.25C1.42157 23.25 0.75 22.5784 0.75 21.75V6.75C0.75 5.92157 1.42157 5.25 2.25 5.25H9.75' stroke='black' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round'/%3e%3c/svg%3e");
}
/* Administration icon. */
.toolbar .toolbar-bar .toolbar-menu-administration .toolbar-icon-system-admin::before,
.toolbar .toolbar-bar .toolbar-menu-administration .toolbar-icon-farm-setup::before {
-webkit-mask-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3e%3ccircle fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' cx='12' cy='12' r='3'/%3e%3cpath fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' d='M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-2 2 2 2 0 01-2-2v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83 0 2 2 0 010-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 01-2-2 2 2 0 012-2h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 010-2.83 2 2 0 012.83 0l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 012-2 2 2 0 012 2v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 0 2 2 0 010 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 012 2 2 2 0 01-2 2h-.09a1.65 1.65 0 00-1.51 1z'/%3e%3c/svg%3e");
mask-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'%3e%3ccircle fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' cx='12' cy='12' r='3'/%3e%3cpath fill='none' stroke='currentColor' stroke-width='2.25' stroke-linecap='round' stroke-linejoin='round' d='M19.4 15a1.65 1.65 0 00.33 1.82l.06.06a2 2 0 010 2.83 2 2 0 01-2.83 0l-.06-.06a1.65 1.65 0 00-1.82-.33 1.65 1.65 0 00-1 1.51V21a2 2 0 01-2 2 2 2 0 01-2-2v-.09A1.65 1.65 0 009 19.4a1.65 1.65 0 00-1.82.33l-.06.06a2 2 0 01-2.83 0 2 2 0 010-2.83l.06-.06a1.65 1.65 0 00.33-1.82 1.65 1.65 0 00-1.51-1H3a2 2 0 01-2-2 2 2 0 012-2h.09A1.65 1.65 0 004.6 9a1.65 1.65 0 00-.33-1.82l-.06-.06a2 2 0 010-2.83 2 2 0 012.83 0l.06.06a1.65 1.65 0 001.82.33H9a1.65 1.65 0 001-1.51V3a2 2 0 012-2 2 2 0 012 2v.09a1.65 1.65 0 001 1.51 1.65 1.65 0 001.82-.33l.06-.06a2 2 0 012.83 0 2 2 0 010 2.83l-.06.06a1.65 1.65 0 00-.33 1.82V9a1.65 1.65 0 001.51 1H21a2 2 0 012 2 2 2 0 01-2 2h-.09a1.65 1.65 0 00-1.51 1z'/%3e%3c/svg%3e");
}
@@ -0,0 +1,68 @@
/* Add spacing below views attachments like the map. */
.view .view-filters,
.view .attachment.attachment-before {
margin-bottom: var(--gin-spacing-s);
}
/* Decrease space after exposed filter form. */
.view .view-filters form.views-exposed-form {
margin-bottom: var(--gin-spacing-s);
}
/* Decrease padding within the view-content wrapper. */
.view .view-content.gin-layer-wrapper {
padding: var(--gin-spacing-xs);
}
/* Do not wrap text within views table cells. */
.view table.views-table th,
.view table.views-table td {
max-width: 15em;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
/*
Decrease size of elements in views exposed form.
This is inspired by the claro/gin form-element--extrasmall but does not make
elements quite as small. Specifically a min-height of 2.5 instead of 1.5.
*/
.view form.views-exposed-form .form-element {
font-size: var(--gin-font-size-s);
line-height: 1.5;
border-radius: var(--gin-border-s);
min-height: 2.5rem;
}
/* Styling for text and date elements in exposed form. */
.view form.views-exposed-form .form-element--type-text,
.view form.views-exposed-form .form-element--type-date {
padding: var(--gin-spacing-xxs) var(--gin-spacing-xs);
max-width: 15rem;
}
/* Styling for select elements in exposed form. */
.view form.views-exposed-form .form-element--type-select,
.view form.views-exposed-form .form-element--type-select-multiple {
padding: var(--gin-spacing-xxs) var(--gin-spacing-xs);
min-width: 3.5rem;
}
.view form.views-exposed-form .form-element--type-select {
background-size: 1.75rem 0.4375rem;
padding-right: calc(1.5rem - 1px);
}
/* Decrease height of views bulk form action. */
.view form.views-form div[data-drupal-selector='edit-header'] > div.form-wrapper {
padding: 0 0 0 var(--gin-spacing-xs);
}
/* Specify gin variables for collapsible filter styles. */
div.view-filters details > summary {
padding: var(--gin-spacing-m);
font-weight: var(--gin-font-weight-semibold);
}
div.view-filters details > div {
margin: 0 0 0 var(--gin-spacing-s);
}
@@ -0,0 +1,91 @@
<?php
/**
* @file
* Hooks provided by farm_ui_theme.
*
* This file contains no working PHP code; it exists to provide additional
* documentation for doxygen as well as to document hooks in the standard
* Drupal manner.
*/
/**
* @addtogroup hooks
* @{
*/
/**
* Add entity form field groups.
*
* @param string $entity_type
* The entity type.
* @param string $bundle
* The bundle.
*/
function hook_farm_ui_theme_field_groups(string $entity_type, string $bundle) {
if ($entity_type == 'asset' && $bundle == 'animal') {
return [
'custom' => [
'location' => 'main',
'title' => t('Custom'),
'weight' => 50,
],
];
}
return [];
}
/**
* Specify the field groups to place entity fields in.
*
* @param string $entity_type
* The entity type.
* @param string $bundle
* The bundle.
*
* @return string[]
* An array keyed by field ID mapping to field group.
*/
function hook_farm_ui_theme_field_group_items(string $entity_type, string $bundle) {
if ($entity_type == 'asset' && $bundle == 'animal') {
return [
'nickname' => 'bundle',
'sex' => 'bundle',
];
}
return [];
}
/**
* Specify the regions that asset, log, and plan content items should be in.
*
* @param string $entity_type
* The entity type ('asset', 'log', or 'plan').
*
* @return array
* An array of item name arrays, keyed by region name ('top', 'first',
* 'second', 'bottom'). For example:
* [
* 'top' => [],
* 'first' => [],
* 'second' => [
* 'status',
* 'type',
* ],
* 'bottom' => [],
* ];
*/
function hook_farm_ui_theme_region_items(string $entity_type) {
if ($entity_type == 'log') {
return [
'second' => [
'is_movement',
],
];
}
return [];
}
/**
* @} End of "addtogroup hooks".
*/
@@ -0,0 +1,8 @@
name: farmOS UI Theme
description: Install Gin theme and provide overrides for farmOS.
type: module
package: farmOS UI
core_version_requirement: ^10
dependencies:
- drupal:block
- drupal:layout_discovery
@@ -0,0 +1,88 @@
<?php
/**
* @file
* Install, update and uninstall functions for the farm_ui_theme module.
*/
use Drupal\block\Entity\Block;
/**
* Implements hook_install().
*/
function farm_ui_theme_install() {
// Install the Gin theme and make it the default.
\Drupal::service('theme_installer')->install(['gin']);
\Drupal::configFactory()->getEditable('system.theme')->set('default', 'gin')->save();
// Load Gin settings.
$gin_settings = \Drupal::configFactory()->getEditable('gin.settings');
// Use vertical toolbar.
$gin_settings->set('classic_toolbar', 'vertical');
// Use green/orange color palette.
$gin_settings->set('preset_accent_color', 'green');
$gin_settings->set('preset_focus_color', 'orange');
// Use farmOS logo and favicon.
$path = \Drupal::service('extension.list.module')->getPath('farm_ui_theme');
$gin_settings->set('logo.use_default', FALSE);
$gin_settings->set('logo.path', $path . '/logo.png');
$gin_settings->set('favicon.use_default', FALSE);
$gin_settings->set('favicon.path', $path . '/favicon.ico');
// Users can override Gin settings.
$gin_settings->set('show_user_theme_settings', TRUE);
// Save Gin settings.
$gin_settings->save();
// Create the "Powered by farmOS" block.
// This must be done in hook_install() instead of config/install because Gin
// needs to be installed first.
$values = [
'id' => 'farm_powered',
'plugin' => 'farm_powered_by_block',
'theme' => 'gin',
'region' => 'content',
'weight' => 1000,
'settings' => [
'id' => 'farm_powered_by_block',
'label' => t('Powered by farmOS'),
'provider' => 'farm_ui_theme',
'label_display' => '0',
],
'visibility' => [],
'dependencies' => [
'enforced' => [
'module' => [
'farm_ui_theme',
],
],
],
];
Block::create($values)->save();
}
/**
* Update Gin theme logo settings.
*/
function farm_ui_theme_update_9000(&$sandbox) {
$gin_settings = \Drupal::configFactory()->getEditable('gin.settings');
$gin_settings->set('logo.use_default', $gin_settings->get('icon_default'));
$gin_settings->clear('icon_default');
$gin_settings->set('logo.path', $gin_settings->get('icon_path'));
$gin_settings->clear('icon_path');
$gin_settings->save();
}
/**
* Allow users to override Gin settings.
*/
function farm_ui_theme_update_9001(&$sandbox) {
$gin_settings = \Drupal::configFactory()->getEditable('gin.settings');
$gin_settings->set('show_user_theme_settings', TRUE);
$gin_settings->save();
}
@@ -0,0 +1,64 @@
asset_map_popup:
css:
theme:
css/asset_map_popup.css: { }
comment:
css:
theme:
css/comment.css: { }
content_form:
css:
theme:
css/content-form.css: { }
dashboard:
css:
theme:
css/dashboard.css: { }
flag:
css:
theme:
css/flag.css: { }
footer:
css:
theme:
css/footer.css: { }
help:
css:
theme:
css/help.css: { }
image:
css:
theme:
css/image.css: { }
layout:
css:
theme:
css/layout.css: { }
map:
css:
theme:
css/map.css: { }
dependencies:
- farm_map/farm_map
menu_local_task:
css:
theme:
css/menu-local-task.css: { }
quick:
css:
theme:
css/quick.css: { }
regions:
css:
theme:
css/regions.css: { }
toolbar:
css:
theme:
css/toolbar.css: { }
js:
js/toolbar.js: { weight: -50 }
views:
css:
theme:
css/views.css: { }
@@ -0,0 +1,392 @@
<?php
/**
* @file
* The farmOS UI Theme module.
*/
use Drupal\Core\Block\BlockPluginInterface;
use Drupal\Core\Entity\Display\EntityFormDisplayInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\farm_ui_theme\Form\AssetForm;
use Drupal\farm_ui_theme\Form\LogForm;
use Drupal\farm_ui_theme\Form\PlanForm;
use Drupal\farm_ui_theme\Form\TaxonomyTermForm;
/**
* Implements hook_theme().
*/
function farm_ui_theme_theme($existing, $type, $theme, $path) {
return [
'html__asset__map_popup' => [
'base hook' => 'html',
],
'menu_local_tasks__farm' => [
'base hook' => 'menu_local_tasks',
],
'menu_local_task__secondary' => [
'base hook' => 'menu_local_task',
],
'page__asset__map_popup' => [
'base hook' => 'page',
],
// Implement the node edit form theme hook.
// See https://www.drupal.org/project/gin/issues/3342164
'node_edit_form' => [
'render element' => 'form',
],
];
}
/**
* Implements hook_theme_registry_alter().
*/
function farm_ui_theme_theme_registry_alter(&$theme_registry) {
$theme_registry['comment']['path'] = \Drupal::service('extension.list.module')->getPath('farm_ui_theme') . '/templates';
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function farm_ui_theme_theme_suggestions_menu_local_task(array $variables) {
// Add suggestions for primary and secondary task levels.
$suggestions = [];
if (isset($variables['element']['#level'])) {
$suggestions[] = 'menu_local_task__' . $variables['element']['#level'];
}
return $suggestions;
}
/**
* Implements hook_theme_suggestions_HOOK().
*/
function farm_ui_theme_theme_suggestions_menu_local_tasks(array $variables) {
return ['menu_local_tasks__farm'];
}
/**
* Implements hook_entity_form_display_alter().
*/
function farm_ui_theme_entity_form_display_alter(EntityFormDisplayInterface $form_display, array $context) {
// Only alter farm entity types.
$entity_types = ['asset', 'log', 'plan', 'taxonomy_term'];
if (!in_array($context['entity_type'], $entity_types)) {
return;
}
// Ask modules for a list of field group items.
$field_map = \Drupal::moduleHandler()->invokeAll(
'farm_ui_theme_field_group_items',
[$context['entity_type'], $context['bundle']],
);
// Apply the field group mapping if not already specified on the form display.
foreach ($field_map as $field_id => $field_group) {
if (($renderer = $form_display->getRenderer($field_id)) && !$renderer->getThirdPartySetting('farm_ui_theme', 'field_group', FALSE)) {
$renderer->setThirdPartySetting('farm_ui_theme', 'field_group', $field_group);
}
}
}
/**
* Implements hook_farm_ui_theme_field_group_items().
*/
function farm_ui_theme_farm_ui_theme_field_group_items(string $entity_type, string $bundle) {
// Define base fields for asset, log, and plans on behalf of core modules.
$fields = [
'name' => 'default',
'status' => 'meta',
'flag' => 'meta',
'file' => 'file',
'image' => 'file',
'revision' => 'revision',
'revision_log_message' => 'revision',
];
switch ($entity_type) {
case 'asset':
$fields['owner'] = 'meta';
$fields['parent'] = 'parent';
$fields['intrinsic_geometry'] = 'location';
$fields['is_location'] = 'location';
$fields['is_fixed'] = 'location';
$fields['id_tag'] = 'id_tag';
break;
case 'log':
$fields['timestamp'] = 'default';
$fields['category'] = 'meta';
$fields['owner'] = 'meta';
$fields['asset'] = 'asset';
$fields['geometry'] = 'location';
$fields['location'] = 'location';
$fields['is_movement'] = 'location';
$fields['quantity'] = 'quantity';
break;
case 'plan':
break;
case 'taxonomy_term':
$fields['external_uri'] = 'reference';
break;
default:
$fields = [];
}
return $fields;
}
/**
* Implements hook_gin_content_form_routes().
*/
function farm_ui_theme_gin_content_form_routes() {
$routes = [];
$entity_types = ['asset', 'log', 'plan', 'taxonomy_term'];
foreach ($entity_types as $entity_type) {
$routes[] = "entity.$entity_type.add_form";
$routes[] = "entity.$entity_type.edit_form";
}
return $routes;
}
/**
* Implements hook_entity_type_build().
*/
function farm_ui_theme_entity_type_build(array &$entity_types) {
// Override the default add and edit form class.
$target_entity_types = [
'asset' => AssetForm::class,
'log' => LogForm::class,
'plan' => PlanForm::class,
'taxonomy_term' => TaxonomyTermForm::class,
];
foreach ($target_entity_types as $entity_type => $form_class) {
if (isset($entity_types[$entity_type])) {
$entity_types[$entity_type]->setFormClass('default', $form_class);
$entity_types[$entity_type]->setFormClass('add', $form_class);
$entity_types[$entity_type]->setFormClass('edit', $form_class);
}
}
}
/**
* Implements hook_element_info_alter().
*/
function farm_ui_theme_element_info_alter(array &$info) {
if (isset($info['farm_map'])) {
$info['farm_map']['#attached']['library'][] = 'farm_ui_theme/map';
}
}
/**
* Implements hook_form_BASE_FORM_ID_alter().
*/
function farm_ui_theme_form_quick_form_alter(&$form, FormStateInterface $form_state, $form_id) {
$form['#attached']['library'][] = 'farm_ui_theme/quick';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_block(&$variables) {
if ($variables['plugin_id'] == 'help_block') {
$variables['#attached']['library'][] = 'farm_ui_theme/help';
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_field(&$variables) {
if ($variables['field_type'] == 'comment') {
$variables['attributes']['class'][] = 'gin-layer-wrapper';
}
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_toolbar(&$variables) {
$variables['#attached']['library'][] = 'farm_ui_theme/toolbar';
}
/**
* Implements hook_block_view_BASE_BLOCK_ID_alter().
*/
function farm_ui_theme_block_view_farm_powered_by_block_alter(array &$build, BlockPluginInterface $block) {
$build['#attached']['library'][] = 'farm_ui_theme/footer';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_field__flag(array &$variables) {
$variables['#attached']['library'][] = 'farm_ui_theme/flag';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_field__image(array &$variables) {
$variables['#attached']['library'][] = 'farm_ui_theme/image';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_asset__full(&$variables) {
farm_ui_theme_build_stacked_twocol_layout($variables, 'asset');
$variables['#attached']['library'][] = 'farm_ui_theme/layout';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_log__full(&$variables) {
farm_ui_theme_build_stacked_twocol_layout($variables, 'log');
$variables['#attached']['library'][] = 'farm_ui_theme/layout';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_page(&$variables) {
$variables['#attached']['library'][] = 'farm_ui_theme/regions';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_page__dashboard(&$variables) {
$variables['#attached']['library'][] = 'farm_ui_theme/dashboard';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_plan__full(&$variables) {
farm_ui_theme_build_stacked_twocol_layout($variables, 'plan');
$variables['#attached']['library'][] = 'farm_ui_theme/layout';
}
/**
* Implements hook_preprocess_HOOK().
*/
function farm_ui_theme_preprocess_views_view(&$variables) {
$variables['#attached']['library'][] = 'farm_ui_theme/views';
}
/**
* Splits content into a stacked two-column layout.
*
* @param array $variables
* A $variables array that contains a 'content' item, which will be replaced
* by a stacked two-column layout.
* @param string $entity_type
* The entity type.
*/
function farm_ui_theme_build_stacked_twocol_layout(array &$variables, string $entity_type) {
// Ask modules for a list of region items.
$region_items = \Drupal::moduleHandler()->invokeAll('farm_ui_theme_region_items', [$entity_type]);
// Split the content items into regions.
$regions = [];
foreach ($variables['content'] as $index => $item) {
$region = 'first';
foreach ($region_items as $region_name => $items) {
if (in_array($index, $items)) {
$region = $region_name;
break;
}
}
$regions[$region][$index] = $item;
}
// Build the layout.
/** @var \Drupal\Core\Layout\LayoutInterface $layoutInstance */
$layout = \Drupal::service('plugin.manager.core.layout')->createInstance('layout_twocol', []);
$variables['content'] = $layout->build($regions);
}
/**
* Implements hook_farm_ui_theme_region_items().
*/
function farm_ui_theme_farm_ui_theme_region_items(string $entity_type) {
// Define common asset, log, and plan region items on behalf of core modules.
switch ($entity_type) {
case 'asset':
return [
'top' => [
'geometry',
],
'first' => [],
'second' => [
'inventory',
'is_location',
'is_fixed',
'location',
'owner',
'status',
'type',
],
'bottom' => [
'api',
'image',
'file',
],
];
case 'log':
return [
'top' => [
'geometry',
],
'first' => [],
'second' => [
'is_movement',
'owner',
'status',
'type',
],
'bottom' => [
'image',
'file',
],
];
case 'plan':
return [
'top' => [],
'first' => [],
'second' => [
'status',
'type',
],
'bottom' => [
'image',
'file',
],
];
default:
return [];
}
}
/**
* Implements hook_farm_update_exclude_config().
*/
function farm_ui_theme_farm_update_exclude_config() {
// Exclude config that we have overridden in hook_install() or the
// farm_ui_theme.overrider service.
return [
'block.block.gin_local_actions',
'block.block.gin_content',
];
}
@@ -0,0 +1,5 @@
services:
farm_ui_theme.overrider:
class: Drupal\farm_ui_theme\Config\FarmUiThemeConfigOverride
tags:
- {name: config.factory.override, priority: 5}
Binary file not shown.

After

Width:  |  Height:  |  Size: 938 B

@@ -0,0 +1,8 @@
(function () {
// Open the Gin toolbar by default.
var itemName = 'Drupal.gin.toolbarExpanded';
if (localStorage.getItem(itemName) === null) {
localStorage.setItem(itemName, 'true');
}
}());
Binary file not shown.

After

Width:  |  Height:  |  Size: 2.0 KiB

@@ -0,0 +1,52 @@
<?php
namespace Drupal\farm_ui_theme\Config;
use Drupal\Core\Cache\CacheableMetadata;
use Drupal\Core\Config\ConfigFactoryOverrideInterface;
use Drupal\Core\Config\StorageInterface;
/**
* Config overrides from the farmOS UI Theme module.
*/
class FarmUiThemeConfigOverride implements ConfigFactoryOverrideInterface {
/**
* {@inheritdoc}
*/
public function loadOverrides($names) {
$overrides = [];
// Override the block.block.gin_local_actions config to use our class.
$name = 'block.block.gin_local_actions';
if (in_array($name, $names)) {
$overrides[$name]['plugin'] = 'farm_local_actions_block';
$overrides[$name]['settings']['id'] = 'farm_local_actions_block';
$overrides[$name]['settings']['provider'] = 'farm_ui_theme';
}
return $overrides;
}
/**
* {@inheritdoc}
*/
public function getCacheSuffix() {
return 'FarmUiThemeConfigOverride';
}
/**
* {@inheritdoc}
*/
public function getCacheableMetadata($name) {
return new CacheableMetadata();
}
/**
* {@inheritdoc}
*/
public function createConfigObject($name, $collection = StorageInterface::DEFAULT_COLLECTION) {
return NULL;
}
}
@@ -0,0 +1,28 @@
<?php
namespace Drupal\farm_ui_theme\Form;
/**
* Asset form for gin content form.
*/
class AssetForm extends GinContentFormBase {
/**
* {@inheritdoc}
*/
protected function getFieldGroups() {
return parent::getFieldGroups() + [
'parent' => [
'location' => 'main',
'title' => $this->t('Parents'),
'weight' => 40,
],
'id_tag' => [
'location' => 'main',
'title' => $this->t('ID Tags'),
'weight' => 100,
],
];
}
}
@@ -0,0 +1,287 @@
<?php
namespace Drupal\farm_ui_theme\Form;
use Drupal\Component\Datetime\TimeInterface;
use Drupal\Core\Datetime\DateFormatterInterface;
use Drupal\Core\Entity\ContentEntityForm;
use Drupal\Core\Entity\EntityChangedInterface;
use Drupal\Core\Entity\EntityRepositoryInterface;
use Drupal\Core\Entity\EntityTypeBundleInfoInterface;
use Drupal\Core\Entity\RevisionLogInterface;
use Drupal\Core\Extension\ModuleHandlerInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\RenderCallbackInterface;
use Drupal\user\EntityOwnerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
/**
* Entity form for gin content form styling.
*/
class GinContentFormBase extends ContentEntityForm implements RenderCallbackInterface {
/**
* The date formatter service.
*
* @var \Drupal\Core\Datetime\DateFormatterInterface
*/
protected $dateFormatter;
/**
* The module handler.
*
* @var \Drupal\Core\Extension\ModuleHandlerInterface
*/
protected $moduleHandler;
/**
* Constructs a ContentEntityForm object.
*
* @param \Drupal\Core\Entity\EntityRepositoryInterface $entity_repository
* The entity repository service.
* @param \Drupal\Core\Entity\EntityTypeBundleInfoInterface $entity_type_bundle_info
* The entity type bundle service.
* @param \Drupal\Component\Datetime\TimeInterface $time
* The time service.
* @param \Drupal\Core\Datetime\DateFormatterInterface $date_formatter
* The date formatter service.
* @param \Drupal\Core\Extension\ModuleHandlerInterface $module_handler
* The module handler.
*/
public function __construct(EntityRepositoryInterface $entity_repository, EntityTypeBundleInfoInterface $entity_type_bundle_info, TimeInterface $time, DateFormatterInterface $date_formatter, ModuleHandlerInterface $module_handler) {
parent::__construct($entity_repository, $entity_type_bundle_info, $time);
$this->dateFormatter = $date_formatter;
$this->moduleHandler = $module_handler;
}
/**
* {@inheritdoc}
*/
public static function create(ContainerInterface $container) {
return new static(
$container->get('entity.repository'),
$container->get('entity_type.bundle.info'),
$container->get('datetime.time'),
$container->get('date.formatter'),
$container->get('module_handler'),
);
}
/**
* {@inheritdoc}
*/
protected function getNewRevisionDefault() {
return TRUE;
}
/**
* Function that returns an array of tab definitions to add.
*
* @return array
* Array of tab definitions keyed by tab id. Each definition should
* provide a location, title and weight.
*/
protected function getFieldGroups() {
$entity_type = $this->entity->getEntityTypeId();
$bundle = $this->entity->bundle();
$field_groups = [
'default' => [
'location' => 'main',
'title' => 'Default',
'weight' => -50,
],
'meta' => [
'location' => 'sidebar',
'title' => $this->t('Meta'),
'weight' => 0,
],
'location' => [
'location' => 'main',
'title' => $this->t('Location'),
'weight' => 50,
],
'file' => [
'location' => 'main',
'title' => $this->t('Files'),
'weight' => 150,
],
'revision' => [
'location' => 'sidebar',
'title' => $this->t('Revision information'),
'weight' => 500,
],
] + $this->moduleHandler->invokeAll('farm_ui_theme_field_groups', [$entity_type, $bundle]);
return $field_groups;
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
// Add process callback to alter form after GinContentFormHelper.
$form['#process'][] = '::processContentForm';
// Only alter the form display if farm_ui_theme.use_field_group is TRUE
// or if the form display is new and not saved.
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $form_state->get('form_display');
if (!$form_display || !$form_display->getThirdPartySetting('farm_ui_theme', 'use_field_group', $form_display->isNew())) {
return $form;
}
// Attach content form styles.
$form['#attached']['library'][] = 'farm_ui_theme/content_form';
// Add field groups, and allow modules to alter them.
$field_groups = $this->getFieldGroups();
if (!empty($field_groups)) {
// Disable HTML5 validation on the form element since it does not work
// with vertical tabs.
$form['#attributes']['novalidate'] = 'novalidate';
// Vary field group titles based on entity and bundle.
if (isset($field_groups['default'])) {
$field_groups['default']['title'] = $this->getBundleEntity()?->label() ?? $this->entity->getEntityType()->getLabel();
}
// Create parent for all tabs.
$form['tabs'] = [
'#type' => 'vertical_tabs',
'#default_tab' => 'edit-setup',
];
// Create tabs.
foreach ($field_groups as $tab_id => $tab_info) {
$tab_id = "{$tab_id}_field_group";
$tab_group = $tab_info['location'] == 'sidebar' ? 'advanced' : 'tabs';
$form[$tab_id] = [
'#type' => 'details',
'#title' => $tab_info['title'],
'#group' => $tab_group,
'#optional' => TRUE,
'#weight' => $tab_info['weight'],
'#open' => $tab_id === 'default_field_group' || $tab_id === 'meta_field_group',
];
}
// Set field group for each display component.
foreach ($form_display->getComponents() as $field_id => $options) {
if (isset($form[$field_id]) && $render = $form_display->getRenderer($field_id)) {
$tab_id = $render->getThirdPartySetting('farm_ui_theme', 'field_group', 'default');
$form[$field_id]['#group'] = "{$tab_id}_field_group";
}
}
}
// Comments are a special case because the CommentWidget sets the #group
// for the widget to advanced but this weight is never set.
if (isset($form['comment']['widget'][0])) {
$form['comment']['widget'][0]['#weight'] = $form['comment']['#weight'];
}
// Add authoring information for existing entities.
if (!$this->entity->isNew()) {
$form['revision_field_group']['#optional'] = FALSE;
$revision_items = [];
// Only add created metadata if available.
if ($this->entity instanceof EntityOwnerInterface) {
$author = $this->entity->getOwner()->getAccountName();
$date = $this->dateFormatter->format($this->entity->getCreatedTime(), 'short', '', $this->currentUser()->getTimeZone(), '');
$revision_items[] = $this->t('Created @timestamp by @author', ['@timestamp' => $date, '@author' => $author]);
}
// Only add revision information if available.
if ($this->entity instanceof RevisionLogInterface && $user = $this->entity->getRevisionUser()) {
$changed = $this->dateFormatter->format($this->entity->getRevisionCreationTime(), 'short', '', $this->currentUser()->getTimeZone(), '');
$revision_items[] = $this->t('Last saved: @timestamp by @author', ['@timestamp' => $changed, '@author' => $user->label()]);
}
// Else only add changed metadata if available.
elseif ($this->entity instanceof EntityChangedInterface) {
$changed = $this->dateFormatter->format($this->entity->getChangedTime(), 'short', '', $this->currentUser()->getTimeZone(), '');
$revision_items[] = $this->t('Last saved: @timestamp', ['@timestamp' => $changed]);
}
// Add to revision field group.
$form['revision_field_group']['revision_meta'] = [
'#theme' => 'item_list',
'#items' => $revision_items,
];
}
return $form;
}
/**
* Process function to update form after GinContentFormHelper.
*
* @param array $form
* The form array to alter.
* @param \Drupal\Core\Form\FormStateInterface $form_state
* The form state.
*
* @return array
* The form array.
*
* @see \Drupal\gin\GinContentFormHelper
*/
public function processContentForm(array $form, FormStateInterface $form_state): array {
// Increase weight of Gin's meta group to bottom of the sidebar.
// This group has special styling and includes additional action
// buttons like Delete that should be included on the page.
$form['meta']['#weight'] = 500;
// Assign correct status group after GinContentFormHelper.
if (isset($form['status']) && isset($form['meta_field_group'])) {
$form['status']['#group'] = 'meta_field_group';
}
// Else unset the status group that is set by GinContentFormHelper.
else {
unset($form['status']['#group']);
}
// Remove the sidebar if the display is not using field groups.
/** @var \Drupal\Core\Entity\Display\EntityFormDisplayInterface $form_display */
$form_display = $form_state->get('form_display');
if (!$form_display || !$form_display->getThirdPartySetting('farm_ui_theme', 'use_field_group', $form_display->isNew())) {
// Revert Gin changes to advanced and revision information.
$form['advanced']['#type'] = 'vertical_tabs';
$form['revision_information']['#type'] = 'details';
$form['revision_information']['#group'] = 'advanced';
// Do not use the node_edit_form theme.
// The template includes elements for the sidebar.
unset($form['#theme']);
unset($form['gin_actions']);
unset($form['gin_sidebar']);
// Remove gin sidebar and edit_form libraries.
if (($index = array_search('gin/sidebar', $form['#attached']['library'])) !== FALSE) {
unset($form['#attached']['library'][$index]);
}
if (($index = array_search('gin/edit_form', $form['#attached']['library'])) !== FALSE) {
unset($form['#attached']['library'][$index]);
}
}
return $form;
}
/**
* {@inheritdoc}
*/
public function save(array $form, FormStateInterface $form_state) {
$status = parent::save($form, $form_state);
$entity_type_label = $this->entity->getEntityType()->getSingularLabel();
$entity_url = $this->entity->toUrl()->setAbsolute()->toString();
$this->messenger()->addMessage($this->t('Saved %entity_type_label: <a href=":url">%label</a>', ['%entity_type_label' => $entity_type_label, ':url' => $entity_url, '%label' => $this->entity->label()]));
$form_state->setRedirectUrl($this->entity->toUrl());
return $status;
}
}
@@ -0,0 +1,28 @@
<?php
namespace Drupal\farm_ui_theme\Form;
/**
* Log form for gin content form.
*/
class LogForm extends GinContentFormBase {
/**
* {@inheritdoc}
*/
protected function getFieldGroups() {
return parent::getFieldGroups() + [
'asset' => [
'location' => 'main',
'title' => $this->t('Assets'),
'weight' => 40,
],
'quantity' => [
'location' => 'main',
'title' => $this->t('Quantity'),
'weight' => 100,
],
];
}
}
@@ -0,0 +1,10 @@
<?php
namespace Drupal\farm_ui_theme\Form;
/**
* Plan form for gin content form.
*/
class PlanForm extends GinContentFormBase {
}
@@ -0,0 +1,174 @@
<?php
namespace Drupal\farm_ui_theme\Form;
use Drupal\Core\Entity\EntityConstraintViolationListInterface;
use Drupal\Core\Form\FormStateInterface;
use Drupal\taxonomy\TermInterface;
/**
* Taxonomy term form for gin content form.
*/
class TaxonomyTermForm extends GinContentFormBase {
/**
* {@inheritdoc}
*/
protected function getFieldGroups() {
return parent::getFieldGroups() + [
'reference' => [
'location' => 'main',
'title' => $this->t('Reference'),
'weight' => 50,
],
'relations' => [
'location' => 'sidebar',
'title' => $this->t('Relations'),
'weight' => 50,
],
];
}
/**
* {@inheritdoc}
*/
public function form(array $form, FormStateInterface $form_state) {
$form = parent::form($form, $form_state);
// Term relations logic copied from Drupal\taxonomy\TermForm::form.
$term = $this->entity;
$vocab_storage = $this->entityTypeManager->getStorage('taxonomy_vocabulary');
/** @var \Drupal\taxonomy\TermStorageInterface $taxonomy_storage */
$taxonomy_storage = $this->entityTypeManager->getStorage('taxonomy_term');
$vocabulary = $vocab_storage->load($term->bundle());
$parent = $this->getParentIds($term);
$form_state->set(['taxonomy', 'parent'], $parent);
$form_state->set(['taxonomy', 'vocabulary'], $vocabulary);
// \Drupal\taxonomy\TermStorageInterface::loadTree() and
// \Drupal\taxonomy\TermStorageInterface::loadParents() may contain large
// numbers of items so we check for taxonomy.settings:override_selector
// before loading the full vocabulary. Contrib modules can then intercept
// before hook_form_alter to provide scalable alternatives.
if (!$this->config('taxonomy.settings')->get('override_selector')) {
$exclude = [];
if (!$term->isNew()) {
$children = $taxonomy_storage->loadTree($vocabulary->id(), $term->id());
// A term can't be the child of itself, nor of its children.
foreach ($children as $child) {
$exclude[] = $child->tid;
}
$exclude[] = $term->id();
}
$tree = $taxonomy_storage->loadTree($vocabulary->id());
$options = ['<' . $this->t('root') . '>'];
if (empty($parent)) {
$parent = [0];
}
foreach ($tree as $item) {
if (!in_array($item->tid, $exclude)) {
$options[$item->tid] = str_repeat('-', $item->depth) . $item->name;
}
}
}
else {
$options = ['<' . $this->t('root') . '>'];
$parent = [0];
}
if ($this->getRequest()->query->has('parent')) {
$parent = array_values(array_intersect(
array_keys($options),
(array) $this->getRequest()->query->all()['parent'],
));
}
// The select field doesn't support #group so needs to be under the
// relations_field_group form structure.
$form['relations_field_group']['parent'] = [
'#type' => 'select',
'#title' => $this->t('Parent terms'),
'#options' => $options,
'#default_value' => $parent,
'#multiple' => TRUE,
'#group' => 'relations_field_group',
];
// Textfields support #group so use that.
$form['weight'] = [
'#type' => 'textfield',
'#title' => $this->t('Weight'),
'#size' => 6,
'#default_value' => $term->getWeight(),
'#description' => $this->t('Terms are displayed in ascending order by weight.'),
'#required' => TRUE,
'#group' => 'relations_field_group',
];
return $form;
}
/**
* {@inheritdoc}
*/
public function buildEntity(array $form, FormStateInterface $form_state) {
$term = parent::buildEntity($form, $form_state);
// Prevent leading and trailing spaces in term names.
$term->setName(trim($term->getName()));
// Assign parents with proper delta values starting from 0.
$term->parent = array_values($form_state->getValue('parent'));
return $term;
}
/**
* {@inheritdoc}
*/
protected function getEditedFieldNames(FormStateInterface $form_state) {
return array_merge(['parent', 'weight'], parent::getEditedFieldNames($form_state));
}
/**
* {@inheritdoc}
*/
protected function flagViolations(EntityConstraintViolationListInterface $violations, array $form, FormStateInterface $form_state) {
// Manually flag violations of fields not handled by the form display. This
// is necessary as entity form displays only flag violations for fields
// contained in the display.
// @see ::form()
foreach ($violations->getByField('parent') as $violation) {
$form_state->setErrorByName('parent', $violation->getMessage());
}
foreach ($violations->getByField('weight') as $violation) {
$form_state->setErrorByName('weight', $violation->getMessage());
}
parent::flagViolations($violations, $form, $form_state);
}
/**
* Returns term parent IDs, including the root.
*
* @param \Drupal\taxonomy\TermInterface $term
* The taxonomy term entity.
*
* @return array
* A list if parent term IDs.
*/
protected function getParentIds(TermInterface $term): array {
$parent = [];
// Get the parent directly from the term as
// \Drupal\taxonomy\TermStorageInterface::loadParents() excludes the root.
foreach ($term->get('parent') as $item) {
$parent[] = (int) $item->target_id;
}
return $parent;
}
}
@@ -0,0 +1,47 @@
<?php
namespace Drupal\farm_ui_theme\Plugin\Block;
use Drupal\Component\Utility\SortArray;
use Drupal\Core\Menu\Plugin\Block\LocalActionsBlock;
/**
* Provides a block to display the local actions.
*
* @Block(
* id = "farm_local_actions_block",
* admin_label = @Translation("Primary farm admin actions")
* )
*/
class FarmLocalActionsBlock extends LocalActionsBlock {
/**
* {@inheritdoc}
*/
public function build() {
// Render local actions as a dropbutton.
$local_actions = parent::build();
uasort($local_actions, [SortArray::class, 'sortByWeightProperty']);
$links = [];
foreach ($local_actions as $local_action) {
if (!empty($local_action['#link']) && $local_action['#access']->isAllowed()) {
// Copy localized_options into the URL options.
// This is necessary to maintain any query parameters that were added
// to the action links.
$local_action['#link']['url']->setOptions(array_merge($local_action['#link']['url']->getOptions(), $local_action['#link']['localized_options']));
// Add the link.
$links[] = $local_action['#link'];
}
}
return [
'#type' => 'dropbutton',
'#dropbutton_type' => 'standard',
'#links' => $links,
'#cache' => $local_actions['#cache'],
];
}
}
Loaded 100 of 31193 files, more files were not shown because too many files have changed in this diff. Show more