Merge pull request #19691 from colemanw/afformEditLink
[civicrm-core.git] / Civi / Angular / AngularLoader.php
1 <?php
2 namespace 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 *
11 * ```
12 * $loader = new AngularLoader();
13 * $loader->setPageName('civicrm/case/a');
14 * $loader->setModules(array('crmApp'));
15 * $loader->load();
16 * ```
17 *
18 * @link https://docs.angularjs.org/guide/bootstrap
19 */
20 class 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
64 /**
65 * @var array|null
66 */
67 protected $crmApp = NULL;
68
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';
76 $this->pageName = \CRM_Utils_System::currentPath();
77 $this->modules = [];
78 }
79
80 /**
81 * Register resources required by Angular.
82 *
83 * @return AngularLoader
84 */
85 public function load() {
86 $angular = $this->getAngular();
87 $res = $this->getRes();
88
89 if ($this->crmApp !== NULL) {
90 $this->addModules($this->crmApp['modules']);
91 $region = \CRM_Core_Region::instance($this->crmApp['region']);
92 $region->update('default', ['disabled' => TRUE]);
93 $region->add(['template' => $this->crmApp['file'], 'weight' => 0]);
94 $this->res->addSetting([
95 'crmApp' => [
96 'defaultRoute' => $this->crmApp['defaultRoute'],
97 ],
98 ]);
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 #).
103 $this->res->addSetting([
104 'angularRoute' => $this->crmApp['activeRoute'],
105 ]);
106 }
107
108 $moduleNames = $this->findActiveModules();
109 if (!$this->isAllModules($moduleNames)) {
110 $assetParams = ['modules' => implode(',', $moduleNames)];
111 }
112 else {
113 // The module list will be "all modules that the user can see".
114 $assetParams = ['nonce' => md5(implode(',', $moduleNames))];
115 }
116
117 $res->addSettingsFactory(function () use (&$moduleNames, $angular, $res, $assetParams) {
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 }
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 }
133 // TODO optimization; client-side caching
134 return array_merge($settingsByModule, ['permissions' => $permissions], [
135 'resourceUrls' => \CRM_Extension_System::singleton()->getMapper()->getActiveModuleUrls(),
136 'angular' => [
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),
141 ],
142 ]);
143 });
144
145 $res->addScriptFile('civicrm', 'bower_components/angular/angular.min.js', 100, $this->getRegion(), FALSE);
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 }
177 // Add bundles
178 foreach ($this->angular->getResources($moduleNames, 'bundles', 'bundles') as $bundles) {
179 $res->addBundle($bundles);
180 }
181
182 return $this;
183 }
184
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
202 * Ex: '/case/list'
203 * - defaultRoute: string, use this to redirect the default route (`/`) to another page
204 * Ex: '/case/list'
205 * - region: string, the place on the page where we should insert the angular app
206 * Ex: 'page-body'
207 * @return AngularLoader
208 * @link https://code.angularjs.org/1.5.11/docs/guide/bootstrap
209 */
210 public function useApp($settings = []) {
211 $defaults = [
212 'modules' => ['crmApp'],
213 'activeRoute' => NULL,
214 'defaultRoute' => NULL,
215 'region' => 'page-body',
216 'file' => 'Civi/Angular/Page/Main.tpl',
217 ];
218 $this->crmApp = array_merge($defaults, $settings);
219 return $this;
220 }
221
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
255 * @return AngularLoader
256 */
257 public function setRes($res) {
258 $this->res = $res;
259 return $this;
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
271 * @return AngularLoader
272 */
273 public function setAngular($angular) {
274 $this->angular = $angular;
275 return $this;
276 }
277
278 /**
279 * @return string
280 */
281 public function getRegion() {
282 return $this->region;
283 }
284
285 /**
286 * @param string $region
287 * @return AngularLoader
288 */
289 public function setRegion($region) {
290 $this->region = $region;
291 return $this;
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'.
305 * @return AngularLoader
306 */
307 public function setPageName($pageName) {
308 $this->pageName = $pageName;
309 return $this;
310 }
311
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
322 /**
323 * @return array
324 */
325 public function getModules() {
326 return $this->modules;
327 }
328
329 /**
330 * @param array $modules
331 * @return AngularLoader
332 */
333 public function setModules($modules) {
334 $this->modules = $modules;
335 return $this;
336 }
337
338 }