theming.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144
  1. "use strict";
  2. /**
  3. * Use of this source code is governed by an MIT-style license that can be
  4. * found in the LICENSE file at https://github.com/NG-ZORRO/ng-zorro-antd/blob/master/LICENSE
  5. */
  6. var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
  7. function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
  8. return new (P || (P = Promise))(function (resolve, reject) {
  9. function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
  10. function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
  11. function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
  12. step((generator = generator.apply(thisArg, _arguments || [])).next());
  13. });
  14. };
  15. Object.defineProperty(exports, "__esModule", { value: true });
  16. exports.addThemeToAppStyles = addThemeToAppStyles;
  17. const schematics_1 = require("@angular/cdk/schematics");
  18. const core_1 = require("@angular-devkit/core");
  19. const schematics_2 = require("@angular-devkit/schematics");
  20. const change_1 = require("@schematics/angular/utility/change");
  21. const workspace_1 = require("@schematics/angular/utility/workspace");
  22. const path_1 = require("path");
  23. const create_custom_theme_1 = require("../../utils/create-custom-theme");
  24. const compiledThemePathSegment = 'ng-zorro-antd';
  25. const compiledThemePath = './node_modules/ng-zorro-antd/ng-zorro-antd.min.css';
  26. const defaultCustomThemeFilename = 'theme.less';
  27. /** Object that maps a CLI target to its default builder name. */
  28. const defaultTargetBuilders = {
  29. build: [
  30. '@angular-devkit/build-angular:application', // for esbuild
  31. '@angular-devkit/build-angular:browser' // for webpack
  32. ],
  33. test: ['@angular-devkit/build-angular:karma']
  34. };
  35. /** Add pre-built styles to the main project style file. */
  36. function addThemeToAppStyles(options) {
  37. return (host, context) => __awaiter(this, void 0, void 0, function* () {
  38. if (options.theme) {
  39. return insertCustomTheme(options.project, host, context.logger);
  40. }
  41. else {
  42. return insertCompiledTheme(options.project, context.logger);
  43. }
  44. });
  45. }
  46. /**
  47. * Insert a custom theme to project style file. If no valid style file could be found, a new
  48. * Scss file for the custom theme will be created.
  49. */
  50. function insertCustomTheme(projectName, host, logger) {
  51. return __awaiter(this, void 0, void 0, function* () {
  52. const workspace = yield (0, workspace_1.getWorkspace)(host);
  53. const project = (0, schematics_1.getProjectFromWorkspace)(workspace, projectName);
  54. const stylesPath = (0, schematics_1.getProjectStyleFile)(project, 'less');
  55. const themeContent = (0, create_custom_theme_1.createCustomTheme)();
  56. if (!stylesPath) {
  57. if (!project.sourceRoot) {
  58. throw new schematics_2.SchematicsException(`Could not find source root for project: "${projectName}". ` +
  59. `Please make sure that the "sourceRoot" property is set in the workspace config.`);
  60. }
  61. // Normalize the path through the devkit utilities because we want to avoid having
  62. // unnecessary path segments and windows backslash delimiters.
  63. const customThemePath = (0, core_1.normalize)((0, path_1.join)(project.sourceRoot, defaultCustomThemeFilename));
  64. if (host.exists(customThemePath)) {
  65. logger.warn(`Cannot create a custom NG-ZORRO theme because
  66. ${customThemePath} already exists. Skipping custom theme generation.`);
  67. return (0, schematics_2.noop)();
  68. }
  69. host.create(customThemePath, themeContent);
  70. return addThemeStyleToTarget(projectName, 'build', customThemePath, logger);
  71. }
  72. const insertion = new change_1.InsertChange(stylesPath, 0, themeContent);
  73. const recorder = host.beginUpdate(stylesPath);
  74. recorder.insertLeft(insertion.pos, insertion.toAdd);
  75. host.commitUpdate(recorder);
  76. });
  77. }
  78. /** Insert a pre-built theme into the angular.json file. */
  79. function insertCompiledTheme(project, logger) {
  80. return (0, schematics_2.chain)([
  81. addThemeStyleToTarget(project, 'build', compiledThemePath, logger),
  82. addThemeStyleToTarget(project, 'test', compiledThemePath, logger)
  83. ]);
  84. }
  85. /** Adds a theming style entry to the given project target options. */
  86. function addThemeStyleToTarget(projectName, targetName, assetPath, logger) {
  87. return (0, workspace_1.updateWorkspace)(workspace => {
  88. const project = (0, schematics_1.getProjectFromWorkspace)(workspace, projectName);
  89. // Do not update the builder options in case the target does not use the default CLI builder.
  90. if (!validateDefaultTargetBuilder(project, targetName, logger)) {
  91. return;
  92. }
  93. const targetOptions = (0, schematics_1.getProjectTargetOptions)(project, targetName);
  94. const styles = targetOptions.styles;
  95. if (!styles) {
  96. targetOptions.styles = [assetPath];
  97. }
  98. else {
  99. const existingStyles = styles.map(s => (typeof s === 'string' ? s : s.input));
  100. for (const [index, stylePath] of existingStyles.entries()) {
  101. // If the given asset is already specified in the styles, we don't need to do anything.
  102. if (stylePath === assetPath) {
  103. return;
  104. }
  105. // In case a prebuilt theme is already set up, we can safely replace the theme with the new
  106. // theme file. If a custom theme is set up, we are not able to safely replace the custom
  107. // theme because these files can contain custom styles, while prebuilt themes are
  108. // always packaged and considered replaceable.
  109. if (stylePath.includes(defaultCustomThemeFilename)) {
  110. logger.error(`Could not style file to the CLI project configuration ` +
  111. `because there is already a custom theme file referenced.`);
  112. logger.info(`Please manually add the following style file to your configuration:`);
  113. logger.info(`${assetPath}`);
  114. return;
  115. }
  116. else if (stylePath.includes(compiledThemePathSegment)) {
  117. styles.splice(index, 1);
  118. }
  119. }
  120. }
  121. styles.unshift(assetPath);
  122. });
  123. }
  124. /**
  125. * Validates that the specified project target is configured with the default builders which are
  126. * provided by the Angular CLI. If the configured builder does not match the default builder,
  127. * this function can either throw or just show a warning.
  128. */
  129. function validateDefaultTargetBuilder(project, targetName, logger) {
  130. const defaultBuilder = defaultTargetBuilders[targetName];
  131. const targetConfig = project.targets && project.targets.get(targetName);
  132. const isDefaultBuilder = targetConfig && defaultBuilder.includes(targetConfig.builder);
  133. if (!isDefaultBuilder && targetName === 'build') {
  134. throw new schematics_2.SchematicsException(`Your project is not using the default builders for ` +
  135. `"${targetName}". The NG-ZORRO schematics cannot add a theme to the workspace ` +
  136. `configuration if the builder has been changed.`);
  137. }
  138. else if (!isDefaultBuilder) {
  139. logger.warn(`Your project is not using the default builders for "${targetName}". This ` +
  140. `means that we cannot add the configured theme to the "${targetName}" target.`);
  141. }
  142. return isDefaultBuilder;
  143. }
  144. //# sourceMappingURL=theming.js.map