Merge pull request #19691 from colemanw/afformEditLink
[civicrm-core.git] / Civi / Angular / AngularLoader.php
CommitLineData
b20ea913
TO
1<?php
2namespace Civi\Angular;
3
4/**
5 * The AngularLoader loads any JS/CSS/JSON resources
6 * required for setting up AngularJS.
7 *
8 * The AngularLoader stops short of bootstrapping AngularJS. You may
9 * need to `<div ng-app="..."></div>` or `angular.bootstrap(...)`.
10 *
0b882a86 11 * ```
b20ea913
TO
12 * $loader = new AngularLoader();
13 * $loader->setPageName('civicrm/case/a');
14 * $loader->setModules(array('crmApp'));
15 * $loader->load();
0b882a86 16 * ```
b20ea913
TO
17 *
18 * @link https://docs.angularjs.org/guide/bootstrap
19 */
20class AngularLoader {
21
22 /**
23 * The weight to assign to any Angular JS module files.
24 */
25 const DEFAULT_MODULE_WEIGHT = 200;
26
27 /**
28 * The resource manager.
29 *
30 * Do not use publicly. Inject your own copy!
31 *
32 * @var \CRM_Core_Resources
33 */
34 protected $res;
35
36 /**
37 * The Angular module manager.
38 *
39 * Do not use publicly. Inject your own copy!
40 *
41 * @var \Civi\Angular\Manager
42 */
43 protected $angular;
44
45 /**
46 * The region of the page into which JavaScript will be loaded.
47 *
48 * @var string
49 */
50 protected $region;
51
52 /**
53 * @var string
54 * Ex: 'civicrm/a'.
55 */
56 protected $pageName;
57
58 /**
59 * @var array
60 * A list of modules to load.
61 */
62 protected $modules;
63
3e8823e3 64 /**
cc101011 65 * @var array|null
3e8823e3
TO
66 */
67 protected $crmApp = NULL;
68
b20ea913
TO
69 /**
70 * AngularLoader constructor.
71 */
72 public function __construct() {
73 $this->res = \CRM_Core_Resources::singleton();
74 $this->angular = \Civi::service('angular');
75 $this->region = \CRM_Utils_Request::retrieve('snippet', 'String') ? 'ajax-snippet' : 'html-header';
292054ac 76 $this->pageName = \CRM_Utils_System::currentPath();
c64f69d9 77 $this->modules = [];
b20ea913
TO
78 }
79
80 /**
81 * Register resources required by Angular.
cba659e7
TO
82 *
83 * @return AngularLoader
b20ea913
TO
84 */
85 public function load() {
86 $angular = $this->getAngular();
87 $res = $this->getRes();
88
3e8823e3
TO
89 if ($this->crmApp !== NULL) {
90 $this->addModules($this->crmApp['modules']);
91 $region = \CRM_Core_Region::instance($this->crmApp['region']);
c64f69d9
CW
92 $region->update('default', ['disabled' => TRUE]);
93 $region->add(['template' => $this->crmApp['file'], 'weight' => 0]);
94 $this->res->addSetting([
95 'crmApp' => [
3e8823e3 96 'defaultRoute' => $this->crmApp['defaultRoute'],
c64f69d9
CW
97 ],
98 ]);
3e8823e3
TO
99
100 // If trying to load an Angular page via AJAX, the route must be passed as a
101 // URL parameter, since the server doesn't receive information about
102 // URL fragments (i.e, what comes after the #).
c64f69d9 103 $this->res->addSetting([
3e8823e3 104 'angularRoute' => $this->crmApp['activeRoute'],
c64f69d9 105 ]);
3e8823e3
TO
106 }
107
b20ea913
TO
108 $moduleNames = $this->findActiveModules();
109 if (!$this->isAllModules($moduleNames)) {
c64f69d9 110 $assetParams = ['modules' => implode(',', $moduleNames)];
b20ea913
TO
111 }
112 else {
113 // The module list will be "all modules that the user can see".
c64f69d9 114 $assetParams = ['nonce' => md5(implode(',', $moduleNames))];
b20ea913
TO
115 }
116
117 $res->addSettingsFactory(function () use (&$moduleNames, $angular, $res, $assetParams) {
aa882f9b
CW
118 // Merge static settings with the results of settingsFactory functions
119 $settingsByModule = $angular->getResources($moduleNames, 'settings', 'settings');
120 foreach ($angular->getResources($moduleNames, 'settingsFactory', 'settingsFactory') as $moduleName => $factory) {
121 $settingsByModule[$moduleName] = array_merge($settingsByModule[$moduleName] ?? [], $factory());
122 }
66c46618
CW
123 // Add clientside permissions
124 $permissions = [];
125 $toCheck = $angular->getResources($moduleNames, 'permissions', 'permissions');
126 foreach ($toCheck as $perms) {
127 foreach ((array) $perms as $perm) {
128 if (!isset($permissions[$perm])) {
129 $permissions[$perm] = \CRM_Core_Permission::check($perm);
130 }
131 }
132 }
b20ea913 133 // TODO optimization; client-side caching
66c46618 134 return array_merge($settingsByModule, ['permissions' => $permissions], [
b20ea913 135 'resourceUrls' => \CRM_Extension_System::singleton()->getMapper()->getActiveModuleUrls(),
c64f69d9 136 'angular' => [
b20ea913
TO
137 'modules' => $moduleNames,
138 'requires' => $angular->getResources($moduleNames, 'requires', 'requires'),
139 'cacheCode' => $res->getCacheCode(),
140 'bundleUrl' => \Civi::service('asset_builder')->getUrl('angular-modules.json', $assetParams),
c64f69d9
CW
141 ],
142 ]);
b20ea913
TO
143 });
144
145 $res->addScriptFile('civicrm', 'bower_components/angular/angular.min.js', 100, $this->getRegion(), FALSE);
b20ea913
TO
146
147 $headOffset = 0;
148 $config = \CRM_Core_Config::singleton();
149 if ($config->debug) {
150 foreach ($moduleNames as $moduleName) {
151 foreach ($this->angular->getResources($moduleName, 'css', 'cacheUrl') as $url) {
152 $res->addStyleUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->getRegion());
153 }
154 foreach ($this->angular->getResources($moduleName, 'js', 'cacheUrl') as $url) {
155 $res->addScriptUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->getRegion());
156 // addScriptUrl() bypasses the normal string-localization of addScriptFile(),
157 // but that's OK because all Angular strings (JS+HTML) will load via crmResource.
158 }
159 }
160 }
161 else {
162 // Note: addScriptUrl() bypasses the normal string-localization of addScriptFile(),
163 // but that's OK because all Angular strings (JS+HTML) will load via crmResource.
164 // $aggScriptUrl = \CRM_Utils_System::url('civicrm/ajax/angular-modules', 'format=js&r=' . $res->getCacheCode(), FALSE, NULL, FALSE);
165 $aggScriptUrl = \Civi::service('asset_builder')->getUrl('angular-modules.js', $assetParams);
166 $res->addScriptUrl($aggScriptUrl, 120, $this->getRegion());
167
168 // FIXME: The following CSS aggregator doesn't currently handle path-adjustments - which can break icons.
169 //$aggStyleUrl = \CRM_Utils_System::url('civicrm/ajax/angular-modules', 'format=css&r=' . $res->getCacheCode(), FALSE, NULL, FALSE);
170 //$aggStyleUrl = \Civi::service('asset_builder')->getUrl('angular-modules.css', $assetParams);
171 //$res->addStyleUrl($aggStyleUrl, 120, $this->getRegion());
172
173 foreach ($this->angular->getResources($moduleNames, 'css', 'cacheUrl') as $url) {
174 $res->addStyleUrl($url, self::DEFAULT_MODULE_WEIGHT + (++$headOffset), $this->getRegion());
175 }
176 }
d67ff852
CW
177 // Add bundles
178 foreach ($this->angular->getResources($moduleNames, 'bundles', 'bundles') as $bundles) {
179 $res->addBundle($bundles);
180 }
cba659e7
TO
181
182 return $this;
b20ea913
TO
183 }
184
3e8823e3
TO
185 /**
186 * Use Civi's generic "application" module.
187 *
188 * This is suitable for use on a basic, standalone Angular page
189 * like `civicrm/a`. (If you need to integrate Angular with pre-existing,
190 * non-Angular pages... then this probably won't help.)
191 *
192 * The Angular bootstrap process requires an HTML directive like
193 * `<div ng-app="foo">`.
194 *
195 * Calling useApp() will replace the page's main body with the
196 * `<div ng-app="crmApp">...</div>` and apply some configuration options
197 * for the `crmApp` module.
198 *
199 * @param array $settings
200 * A list of settings. Accepted values:
201 * - activeRoute: string, the route to open up immediately
23a258ce
TO
202 * Ex: '/case/list'
203 * - defaultRoute: string, use this to redirect the default route (`/`) to another page
204 * Ex: '/case/list'
3e8823e3 205 * - region: string, the place on the page where we should insert the angular app
23a258ce 206 * Ex: 'page-body'
3e8823e3
TO
207 * @return AngularLoader
208 * @link https://code.angularjs.org/1.5.11/docs/guide/bootstrap
209 */
c64f69d9
CW
210 public function useApp($settings = []) {
211 $defaults = [
212 'modules' => ['crmApp'],
3e8823e3
TO
213 'activeRoute' => NULL,
214 'defaultRoute' => NULL,
215 'region' => 'page-body',
216 'file' => 'Civi/Angular/Page/Main.tpl',
c64f69d9 217 ];
3e8823e3
TO
218 $this->crmApp = array_merge($defaults, $settings);
219 return $this;
220 }
221
b20ea913
TO
222 /**
223 * Get a list of all Angular modules which should be activated on this
224 * page.
225 *
226 * @return array
227 * List of module names.
228 * Ex: array('angularFileUpload', 'crmUi', 'crmUtil').
229 */
230 public function findActiveModules() {
231 return $this->angular->resolveDependencies(array_merge(
232 $this->getModules(),
233 $this->angular->resolveDefaultModules($this->getPageName())
234 ));
235 }
236
237 /**
238 * @param $moduleNames
239 * @return int
240 */
241 private function isAllModules($moduleNames) {
242 $allModuleNames = array_keys($this->angular->getModules());
243 return count(array_diff($allModuleNames, $moduleNames)) === 0;
244 }
245
246 /**
247 * @return \CRM_Core_Resources
248 */
249 public function getRes() {
250 return $this->res;
251 }
252
253 /**
254 * @param \CRM_Core_Resources $res
cba659e7 255 * @return AngularLoader
b20ea913
TO
256 */
257 public function setRes($res) {
258 $this->res = $res;
cba659e7 259 return $this;
b20ea913
TO
260 }
261
262 /**
263 * @return \Civi\Angular\Manager
264 */
265 public function getAngular() {
266 return $this->angular;
267 }
268
269 /**
270 * @param \Civi\Angular\Manager $angular
cba659e7 271 * @return AngularLoader
b20ea913
TO
272 */
273 public function setAngular($angular) {
274 $this->angular = $angular;
cba659e7 275 return $this;
b20ea913
TO
276 }
277
278 /**
279 * @return string
280 */
281 public function getRegion() {
282 return $this->region;
283 }
284
285 /**
286 * @param string $region
cba659e7 287 * @return AngularLoader
b20ea913
TO
288 */
289 public function setRegion($region) {
290 $this->region = $region;
cba659e7 291 return $this;
b20ea913
TO
292 }
293
294 /**
295 * @return string
296 * Ex: 'civicrm/a'.
297 */
298 public function getPageName() {
299 return $this->pageName;
300 }
301
302 /**
303 * @param string $pageName
304 * Ex: 'civicrm/a'.
cba659e7 305 * @return AngularLoader
b20ea913
TO
306 */
307 public function setPageName($pageName) {
308 $this->pageName = $pageName;
cba659e7 309 return $this;
b20ea913
TO
310 }
311
d2f38ec9
TO
312 /**
313 * @param array|string $modules
314 * @return AngularLoader
315 */
316 public function addModules($modules) {
317 $modules = (array) $modules;
318 $this->modules = array_unique(array_merge($this->modules, $modules));
319 return $this;
320 }
321
b20ea913
TO
322 /**
323 * @return array
324 */
325 public function getModules() {
326 return $this->modules;
327 }
328
329 /**
330 * @param array $modules
cba659e7 331 * @return AngularLoader
b20ea913
TO
332 */
333 public function setModules($modules) {
334 $this->modules = $modules;
cba659e7 335 return $this;
b20ea913
TO
336 }
337
338}