Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URLs added here will be added as <link>s in order, and before the CSS in the editor. You can use the CSS from another Pen by using its URL and the proper URL extension.

+ add another resource

JavaScript

Babel includes JSX processing.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Packages

Add Packages

Search for and use JavaScript packages from npm here. By selecting a package, an import statement will be added to the top of the JavaScript editor for this package.

Behavior

Auto Save

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <h1>Gmail Group Spam Filter Pattern Generator</h1>
<p>Checking the Spam folder from time to time is quite important for not losing important emails, but it could be really tedious because all those spam rubbish in there. This tool generates a pattern string for your Gmail filter so useless emails from known spammers could be deleted from the Spam folder immediately after they were received.</p>

<div id="root"></div>

<h2>How to use it?</h2>
<p>Step 1: If you already have a spam filter pattern, copy and paste that into the "Pattern" field and click "Commit Changes" to extract the list of senders to the spammer list below.</p>
<p>Step 2: Add more spammers to the list. One entry per line. In the end, click "Commit Changes" to get the updated pattern in the text field above.</p>
<p>Step 3: Copy the updated pattern and use it to search in Gmail and create a filter for it or update an existing one. Then decide what to do with all these matched emails. What I did was simply deleting them. After creating the filter, all incoming emails matching the pattern (in spam folder and from these senders) will be deleted immediately.</p>

<fieldset>
  <legend>Todos</legend>
  <ul>
    <li>Better schema support? (Currently it strictly matches the example shown above.)</li>
    <li>Remove redundant entries.</li>
    <li>There seems to be a length limit of the filter string. But I can't find the actual limit. </li>
  </ul>
</fieldset>
              
            
!

CSS

              
                .input-fieldset {
  margin-bottom: 10px;
  
  & > legend {
    min-width: 300px;

    & > button {
      float: right;
    }
  }
}

#pattern-input, .pattern-input {
  display: block;
  box-sizing: border-box;
  width: 100%;
  margin-bottom: 5px;
}

#spammer-list-input, .spammer-list-input {
  display: block;
  box-sizing: border-box;
  width: 100%;
  margin-bottom: 5px;
  resize: vertical;
}

.pattern-input,
.spammer-list-input {
  &--changed {
    background-color: orange;
  }
}
              
            
!

JS

              
                /* import { Component } from 'react'; */
const { Component } = React;

/* import { render } from 'react-dom'; */
const { render } = ReactDOM;

/* import { createStore, combineReducers } from 'redux'; */
const { createStore, combineReducers } = Redux;

/* import { connect, Provider } from 'react-redux'; */
const { connect, Provider } = ReactRedux;

/**
 * @param {string} patternString
 * @return {Array.<string>}
 */
const parsePattern = (patternString) => {
  // Check the "from:" group.
  const fromGroupMatch = patternString.match(/from:\(((?:[^ ()]+(?: OR )?)+)\)/i);
  
  const fromGroupList = fromGroupMatch
    ? fromGroupMatch[1]
      .split(" OR ")
      .filter((s) => s.length > 0)
    : [];
  
  return fromGroupList;
};

/**
 * @param {string} a
 * @param {string} b
 * @return {number}
 */
const sortCompareSender = (a, b) => {
  const parseA = a.split("@");
  const parseB = b.split("@");
  
  // Compare domain first.
  if (parseA[1] < parseB[1]) {
    return -1;
  } else if (parseA[1] > parseB[1]) {
    return 1;
  } else {
    // Compare user next.
    if (parseA[0] < parseB[0]) {
      return -1;
    } else if (parseA[0] > parseB[0]) {
      return 1;
    } else {
      return 0;
    }
  }
};

/**
 * @param {Array.<string>} spammerList
 * @return {string}
 */
const generatePattern = (spammerList) => `label:spam from:(${spammerList.join(" OR ")})`;

/**
 * @param {string} spammerListString
 * @return {Array.<string>}
 */
const getSpammerList = (spammerListString) => spammerListString
  .split('\n')
  .map((s) => s.trim())
  .filter((s) => s.length > 0);

/**
 * @param {Array.<string>} spammerList
 * @return {string}
 */
const generateSpammerListString = (spammerList) => spammerList.join('\n');

