How to use balanced-match - 9 common examples

To help you get started, we’ve selected a few balanced-match examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jhildenbiddle / css-vars-ponyfill / src / parse-css.js View on Github external
function rule() {
        if (!settings.preserveStatic) {
            const balancedMatch = balanced('{', '}', css);

            // Skip rulset if it does not contain a root/host variable
            // declaration or a variable function value
            if (balancedMatch) {
                const hasVarDecl = /:(?:root|host)(?![.:#(])/.test(balancedMatch.pre) && /--\S*\s*:/.test(balancedMatch.body);
                const hasVarFunc = /var\(/.test(balancedMatch.body);

                if (!hasVarDecl && !hasVarFunc) {
                    css = css.slice(balancedMatch.end + 1);

                    return {};
                }
            }
        }

        const sel   = selector() || [];
github ElementUI / theme-default-scss / src / features / calc.es6 View on Github external
const removeCalc = value => {
  var calcIndex = value.indexOf('calc')
  if (calcIndex === -1) return value
  var pre = value.substr(0, calcIndex)
  var next = value.substr(calcIndex)

  var result = balanced('(', ')', next)

  // if (result.post[0] === '%') {
  //   result.post = result.post.substr(1)
  // }

  if (result.post[0] !== ' ') {
    result.body = '(' + result.body
    while (result.post[0] && result.post[0] !== ' ') {
      result.body += result.post[0]
      result.post = result.post.substr(1)
    }
    result.body += ')'
  }

  if (result.body[0] !== '(') {
    result.body = '(' + result.body + ')'
github salesforce / lwc / packages / postcss-plugin-lwc / src / custom-properties / transform.ts View on Github external
function transform(decl: Declaration, transformer: VarTransformer, value: string): string {
    const varMatch = VAR_FUNC_REGEX.exec(value);

    // Early exit of the value doesn't contain any `var` function call
    if (varMatch === null) {
        return value;
    }

    // Prefix is either an empty string or a whitespace depending if the `var()` function is
    // in the middle of the value or not. We need to preserve this whitespace in the final
    // output.
    const prefixWhitespace = varMatch[1];
    const start = varMatch.index;

    const parenthesisMatch = balanced('(', ')', value.slice(start));
    if (!parenthesisMatch) {
        throw generateErrorFromDeclaration(decl, {
            errorInfo: CSSTransformErrors.CUSTOM_PROPERTY_MISSING_CLOSING_PARENS,
            messageArgs: [value]
        });
    }

    // Extract the `var()` function arguments
    const varArgumentsMatch = VAR_ARGUMENTS_REGEX.exec(parenthesisMatch.body);
    if (varArgumentsMatch === null) {
        throw generateErrorFromDeclaration(decl, {
            errorInfo: CSSTransformErrors.CUSTOM_PROPERTY_INVALID_VAR_FUNC_SIGNATURE,
            messageArgs: [value]
        });
    }
github jhildenbiddle / css-vars-ponyfill / src / transform-css.js View on Github external
function resolveValue(value, settings = {}, __recursiveFallback) {
    if (value.indexOf('var(') === -1) {
        return value;
    }

    const valueData = balanced('(', ')', value);

    /**
     * Resolves contents of CSS custom property function
     *
     * @param {string} value String containing contents of CSS var() function
     * @returns {string}
     *
     * @example
     *
     *   resolveFunc('--x, var(--y, green)')
     *   // => obj['--x'] or obj['--y'] or 'green'
     *
     *   resolveFunc('--fail')
     *   // => 'var(--fail)' when obj['--fail'] does not exist
     */
    function resolveFunc(value) {
github iamstarkov / postcss-color-mix / index.js View on Github external
const transformColor = (string, source) => {
  if (string.indexOf('mix(') === -1) {
    return string;
  }

  const value = balanced('(', ')', string).body;

  if (!value) { throw new Error(`Missing closing parentheses in "${string}"`, source); }

  return mix.apply(null, value.split(/,\s*(?![^()]*\))/));
};
github postcss / postcss-selector-matches / src / replaceRuleSelector.js View on Github external
selectorPart.forEach(part => {
      const position = part.indexOf(pseudoClass)
      const pre = part.slice(0, position)
      const body = part.slice(position)
      const matches = balancedMatch("(", ")", body)

      const bodySelectors = matches && matches.body ?
        list
          .comma(matches.body)
          .reduce((acc, s) => [
            ...acc,
            ...explodeSelector(s, options),
          ], [])
        : [body]

      const postSelectors = matches && matches.post
        ? explodeSelector(matches.post, options)
        : []

      let newParts
      if (postSelectors.length === 0) {
github postcss / postcss-selector-not / src / index.js View on Github external
function explodeSelector(pseudoClass, selector) {
  const position = locatePseudoClass(selector, pseudoClass)
  if (selector && position > -1) {
    const pre = selector.slice(0, position)
    const matches = balancedMatch("(", ")", selector.slice(position))
    const bodySelectors = matches.body
      ? list
        .comma(matches.body)
        .map(s => explodeSelector(pseudoClass, s))
        .join(`)${pseudoClass}(`)
      : ""
    const postSelectors = matches.post
      ? explodeSelector(pseudoClass, matches.post)
      : ""

    return `${pre}${pseudoClass}(${bodySelectors})${postSelectors}`
  }
  return selector
}
github stylelint / stylelint / src / utils / blurFunctionArguments.js View on Github external
export default function (
  source: string,
  functionName: string,
  blurChar: string = "`"
): string {
  const nameWithParen = `${functionName.toLowerCase()}(`
  const lowerCaseSource = source.toLowerCase()
  if (!_.includes(lowerCaseSource, nameWithParen)) { return source }

  const functionNameLength: number = functionName.length

  let result = source
  let searchStartIndex = 0
  while (lowerCaseSource.indexOf(nameWithParen, searchStartIndex) !== -1) {
    const openingParenIndex = lowerCaseSource.indexOf(nameWithParen, searchStartIndex) + functionNameLength
    const closingParenIndex = balancedMatch("(", ")", lowerCaseSource.slice(openingParenIndex)).end + openingParenIndex
    const argumentsLength = closingParenIndex - openingParenIndex - 1
    result = result.slice(0, openingParenIndex + 1) + _.repeat(blurChar, argumentsLength) + result.slice(closingParenIndex)
    searchStartIndex = closingParenIndex
  }
  return result
}
github db-migrate / node-db-migrate / lib / transitions / update-version.js View on Github external
var searchString = 'exports.down';
  var balance;
  var metaIndex;
  var plus = 1;

  if(required._meta)
    searchString = 'exports._meta';

  metaIndex = data.indexOf(searchString);
  sub = data.substring(metaIndex);
  balance = balanced('{', '}', sub);

  if(sub[balance.end + 1] === ';')
    ++plus;

  sub = sub.substring(0, balanced.end);

  if(required._meta) {

    required._meta.version = version;

    data = data.substring(0, metaIndex) + sub.replace(
      sub.substring(balance.start, balance.end + 1),
      JSON.stringify(required._meta, null, 2)
    ) + data.substring(metaIndex + balance.end + plus);
  }
  else {

    data = data.substring(0, metaIndex + balance.end + plus) +
      '\n\nexports._meta = ' +
      JSON.stringify({ version: version }, null, 2) + ';' +
      data.substring(metaIndex + balance.end + plus);

balanced-match

Match balanced character pairs, like "{" and "}"

MIT
Latest version published 1 year ago

Package Health Score

75 / 100
Full package analysis

Popular balanced-match functions