All files / packages/design-system/scripts/gulp/generate sanitized.js

0% Statements 0/60
0% Branches 0/10
0% Functions 0/11
0% Lines 0/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 
// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved
// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license
 
import fs from 'fs';
import I from 'immutable';
import path from 'path';
import gulp from 'gulp';
import gulpRename from 'gulp-rename';
import through from 'through2';
import discardComments from 'postcss-discard-comments';
import { toList } from '../../../shared/utils/tree';
import paths from '../../helpers/paths';
import * as gulpHelpers from '../../helpers/gulp';
import { uiJson } from '../../ui';
 
const MODULE_NAME = 'salesforce-lightning-design-system';
 
/**
 * Store paths
 */
const root = path.resolve(__dirname, '../../../');
const rootPath = path.resolve.bind(path, root);
const distPath = path.resolve.bind(path, paths.dist);
 
/**
 * Regex to remove BEM -- modifier from source
 */
export const regex = [/(\.\S.*[\S]+.(--)+.*)(\,)+?\B/g, /\,[\n\s]*(\.\S.*[\S]+.(--)+.*)\b(\s|\]\))/g];
 
/**
 * Store ui.json in a keyed collection object
 * Map : string -> object
 */
const ui = I.Map(JSON.parse(uiJson()));
 
/**
 * Parse ui.json and store components from collection since we're
 * only concerned about components and not utilities
 * fromJs : object -> Map
 */
const components = I.fromJS(ui.get('components'));
 
/**
 * Empty array to store components that match the annotations we're looking for
 */
let rollup = [];
 
/**
 * Helper function to store paths in a friendly way
 * @param {string} c - Top level component
 * @param {string} v - Component variant, if it exists
 * setPath : component, variant -> string
 */
const setPath = (c, v) => {
  const component = c.get('id');
  const variant = c.get('id') === v.get('id') ? 'base' : v.get('id');
  return `${component}/${variant}`;
};
 
/**
 * Parse and store import paths based on lwc annotations
 * @param {Map} c - Immutable Map of components
 */
const readLwcAnnotations = (c) => {
  c.map((x) => {
    toList(x)
      .filter((item) => item.getIn(['annotations', 'lwc']))
      .map((z) => rollup.push(setPath(x, z)));
  });
};
 
/**
 * Writes a new scss file into ui/components that has the imports for
 * all components with @lwc annotations
 * @param {array} packages
 * @note Will sort alphabetically
 */
export const writeSanitizedScssFile = (packages) => {
  const file = rootPath('ui/components/_index.sanitized.scss');
  let pathImports = [];
  packages.map((t) => {
    pathImports.push(`@import '${t}/index';`);
  });
  let content = [
    '// Copyright (c) 2015-present, salesforce.com, inc. All rights reserved',
    '\n',
    '// Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license',
    '\n\n',
    pathImports.sort((a, b) => a.localeCompare(b)).join('\n'),
    '\n',
  ].join('');
 
  try {
    fs.writeFileSync(file, content);
  } catch (err) {
    console.log(`Unable to write file - ${err}`);
  }
};
 
/**
 * Writes a new css file into ui/components that has the imports for
 * all components with @lwc annotations, this file is for lwc to chunk
 * files using @import statements
 * @param {array} packages
 * @note Will sort alphabetically
 */
export const writeSanitizedCssFile = (packages) => {
  const file = distPath(`assets/styles/${MODULE_NAME}-imports.sanitized.css`);
  let pathImports = [];
  packages.map((t) => {
    pathImports.push(`@import '../../css/${t}/index.css';`);
  });
  let content = [
    '/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved',
    '\n',
    'Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */',
    '\n\n',
    "@import '../../css/common/index.css';",
    '\n',
    pathImports.sort((a, b) => a.localeCompare(b)).join('\n'),
    '\n',
  ].join('');
 
  try {
    fs.writeFileSync(file, content);
  } catch (err) {
    console.log(`Unable to write file - ${err}`);
  }
};
 
/**
 * We need to dynamically generate a common file to be used as an import
 * @param {callback} done
 */
export const writeCommonCss = (done) => {
  const dir = rootPath(`.css/common`);
  const file = rootPath(`${dir}/index.scss`);
  let content = [
    '/* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved',
    '\n',
    'Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */',
    '\n\n',
    "@import 'dist/scss/init';",
    '\n',
    "@import 'dist/scss/vendor/normalize-sanitized';",
    '\n',
    '@include core($scoped: false, $globals: false);',
    '\n',
  ].join('');
  try {
    if (fs.existsSync(dir)) {
      fs.writeFileSync(file, content);
    } else {
      fs.mkdir(dir, (err) => {
        if (err) throw err;
        fs.writeFileSync(file, content);
      });
    }
  } catch (err) {
    console.log(`Unable to write file - ${err}`);
  }
  if (done) done();
};
 
/**
 * Write sanitized version to assets/styles so it can be copied
 * and minified with dist script runs
 */
export const writeSanitizedCss = (done) => {
  gulp
    .src('ui/index-sanitized.scss')
    .pipe(gulpHelpers.writeScss({ outputStyle: 'expanded' }))
    .pipe(gulpHelpers.writePostCss([discardComments()]))
    // Need to format to ensure proper parsing
    .pipe(gulpHelpers.writePrettierCss())
    // Remove BEM -- modifiers
    .pipe(
      through.obj((file, enc, next) => {
        let newFile = file.clone();
        newFile.contents = Buffer.from(file.contents.toString().replace(regex[0], '').replace(regex[1], ''));
        return next(null, newFile);
      }),
    )
    // For cleanup
    .pipe(gulpHelpers.writePrettierCss())
    .pipe(
      gulpRename((path) => {
        path.basename = `${MODULE_NAME}.sanitized`;
        path.extname = '.css';
        return path;
      }),
    )
    .pipe(gulp.dest(distPath('assets/styles/')));
  if (done) done();
};
 
/**
 * Compiles sanitized version of SLDS component files
 */
export const writeSanitizedComponentCss = () => {
  return (
    gulp
      .src([paths.rootPath('.css/**/index.scss'), paths.rootPath('.css/**/touch.scss')])
      .pipe(gulpHelpers.writeScss({ outputStyle: 'expanded' }))
      .pipe(gulpHelpers.writePostCss([discardComments()]))
      // Need to format to ensure proper parsing
      .pipe(gulpHelpers.writePrettierCss())
      .pipe(
        through.obj((file, enc, next) => {
          let newFile = file.clone();
          newFile.contents = Buffer.from(
            file.contents.toString().replace(regex[0], '').replace(regex[1], ''),
          );
          return next(null, newFile);
        }),
      )
      // For cleanup
      .pipe(gulpHelpers.writePrettierCss())
      .pipe(gulp.dest(distPath('css/')))
  );
};
 
/**
 * Export for gulp task
 * @param {callback} done
 */
export const generateSanitizedScss = (done) => {
  readLwcAnnotations(components);
  writeSanitizedScssFile(rollup);
  writeSanitizedCssFile(rollup);
  if (done) done();
};