/*********
* React Component Container
**********/
const App = connect((state, ownProps) => {
  return {
    patternInputValue: state.patternInputValue,
    patternChanged: !_.isEqual(state.committedSpammerList, state.spammerListFromPattern),
    spammerListInputValue: state.spammerListInputValue,
    spammerListChanged: !_.isEqual(state.committedSpammerList, state.spammerListFromList),
    spammerListItemCount: state.spammerListFromList.length,
  };
}, (dispatch, ownProps) => {
  return {
    //onIncrement: () => dispatch({ type: 'INCREMENT' }),
    //...
    onPatternChange: (event) => {
      dispatch({
        type: 'CHANGE_PATTERN_INPUT',
        value: event.target.value,
      });
    },
    onParsePattern: () => {
      dispatch({
        type: 'PARSE_PATTERN_INPUT',
      });
    },
    onSpammerListChange: (event) => {
      dispatch({
        type: 'CHANGE_SPAMMER_LIST_INPUT',
        value: event.target.value,
      });
    },
    onCommitSpammerList: () => {
      dispatch({
        type: 'COMMIT_SPAMMER_LIST_INPUT',
      });
    },
    onSortSpammerList: () => {
      dispatch({
        type: 'SORT_SPAMMER_LIST_INPUT',
      });
    },
  };
})(({
  patternInputValue,
  patternChanged,
  spammerListInputValue,
  spammerListChanged,
  spammerListItemCount,
  onPatternChange,
  onParsePattern,
  onSpammerListChange,
  onCommitSpammerList,
  onSortSpammerList,
}) => (
  <div>
    <fieldset className="input-fieldset">
      <legend>
        <label>Pattern</label>
        <button
          type="button"
          disabled={!patternChanged}
          onClick={onParsePattern}
        >Commit Changes</button>
      </legend>
      <input
        className={`pattern-input ${patternChanged ? 'pattern-input--changed' : ''}`}
        title={patternChanged ? 'Changes were made, remember to commit.' : ''}
        type="text"
        value={patternInputValue}
        onChange={onPatternChange}
      />
    </fieldset>

    <fieldset className="input-fieldset">
      <legend>
        <label>Spamers (one per line)</label>
        <button
          type="button"
          disabled={!spammerListChanged}
          onClick={onCommitSpammerList}
        >Commit Changes</button>
      </legend>
      <textarea
        className={`spammer-list-input ${spammerListChanged ? 'spammer-list-input--changed' : ''}`}
        title={spammerListChanged ? 'Changes were made, remember to commit.' : ''}
        rows="8"
        onChange={onSpammerListChange}
        value={spammerListInputValue}
      />
      <div>
        <label><span>{spammerListItemCount}</span> item(s).</label>
        <button type="button" onClick={onSortSpammerList}>Sort</button>
      </div>
    </fieldset>
  </div>
));


/*********
* State and Reducer
**********/
const initialState = (() => {
  const patternInputValue = 'label:spam from:(example@spam.it OR @allspam.me)';
  const spammerListFromPattern = parsePattern(patternInputValue);
  const committedSpammerList = spammerListFromPattern;
  const spammerListInputValue = committedSpammerList.join("\n");
  const spammerListFromList = getSpammerList(spammerListInputValue);
  
  return {
    patternInputValue,
    spammerListFromPattern,
    committedSpammerList,
    spammerListInputValue,
    spammerListFromList,
  };
})();
const reducer = (state, action) => {
  console.log({state, action});
  
  let newState = {...state};
  
  switch (action.type) {
    case '@@redux/INIT':
      // do nothing.
      break;
    case 'CHANGE_PATTERN_INPUT':
      newState.patternInputValue = action.value;
      newState.spammerListFromPattern = parsePattern(newState.patternInputValue);
      break;
    case 'CHANGE_SPAMMER_LIST_INPUT':
      newState.spammerListInputValue = action.value;
      newState.spammerListFromList = getSpammerList(newState.spammerListInputValue);
      break;
    case 'PARSE_PATTERN_INPUT':
      newState.patternInputValue = generatePattern(parsePattern(state.patternInputValue));
      newState.spammerListFromPattern = parsePattern(newState.patternInputValue);
      newState.committedSpammerList = newState.spammerListFromPattern;
      newState.spammerListFromList = newState.committedSpammerList;
      newState.spammerListInputValue = generateSpammerListString(newState.spammerListFromList);
      break;
    case 'COMMIT_SPAMMER_LIST_INPUT':
      newState.patternInputValue = generatePattern(getSpammerList(state.spammerListInputValue));
      newState.spammerListFromPattern = parsePattern(newState.patternInputValue);
      newState.committedSpammerList = newState.spammerListFromPattern;
      newState.spammerListFromList = newState.committedSpammerList;
      newState.spammerListInputValue = generateSpammerListString(newState.spammerListFromList);
      break;
    case 'SORT_SPAMMER_LIST_INPUT':
      newState.spammerListFromList = state.spammerListFromList.slice().sort(sortCompareSender);
      newState.spammerListInputValue = generateSpammerListString(newState.spammerListFromList);
      break;
    default:
      // do nothing.
  }
  
  console.log({newState});
  
  return newState;
};
const store = createStore(reducer, initialState);

/*********
* Render
**********/
const rootEl = document.getElementById('root');

ReactDOM.render(
  <App store={store} />,
  rootEl
);
              
            
!
999px

Console