Commit 405d6da8 authored by mxh's avatar mxh
Browse files

Issue #3276919 by mxh: Add a magic "filter" section variable

parent 31a3e27f
Loading
Loading
Loading
Loading

js/magic/filter.js

0 → 100644
+79 −0
Original line number Diff line number Diff line
/**
 * @file
 * Magic filters for Mustache templates.
 */

(function (sync) {
  var magicFilter = function (buffer, props) {
    return new Proxy(buffer, Object.assign({
      keys: [],
      available: {trim: 0, striptags: 0, nl2br: 0, spaceless: 0, upper: 0, lower: 0, capitalize: 0, truncate: 1},
      cloned: false,
      get: function (buffer, property, receiver) {
        if (!this.cloned) {
          return magicFilter(buffer, {cloned: true})[property];
        }
        this.keys.push(property);
        if (this.available[property]) {
          return receiver;
        }
        return function (wrapper) {
          return function(wrapper, text, render) {
            var k, m, param, rendered = render(text);
            for (var i = 0; i < wrapper.keys.length; i++) {
              k = wrapper.keys[i];
              m = wrapper[k];
              if ((typeof m === 'function') && (typeof wrapper.available[k] === 'number')) {
                if (wrapper.available[k]) {
                  param = wrapper.keys[i + 1];
                }
                rendered = m(rendered, param);
              }
            }
            return rendered;
          }.bind(wrapper, wrapper);
        }.bind(this, this);
      },
      has: function(target, prop) {
        return true;
      },
      trim: function (text) {
        return text.trim();
      },
      striptags: function (text) {
        var el = document.createElement('div');
        el.innerHTML = text;
        return el.textContent || el.innerText;
      },
      nl2br: function (text) {
        return text.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1<br/>$2');
      },
      spaceless: function (text) {
        return text.replace(/>\s+</g,'><').trim();
      },
      upper: function (text) {
        return text.toUpperCase();
      },
      lower: function (text) {
        return text.toLowerCase();
      },
      capitalize: function (text) {
        return text.charAt(0).toUpperCase() + text.slice(1);
      },
      truncate: function (text, size) {
        if (typeof size === 'string') {
          size = parseInt(size);
        }
        if ((typeof size === 'number') && (text.length > size)) {
          text = (text += " ").substring(0, size);
          text = text.substring(0, Math.min(text.length, text.lastIndexOf(" ")));
          text += '...';
        }
        return text;
      }
    }, props));
  };
  sync.registry.magic.filter = function (buffer) {
    return magicFilter(buffer, {});
  };
}(mustacheSync));

js/magic/filter.min.js

0 → 100644
+1 −0
Original line number Diff line number Diff line
!function(n){var t=function(n,e){return new Proxy(n,Object.assign({keys:[],available:{trim:0,striptags:0,nl2br:0,spaceless:0,upper:0,lower:0,capitalize:0,truncate:1},cloned:!1,get:function(n,e,r){return this.cloned?(this.keys.push(e),this.available[e]?r:function(n){return function(n,t,e){for(var r,i,u,a=e(t),s=0;s<n.keys.length;s++)"function"==typeof(i=n[r=n.keys[s]])&&"number"==typeof n.available[r]&&(n.available[r]&&(u=n.keys[s+1]),a=i(a,u));return a}.bind(n,n)}.bind(this,this)):t(n,{cloned:!0})[e]},has:function(n,t){return!0},trim:function(n){return n.trim()},striptags:function(n){var t=document.createElement("div");return t.innerHTML=n,t.textContent||t.innerText},nl2br:function(n){return n.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g,"$1<br/>$2")},spaceless:function(n){return n.replace(/>\s+</g,"><").trim()},upper:function(n){return n.toUpperCase()},lower:function(n){return n.toLowerCase()},capitalize:function(n){return n.charAt(0).toUpperCase()+n.slice(1)},truncate:function(n,t){return"string"==typeof t&&(t=parseInt(t)),"number"==typeof t&&n.length>t&&(n=(n=(n+=" ").substring(0,t)).substring(0,Math.min(n.length,n.lastIndexOf(" "))),n+="..."),n}},e))};n.registry.magic.filter=function(n){return t(n,{})}}(mustacheSync);
 No newline at end of file
+6 −0
Original line number Diff line number Diff line
@@ -173,3 +173,9 @@ mustache_test.page_magic_sync_into_somewhere_else:
    _controller: '\Drupal\mustache_test\Controller\MustacheTestMagicController::pageSyncIntoSomewhereElse'
  requirements:
    _access: 'TRUE'
mustache_test.page_magic_filters:
  path: '/mustache-test/magic-filters'
  defaults:
    _controller: '\Drupal\mustache_test\Controller\MustacheTestMagicController::pageFilters'
  requirements:
    _access: 'TRUE'
+67 −0
Original line number Diff line number Diff line
@@ -109,4 +109,71 @@ class MustacheTestMagicController {
    return $render;
  }

  /**
   * Returns a plain page for testing magic filters.
   *
   * @return array
   *   A build array for rendering the Mustache template(s).
   */
  public function pageFilters() {
    $render_array = [];

    $render_array[] = MustacheRenderTemplate::build('filter_template_1', 'filter.trim: {{#filter.trim}}          Hello!       {{/filter.trim}}')
    ->withClientSynchronization()
    ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];

    $render_array[] = MustacheRenderTemplate::build('filter_template_2', 'filter.striptags: {{#filter.striptags}}<h1><strong>Hello</strong> <span>there!</span></h1>{{/filter.striptags}}')
      ->withClientSynchronization()
      ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];

    $render_array[] = MustacheRenderTemplate::build('filter_template_3', "filter.nl2br: {{#filter.nl2br}}Hello\nthere!{{/filter.nl2br}}")
      ->withClientSynchronization()
      ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];

    $render_array[] = MustacheRenderTemplate::build('filter_template_4', 'filter.spaceless: {{#filter.spaceless}}<p> <b>Hello there! </b></p>{{/filter.spaceless}}')
      ->withClientSynchronization()
      ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];

    $render_array[] = MustacheRenderTemplate::build('filter_template_5', 'filter.upper: {{#filter.upper}}Hello!{{/filter.upper}}')
      ->withClientSynchronization()
      ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];

    $render_array[] = MustacheRenderTemplate::build('filter_template_6', 'filter.lower: {{#filter.lower}}Hello!{{/filter.lower}}')
      ->withClientSynchronization()
      ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];

    $render_array[] = MustacheRenderTemplate::build('filter_template_7', 'filter.capitalize: {{#filter.capitalize}}hello!{{/filter.capitalize}}')
      ->withClientSynchronization()
      ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];

    $render_array[] = MustacheRenderTemplate::build('filter_template_8', 'filter.truncate (no change): {{#filter.truncate}}aaaaa bbbbbbb ccccccccc dddddddd eeee fffffffff ggggg{{/filter.truncate}}')
      ->withClientSynchronization()
      ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];

    $render_array[] = MustacheRenderTemplate::build('filter_template_9', 'filter.truncate.30: {{#filter.truncate.30}}aaaaa bbbbbbb ccccccccc dddddddd eeee fffffffff ggggg{{/filter.truncate.30}}')
      ->withClientSynchronization()
      ->toRenderArray();

    $render_array[] = ['#markup' => Markup::create('<hr/>')];
    $render_array[] = ['#markup' => TestLinks::get()];

    return $render_array;
  }

}
+1 −0
Original line number Diff line number Diff line
@@ -40,6 +40,7 @@ abstract class TestLinks {
    $output .= '<li><a href="/mustache-test/magic-sync-inline-tokens-limited">Magic synchronization (inline, limited, /magic-sync-inline-tokens-limited)</a></li>';
    $output .= '<li><a href="/mustache-test/magic-sync-inline-tokens-interactive">Magic synchronization (inline, interactive, /magic-sync-inline-tokens-interactive)</a></li>';
    $output .= '<li><a href="/mustache-test/magic-sync-somewhere-else">Magic synchronization somewhere else (inline, /magic-sync-somewhere-else)</a></li>';
    $output .= '<li><a href="/mustache-test/magic-filters">Magic filters (/magic-filters)</a></li>';
    $output .= '</ul>';
    return Markup::create($output);
  }
Loading