Skip to:
Content

BuddyPress.org

Ticket #8521: 8521.patch

File 8521.patch, 71.9 KB (added by imath, 5 years ago)
  • .jshintignore

    diff --git .jshintignore .jshintignore
    index 7aef61f3c..06a8e1509 100644
    src/**/js/blocks/**/*.js  
    88src/**/js/block-*/*.js
    99src/**/js/block-*/**/*.js
    1010src/**/js/block-*.js
     11src/**/js/friends.js
     12src/**/js/dynamic-widget-block.js
  • Gruntfile.js

    diff --git Gruntfile.js Gruntfile.js
    index bb010cd0c..3417b09fd 100644
    module.exports = function( grunt ) {  
    2222                        '!**/js/blocks/**/*.js',
    2323                        '!**/js/block-*/*.js',
    2424                        '!**/js/block-*/**/*.js',
    25                         '!**/js/block-*.js'
     25                        '!**/js/block-*.js',
     26                        '!**/js/friends.js',
     27                        '!**/js/dynamic-widget-block.js'
    2628                ],
    2729
    2830                BP_EXCLUDED_MISC = [
    … … module.exports = function( grunt ) {  
    4042                        '!bp-members/css/blocks/members.css',
    4143                        '!bp-groups/css/blocks/groups.css',
    4244                        '!bp-core/css/blocks/login-form.css',
    43                         '!bp-activity/css/blocks/latest-activities.css'
     45                        '!bp-activity/css/blocks/latest-activities.css',
     46                        '!bp-friends/css/blocks/friends.css'
    4447                ],
    4548
    4649                autoprefixer = require('autoprefixer');
    … … module.exports = function( grunt ) {  
    168171                                flatten: true,
    169172                                src: ['bp-activity/sass/blocks/*.scss'],
    170173                                dest: SOURCE_DIR + 'bp-activity/css/blocks/'
     174                        },
     175                        friends_blocks: {
     176                                cwd: SOURCE_DIR,
     177                                extDot: 'last',
     178                                expand: true,
     179                                ext: '.css',
     180                                flatten: true,
     181                                src: ['bp-friends/sass/blocks/*.scss'],
     182                                dest: SOURCE_DIR + 'bp-friends/css/blocks/'
    171183                        }
    172184                },
    173185                rtlcss: {
  • package.json

    diff --git package.json package.json
    index ae389d9ca..d47a53eeb 100644
     
    4040                "npm": ">=6.14.8"
    4141        },
    4242        "scripts": {
    43                 "start": "npm run dev:components && parcel watch src/js/bp-*/*s/blocks/*.js --out-dir src --no-source-maps",
    44                 "dev": "npm run dev:components && parcel build src/js/bp-*/*s/blocks/*.js --out-dir src --no-source-maps --no-minify",
    45                 "build": "npm run build:components && parcel build src/js/bp-*/*s/blocks/*.js --out-dir build",
     43                "start": "npm run dev:components && npm run dev:assets && parcel watch src/js/bp-*/*s/blocks/*.js --out-dir src --no-source-maps",
     44                "dev": "npm run dev:components && npm run dev:assets && npm run dev:scripts && parcel build src/js/bp-*/*s/blocks/*.js --out-dir src --no-source-maps --no-minify",
     45                "build": "npm run build:components && npm run build:assets  && npm run build:scripts && parcel build src/js/bp-*/*s/blocks/*.js --out-dir build",
    4646                "watch:components": "parcel watch src/js/bp-core/js/block-components/block-components.js --out-dir src/bp-core/js --out-file block-components.js --no-source-maps --global bpBlock",
    4747                "dev:components": "parcel build src/js/bp-core/js/block-components/block-components.js --out-dir src/bp-core/js --out-file block-components.js --no-source-maps --no-minify --global bpBlock",
    4848                "build:components": "parcel build src/js/bp-core/js/block-components/block-components.js --out-dir build/bp-core/js --out-file block-components.js --global bpBlock",
    4949                "watch:assets": "parcel watch src/js/bp-core/js/block-assets/*.js --out-dir src/bp-core/js --no-source-maps --global bpBlock",
    5050                "dev:assets": "parcel build src/js/bp-core/js/block-assets/*.js --out-dir src/bp-core/js --no-source-maps --no-minify --global bpBlock",
    5151                "build:assets": "parcel build src/js/bp-core/js/block-assets/*.js --out-dir build/bp-core/js --global bpBlock",
     52                "dev:scripts": "parcel build src/js/bp-*/*s/* --out-dir src --no-source-maps --no-minify",
     53                "build:scripts": "parcel build src/js/bp-*/*s/* --out-dir build",
    5254                "wp-env": "wp-env",
    5355                "test-php": "npm run wp-env run phpunit 'php /var/www/html/wp-content/plugins/buddypress/vendor/phpunit/phpunit/phpunit -c /var/www/html/wp-content/plugins/buddypress/tests/phpunit/env.xml'",
    5456                "test-php:group": "npm run wp-env run phpunit 'php /var/www/html/wp-content/plugins/buddypress/vendor/phpunit/phpunit/phpunit -c /var/www/html/wp-content/plugins/buddypress/tests/phpunit/env.xml --group $npm_confi_g'",
  • src/bp-activity/js/blocks/embed-activity.js

    diff --git src/bp-activity/js/blocks/embed-activity.js src/bp-activity/js/blocks/embed-activity.js
    index 5f481a7a1..fc3a737c8 100644
    parcelRequire = (function (modules, cache, entry, globalName) {  
    117117  }
    118118
    119119  return newRequire;
    120 })({"dEOc":[function(require,module,exports) {
     120})({"DCTP":[function(require,module,exports) {
    121121function _arrayWithHoles(arr) {
    122122  if (Array.isArray(arr)) return arr;
    123123}
    124124
    125125module.exports = _arrayWithHoles;
    126 },{}],"RonT":[function(require,module,exports) {
     126},{}],"LoeL":[function(require,module,exports) {
    127127function _iterableToArrayLimit(arr, i) {
    128128  if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
    129129  var _arr = [];
    … … function _iterableToArrayLimit(arr, i) {  
    152152}
    153153
    154154module.exports = _iterableToArrayLimit;
    155 },{}],"LGpM":[function(require,module,exports) {
     155},{}],"jEQo":[function(require,module,exports) {
    156156function _arrayLikeToArray(arr, len) {
    157157  if (len == null || len > arr.length) len = arr.length;
    158158
    … … function _arrayLikeToArray(arr, len) {  
    164164}
    165165
    166166module.exports = _arrayLikeToArray;
    167 },{}],"Vzqv":[function(require,module,exports) {
     167},{}],"Dbv9":[function(require,module,exports) {
    168168var arrayLikeToArray = require("./arrayLikeToArray");
    169169
    170170function _unsupportedIterableToArray(o, minLen) {
    … … function _unsupportedIterableToArray(o, minLen) {  
    177177}
    178178
    179179module.exports = _unsupportedIterableToArray;
    180 },{"./arrayLikeToArray":"LGpM"}],"sa4T":[function(require,module,exports) {
     180},{"./arrayLikeToArray":"jEQo"}],"MWEO":[function(require,module,exports) {
    181181function _nonIterableRest() {
    182182  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    183183}
    184184
    185185module.exports = _nonIterableRest;
    186 },{}],"xkYc":[function(require,module,exports) {
     186},{}],"DERy":[function(require,module,exports) {
    187187var arrayWithHoles = require("./arrayWithHoles");
    188188
    189189var iterableToArrayLimit = require("./iterableToArrayLimit");
    … … function _slicedToArray(arr, i) {  
    197197}
    198198
    199199module.exports = _slicedToArray;
    200 },{"./arrayWithHoles":"dEOc","./iterableToArrayLimit":"RonT","./unsupportedIterableToArray":"Vzqv","./nonIterableRest":"sa4T"}],"Sjre":[function(require,module,exports) {
     200},{"./arrayWithHoles":"DCTP","./iterableToArrayLimit":"LoeL","./unsupportedIterableToArray":"Dbv9","./nonIterableRest":"MWEO"}],"Sjre":[function(require,module,exports) {
    201201"use strict";
    202202
    203203Object.defineProperty(exports, "__esModule", {
    … … var editEmbedActivityBlock = compose([withSelect(function (select, ownProps) {  
    363363})])(EditEmbedActivity);
    364364var _default = editEmbedActivityBlock;
    365365exports.default = _default;
    366 },{"@babel/runtime/helpers/slicedToArray":"xkYc"}],"zmBI":[function(require,module,exports) {
     366},{"@babel/runtime/helpers/slicedToArray":"DERy"}],"zmBI":[function(require,module,exports) {
    367367"use strict";
    368368
    369369Object.defineProperty(exports, "__esModule", {
  • src/bp-core/bp-core-cssjs.php

    diff --git src/bp-core/bp-core-cssjs.php src/bp-core/bp-core-cssjs.php
    index c8d34388d..56b6c9f09 100644
    function bp_core_register_common_scripts() {  
    8585                // Version 2.7.
    8686                'bp-moment'    => array( 'file' => "{$url}vendor/moment-js/moment{$min}.js", 'dependencies' => array(), 'footer' => true ),
    8787                'bp-livestamp' => array( 'file' => "{$url}vendor/livestamp{$min}.js", 'dependencies' => array( 'jquery', 'bp-moment' ), 'footer' => true ),
     88
     89                // Version 9.0.
     90                'bp-dynamic-widget-block-script' => array( 'file' => "{$url}dynamic-widget-block.js", 'dependencies' => array( 'lodash', 'wp-url' ), 'footer' => true ),
    8891        );
    8992
    9093        // Version 2.7 - Add Moment.js locale to our $scripts array if we found one.
  • src/bp-core/bp-core-template-loader.php

    diff --git src/bp-core/bp-core-template-loader.php src/bp-core/bp-core-template-loader.php
    index 9191e2915..eed2d9df5 100644
    function bp_get_asset_template_part( $slug, $name = null, $args = array() ) {  
    8787        return bp_get_template_part( "assets/{$slug}", $name, $args );
    8888}
    8989
     90/**
     91 * Get a dynamic template part.
     92 *
     93 * @since 9.0.0
     94 *
     95 * @param string $template     The Template Pack's relative path to the templata.
     96 *                             Optional.
     97 * @param string $type         Whether to use the template for JavaScript or PHP.
     98 *                             Optional. Defaults to `js`.
     99 * @param array  $tokens       The data to use to customize the template. Optional.
     100 * @param array  $allowed_tags The allowed tags to use. Optional.
     101 * @return string HTML/JS output.
     102 */
     103function bp_get_dynamic_template_part( $template = '', $type = 'js', $tokens = array(), $allowed_tags = array() ) {
     104        $template_string = '';
     105
     106        if ( ! $template ) {
     107                return '';
     108        }
     109
     110        // Use the BP Theme Compat API to allow template override.
     111        $template_path = bp_locate_template( $template );
     112        if ( $template_path ) {
     113                $template_string = file_get_contents( $template_path );
     114        }
     115
     116        if ( ! $template_string ) {
     117                return '';
     118        }
     119
     120        if ( ! $allowed_tags ) {
     121                $allowed_tags = array(
     122                        'li'   => array( 'class' => true ),
     123                        'div'  => array( 'class' => true ),
     124                        'span' => array( 'class' => true ),
     125                        'a'    => array(
     126                                'href'            => true,
     127                                'class'           => true,
     128                                'data-bp-tooltip' => true,
     129                        ),
     130                        'img'  => array(
     131                                'src'     => true,
     132                                'class'   => true,
     133                                'loading' => true,
     134                        ),
     135                );
     136        }
     137
     138        if ( 'js' !== $type ) {
     139                $template_string = wp_kses( $template_string, $allowed_tags );
     140
     141                return bp_core_replace_tokens_in_text( $template_string, $tokens );
     142        }
     143
     144        return $template_string;
     145}
     146
    90147/**
    91148 * Retrieve the name of the highest priority template file that exists.
    92149 *
  • new file src/bp-core/js/dynamic-widget-block.js

    diff --git src/bp-core/js/dynamic-widget-block.js src/bp-core/js/dynamic-widget-block.js
    new file mode 100644
    index 000000000..dfe59fefc
    - +  
     1// modules are defined as an array
     2// [ module function, map of requires ]
     3//
     4// map of requires is short require name -> numeric require
     5//
     6// anything defined in a previous bundle is accessed via the
     7// orig method which is the require for previous bundles
     8parcelRequire = (function (modules, cache, entry, globalName) {
     9  // Save the require from previous bundle to this closure if any
     10  var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
     11  var nodeRequire = typeof require === 'function' && require;
     12
     13  function newRequire(name, jumped) {
     14    if (!cache[name]) {
     15      if (!modules[name]) {
     16        // if we cannot find the module within our internal map or
     17        // cache jump to the current global require ie. the last bundle
     18        // that was added to the page.
     19        var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
     20        if (!jumped && currentRequire) {
     21          return currentRequire(name, true);
     22        }
     23
     24        // If there are other bundles on this page the require from the
     25        // previous one is saved to 'previousRequire'. Repeat this as
     26        // many times as there are bundles until the module is found or
     27        // we exhaust the require chain.
     28        if (previousRequire) {
     29          return previousRequire(name, true);
     30        }
     31
     32        // Try the node require function if it exists.
     33        if (nodeRequire && typeof name === 'string') {
     34          return nodeRequire(name);
     35        }
     36
     37        var err = new Error('Cannot find module \'' + name + '\'');
     38        err.code = 'MODULE_NOT_FOUND';
     39        throw err;
     40      }
     41
     42      localRequire.resolve = resolve;
     43      localRequire.cache = {};
     44
     45      var module = cache[name] = new newRequire.Module(name);
     46
     47      modules[name][0].call(module.exports, localRequire, module, module.exports, this);
     48    }
     49
     50    return cache[name].exports;
     51
     52    function localRequire(x){
     53      return newRequire(localRequire.resolve(x));
     54    }
     55
     56    function resolve(x){
     57      return modules[name][1][x] || x;
     58    }
     59  }
     60
     61  function Module(moduleName) {
     62    this.id = moduleName;
     63    this.bundle = newRequire;
     64    this.exports = {};
     65  }
     66
     67  newRequire.isParcelRequire = true;
     68  newRequire.Module = Module;
     69  newRequire.modules = modules;
     70  newRequire.cache = cache;
     71  newRequire.parent = previousRequire;
     72  newRequire.register = function (id, exports) {
     73    modules[id] = [function (require, module) {
     74      module.exports = exports;
     75    }, {}];
     76  };
     77
     78  var error;
     79  for (var i = 0; i < entry.length; i++) {
     80    try {
     81      newRequire(entry[i]);
     82    } catch (e) {
     83      // Save first error but execute all entries
     84      if (!error) {
     85        error = e;
     86      }
     87    }
     88  }
     89
     90  if (entry.length) {
     91    // Expose entry point to Node, AMD or browser globals
     92    // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
     93    var mainExports = newRequire(entry[entry.length - 1]);
     94
     95    // CommonJS
     96    if (typeof exports === "object" && typeof module !== "undefined") {
     97      module.exports = mainExports;
     98
     99    // RequireJS
     100    } else if (typeof define === "function" && define.amd) {
     101     define(function () {
     102       return mainExports;
     103     });
     104
     105    // <script>
     106    } else if (globalName) {
     107      this[globalName] = mainExports;
     108    }
     109  }
     110
     111  // Override the current require with this new one
     112  parcelRequire = newRequire;
     113
     114  if (error) {
     115    // throw error from earlier, _after updating parcelRequire_
     116    throw error;
     117  }
     118
     119  return newRequire;
     120})({"eNhW":[function(require,module,exports) {
     121function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
     122
     123function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
     124
     125function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
     126
     127/**
     128 * WordPress dependencies.
     129 */
     130var _wp = wp,
     131    addQueryArgs = _wp.url.addQueryArgs;
     132/**
     133 * External dependencies.
     134 */
     135
     136var _lodash = lodash,
     137    template = _lodash.template; // Use the bp global.
     138
     139window.bp = window.bp || {};
     140/**
     141 * Generic class to be used by Dynamic Widget Blocks.
     142 *
     143 * @since 9.0.0
     144 */
     145
     146bp.dynamicWidgetBlock = /*#__PURE__*/function () {
     147  function bpDynamicWidgetBlock(settings, blocks) {
     148    var _this = this;
     149
     150    _classCallCheck(this, bpDynamicWidgetBlock);
     151
     152    var path = settings.path,
     153        root = settings.root,
     154        nonce = settings.nonce;
     155    this.path = path;
     156    this.root = root;
     157    this.nonce = nonce, this.blocks = blocks;
     158    this.blocks.forEach(function (block, i) {
     159      var _ref = block.query_args || 'active',
     160          type = _ref.type;
     161
     162      var _ref2 = block.preloaded || [],
     163          body = _ref2.body;
     164
     165      _this.blocks[i].items = {
     166        'active': [],
     167        'newest': [],
     168        'popular': [],
     169        'alphabetical': []
     170      };
     171
     172      if (!_this.blocks[i].items[type].length && body && body.length) {
     173        _this.blocks[i].items[type] = body;
     174      }
     175    });
     176  }
     177
     178  _createClass(bpDynamicWidgetBlock, [{
     179    key: "useTemplate",
     180    value: function useTemplate(tmpl) {
     181      var options = {
     182        evaluate: /<#([\s\S]+?)#>/g,
     183        interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
     184        escape: /\{\{([^\}]+?)\}\}(?!\})/g,
     185        variable: 'data'
     186      };
     187      return template(document.querySelector('#tmpl-' + tmpl).innerHTML, options);
     188    }
     189  }, {
     190    key: "loop",
     191    value: function loop() {// This method needs to be overriden.
     192    }
     193  }, {
     194    key: "getItems",
     195    value: function getItems() {
     196      var _this2 = this;
     197
     198      var type = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'active';
     199      var blockIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
     200      this.blocks[blockIndex].query_args.type = type;
     201
     202      if (this.blocks[blockIndex].items[type].length) {
     203        this.loop(this.blocks[blockIndex].items[type], this.blocks[blockIndex].selector, type);
     204      } else {
     205        fetch(addQueryArgs(this.root + this.path, this.blocks[blockIndex].query_args), {
     206          method: 'GET',
     207          headers: {
     208            'X-WP-Nonce': this.nonce
     209          }
     210        }).then(function (response) {
     211          return response.json();
     212        }).then(function (data) {
     213          _this2.blocks[blockIndex].items[type] = data;
     214
     215          _this2.loop(_this2.blocks[blockIndex].items[type], _this2.blocks[blockIndex].selector, type);
     216        });
     217      }
     218    }
     219  }]);
     220
     221  return bpDynamicWidgetBlock;
     222}();
     223},{}]},{},["eNhW"], null)
     224 No newline at end of file
  • new file src/bp-friends/bp-friends-blocks.php

    diff --git src/bp-friends/bp-friends-blocks.php src/bp-friends/bp-friends-blocks.php
    new file mode 100644
    index 000000000..876bc46d3
    - +  
     1<?php
     2/**
     3 * BP Friends Blocks Functions.
     4 *
     5 * @package BuddyPress
     6 * @subpackage FriendsBlocks
     7 * @since 9.0.0
     8 */
     9
     10// Exit if accessed directly.
     11if ( ! defined( 'ABSPATH' ) ) {
     12        exit;
     13}
     14
     15/**
     16 * Adds specific script data for the BP Friends blocks.
     17 *
     18 * Only used for the BP Friends block.
     19 *
     20 * @since 9.0.0
     21 */
     22function bp_friends_blocks_add_script_data() {
     23        $friends_blocks = array_filter( buddypress()->friends->block_globals['bp/friends']->items );
     24
     25        if ( ! $friends_blocks ) {
     26                return;
     27        }
     28
     29        // Include the common JS template.
     30        echo bp_get_dynamic_template_part( 'assets/widgets/friends.php' );
     31
     32        // List the block specific props.
     33        wp_add_inline_script(
     34                'bp-friends-script',
     35                sprintf( 'var bpFriendsBlocks = %s;', wp_json_encode( array_values( $friends_blocks ) ) ),
     36                'before'
     37        );
     38}
     39
     40/**
     41 * Callback function to render the BP Friends Block.
     42 *
     43 * @since 9.0.0
     44 *
     45 * @param array $attributes The block attributes.
     46 * @return string           HTML output.
     47 */
     48function bp_friends_render_friends_block( $attributes = array() ) {
     49        $block_args = wp_parse_args(
     50                $attributes,
     51                array(
     52                        'maxFriends'    => 5,
     53                        'friendDefault' => 'active',
     54                        'linkTitle'     => false,
     55                        'postId'        => 0, // If the postId attribute is defined, post author friends are needed.
     56                )
     57        );
     58
     59        $user_id = 0;
     60        if ( $block_args['postId'] ) {
     61                $user_id = (int) get_post_field( 'post_author', $block_args['postId'] );
     62        } else {
     63                $user_id = bp_displayed_user_id();
     64
     65                if ( ! $user_id && isset( $_SERVER['REQUEST_URI'] ) ) {
     66                        $request_uri  = esc_url_raw( wp_unslash( $_SERVER['REQUEST_URI'] ) );
     67                        $request_path = wp_parse_url( $request_uri, PHP_URL_PATH );
     68                        $regex        = addcslashes( sprintf( '%s/.*bp/friends', rest_get_url_prefix() ), '/' );
     69
     70                        if ( preg_match( "/{$regex}/", $request_path ) ) {
     71                                $user_id = bp_loggedin_user_id();
     72                        }
     73                }
     74        }
     75
     76        if ( ! $user_id ) {
     77                return '';
     78        }
     79
     80        $classnames         = 'widget_bp_core_friends_widget buddypress widget';
     81        $wrapper_attributes = get_block_wrapper_attributes( array( 'class' => $classnames ) );
     82
     83        $max_friends = (int) $block_args['maxFriends'];
     84        $no_friends  = __( 'Sorry, no members were found.', 'buddypress' );
     85
     86        /**
     87         * Filters the separator of the friends block nav links.
     88         *
     89         * @since 9.0.0
     90         *
     91         * @param string $separator Separator string. Default '|'.
     92         */
     93        $separator = apply_filters( 'bp_friends_block_nav_links_separator', '|' );
     94
     95        // Make sure the widget ID is unique.
     96        $widget_id = uniqid( 'friends-list-' );
     97
     98        $link = trailingslashit( bp_core_get_user_domain( $user_id ) . bp_get_friends_slug() );
     99
     100        /* translators: %s is the member's display name */
     101        $title = sprintf( __( '%s\'s Friends', 'buddypress' ), bp_core_get_user_displayname( $user_id ) );
     102
     103        // Set the Block's title.
     104        if ( true === $block_args['linkTitle'] ) {
     105                $widget_content = sprintf(
     106                        '<h2 class="widget-title"><a href="%1$s">%2$s</a></h2>',
     107                        esc_url( $link ),
     108                        esc_html( $title )
     109                );
     110        } else {
     111                $widget_content = sprintf( '<h2 class="widget-title">%s</h2>', esc_html( $title ) );
     112        }
     113
     114        $item_options = array(
     115                'newest'  => array(
     116                        'class' => '',
     117                        'label' => __( 'Newest', 'buddypress' ),
     118                ),
     119                'active'  => array(
     120                        'class' => '',
     121                        'label' => __( 'Active', 'buddypress' ),
     122                ),
     123                'popular' => array(
     124                        'class' => '',
     125                        'label' => __( 'Popular', 'buddypress' ),
     126                ),
     127        );
     128
     129        $item_options_output = array();
     130        $separator_output    = sprintf( ' <span class="bp-separator" role="separator">%s</span> ', esc_html( $separator ) );
     131
     132        foreach ( $item_options as $item_type => $item_attr ) {
     133                if ( $block_args['friendDefault'] === $item_type ) {
     134                        $item_attr['class'] = ' class="selected"';
     135                }
     136
     137                $item_options_output[] = sprintf(
     138                        '<a href="%1$s" data-bp-sort="%2$s"%3$s>%4$s</a>',
     139                        esc_url( $link ),
     140                        esc_attr( $item_type ),
     141                        $item_attr['class'],
     142                        esc_html( $item_attr['label'] )
     143                );
     144        }
     145
     146        $preview      = '';
     147        $default_args = array(
     148                'user_id'         => $user_id,
     149                'type'            => $block_args['friendDefault'],
     150                'per_page'        => $max_friends,
     151                'populate_extras' => true,
     152        );
     153
     154        // Previewing the Block inside the editor.
     155        if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
     156                $bp_query = bp_core_get_users( $default_args );
     157                $preview  = sprintf( '<div class="widget-error">%s</div>', $no_friends );
     158
     159                if ( is_array( $bp_query['users'] ) && 0 < count( $bp_query['users'] ) ) {
     160                        $preview = '';
     161                        foreach ( $bp_query['users'] as $user ) {
     162                                if ( 'newest' === $block_args['friendDefault'] ) {
     163                                        /* translators: %s is time elapsed since the registration date happened */
     164                                        $extra = sprintf( _x( 'Registered %s', 'The timestamp when the user registered', 'buddypress' ), bp_core_time_since( $user->user_registered ) );
     165                                } elseif ( 'popular' === $block_args['friendDefault'] && isset( $item_options['popular'] ) && isset( $user->total_friend_count ) ) {
     166                                        /* translators: %s: total friend count */
     167                                        $extra = sprintf( _n( '%s friend', '%s friends', $user->total_friend_count, 'buddypress' ), number_format_i18n( $user->total_friend_count ) );
     168                                } else {
     169                                        /* translators: %s: a human time diff. */
     170                                        $extra = sprintf( __( 'Active %s', 'buddypress' ), bp_core_time_since( $user->last_activity ) );
     171                                }
     172
     173                                $preview .= bp_get_dynamic_template_part(
     174                                        'assets/widgets/friends.php',
     175                                        'php',
     176                                        array(
     177                                                'data.link'              => bp_core_get_user_domain( $user->ID, $user->user_nicename, $user->user_login ),
     178                                                'data.name'              => $user->display_name,
     179                                                'data.avatar_urls.thumb' => bp_core_fetch_avatar(
     180                                                        array(
     181                                                                'item_id' => $user->ID,
     182                                                                'html'    => false,
     183                                                        )
     184                                                ),
     185                                                'data.avatar_alt'        => esc_html(
     186                                                        sprintf(
     187                                                                /* translators: %s: member name */
     188                                                                __( 'Profile picture of %s', 'buddypress' ),
     189                                                                $user->display_name
     190                                                        )
     191                                                ),
     192                                                'data.id'                => $user->ID,
     193                                                'data.extra'             => $extra,
     194                                        )
     195                                );
     196                        }
     197                }
     198        } else {
     199                // Get corresponding friends.
     200                $path = sprintf(
     201                        '/%1$s/%2$s/%3$s',
     202                        bp_rest_namespace(),
     203                        bp_rest_version(),
     204                        buddypress()->members->id
     205                );
     206
     207                $default_path = add_query_arg(
     208                        $default_args,
     209                        $path
     210                );
     211
     212                $preloaded_friends = array();
     213                if ( bp_is_running_wp( '5.0.0' ) ) {
     214                        $preloaded_friends = rest_preload_api_request( '', $default_path );
     215                }
     216
     217                buddypress()->friends->block_globals['bp/friends']->items[ $widget_id ] = (object) array(
     218                        'selector'   => $widget_id,
     219                        'query_args' => $default_args,
     220                        'preloaded'  => reset( $preloaded_friends ),
     221                );
     222
     223                // Only enqueue common/specific scripts and data once per page load.
     224                if ( ! has_action( 'wp_footer', 'bp_friends_blocks_add_script_data', 1 ) ) {
     225                        wp_set_script_translations( 'bp-friends-script', 'buddypress' );
     226                        wp_enqueue_script( 'bp-friends-script' );
     227                        wp_localize_script(
     228                                'bp-friends-script',
     229                                'bpFriendsSettings',
     230                                array(
     231                                        'path'  => ltrim( $path, '/' ),
     232                                        'root'  => esc_url_raw( get_rest_url() ),
     233                                        'nonce' => wp_create_nonce( 'wp_rest' ),
     234                                )
     235                        );
     236
     237                        add_action( 'wp_footer', 'bp_friends_blocks_add_script_data', 1 );
     238                }
     239        }
     240
     241        $widget_content .= sprintf(
     242                '<div class="item-options">
     243                        %1$s
     244                </div>
     245                <ul id="%2$s" class="item-list" aria-live="polite" aria-relevant="all" aria-atomic="true">
     246                        %3$s
     247                </ul>',
     248                implode( $separator_output, $item_options_output ),
     249                esc_attr( $widget_id ),
     250                $preview
     251        );
     252
     253        // Adds a container to make sure the block is styled even when used into the Columns parent block.
     254        $widget_content = sprintf( '<div class="bp-dynamic-block-container">%s</div>', "\n" . $widget_content . "\n" );
     255
     256        // Only add a block wrapper if not loaded into a Widgets sidebar.
     257        if ( ! did_action( 'dynamic_sidebar_before' ) ) {
     258                return sprintf(
     259                        '<div %1$s>%2$s</div>',
     260                        $wrapper_attributes,
     261                        $widget_content
     262                );
     263        }
     264
     265        return $widget_content;
     266}
  • new file src/bp-friends/bp-friends-cssjs.php

    diff --git src/bp-friends/bp-friends-cssjs.php src/bp-friends/bp-friends-cssjs.php
    new file mode 100644
    index 000000000..8e97d3d57
    - +  
     1<?php
     2/**
     3 * BP Friends component CSS/JS.
     4 *
     5 * @package BuddyPress
     6 * @subpackage FriendsScripts
     7 * @since 9.0.0
     8 */
     9
     10// Exit if accessed directly.
     11if ( ! defined( 'ABSPATH' ) ) {
     12        exit;
     13}
     14
     15/**
     16 * Registers the script to manage the dynamic part of the Friends widget/block.
     17 *
     18 * @since 9.0.0
     19 *
     20 * @param array $scripts Data about the scripts to register.
     21 * @return array Data about the scripts to register.
     22 */
     23function bp_friends_register_scripts( $scripts = array() ) {
     24        $scripts['bp-friends-script'] = array(
     25                'file'         => plugins_url( 'js/friends.js', __FILE__ ),
     26                'dependencies' => array(
     27                        'bp-dynamic-widget-block-script',
     28                        'wp-i18n',
     29                ),
     30                'footer'       => true,
     31        );
     32
     33        return $scripts;
     34}
     35add_filter( 'bp_core_register_common_scripts', 'bp_friends_register_scripts', 9, 1 );
  • src/bp-friends/classes/class-bp-friends-component.php

    diff --git src/bp-friends/classes/class-bp-friends-component.php src/bp-friends/classes/class-bp-friends-component.php
    index 29594f04a..c0091c67d 100644
    class BP_Friends_Component extends BP_Component {  
    4646         */
    4747        public function includes( $includes = array() ) {
    4848                $includes = array(
     49                        'cssjs',
    4950                        'cache',
    5051                        'filters',
    5152                        'template',
    5253                        'functions',
    5354                        'widgets',
     55                        'blocks',
    5456                );
    5557
    5658                // Conditional includes.
    … … class BP_Friends_Component extends BP_Component {  
    133135                        'has_directory'         => false,
    134136                        'search_string'         => __( 'Search Friends...', 'buddypress' ),
    135137                        'notification_callback' => 'friends_format_notifications',
    136                         'global_tables'         => $global_tables
     138                        'global_tables'         => $global_tables,
     139                        'block_globals'         => array(
     140                                'bp/friends' => array(
     141                                        'widget_classnames' => array( 'widget_bp_core_friends_widget', 'buddypress' ),
     142                                )
     143                        ),
    137144                );
    138145
    139146                parent::setup_globals( $args );
    … … class BP_Friends_Component extends BP_Component {  
    347354         *                      description.
    348355         */
    349356        public function blocks_init( $blocks = array() ) {
    350                 parent::blocks_init( array() );
     357                parent::blocks_init(
     358                        array(
     359                                'bp/friends' => array(
     360                                        'name'               => 'bp/friends',
     361                                        'editor_script'      => 'bp-friends-block',
     362                                        'editor_script_url'  => plugins_url( 'js/blocks/friends.js', dirname( __FILE__ ) ),
     363                                        'editor_script_deps' => array(
     364                                                'wp-blocks',
     365                                                'wp-element',
     366                                                'wp-components',
     367                                                'wp-i18n',
     368                                                'wp-block-editor',
     369                                                'bp-block-data',
     370                                                'bp-block-components',
     371                                        ),
     372                                        'style'              => 'bp-friends-block',
     373                                        'style_url'          => plugins_url( 'css/blocks/friends.css', dirname( __FILE__ ) ),
     374                                        'attributes'         => array(
     375                                                'maxFriends'    => array(
     376                                                        'type'    => 'number',
     377                                                        'default' => 5,
     378                                                ),
     379                                                'friendDefault' => array(
     380                                                        'type'    => 'string',
     381                                                        'default' => 'active',
     382                                                ),
     383                                                'linkTitle'     => array(
     384                                                        'type'    => 'boolean',
     385                                                        'default' => false,
     386                                                ),
     387                                                'postId'        => array(
     388                                                        'type'    => 'number',
     389                                                        'default' => 0,
     390                                                ),
     391                                        ),
     392                                        'render_callback'    => 'bp_friends_render_friends_block',
     393                                ),
     394                        )
     395                );
    351396        }
    352397}
  • new file src/bp-friends/css/blocks/friends-rtl.css

    diff --git src/bp-friends/css/blocks/friends-rtl.css src/bp-friends/css/blocks/friends-rtl.css
    new file mode 100644
    index 000000000..8aff30506
    - +  
     1.bp-dynamic-block-container .item-options {
     2        font-size: 0.5em;
     3        margin: 0 0 1em;
     4        padding: 1em 0;
     5}
     6
     7.bp-dynamic-block-container .item-options a.selected {
     8        font-weight: 600;
     9}
     10
     11.bp-dynamic-block-container ul.item-list {
     12        list-style: none;
     13        margin: 1em 0;
     14}
     15
     16.bp-dynamic-block-container ul.item-list li {
     17        margin-bottom: 1em;
     18}
     19
     20.bp-dynamic-block-container ul.item-list li:before, .bp-dynamic-block-container ul.item-list li:after {
     21        content: " ";
     22        display: table;
     23}
     24
     25.bp-dynamic-block-container ul.item-list li:after {
     26        clear: both;
     27}
     28
     29.bp-dynamic-block-container ul.item-list li .item-avatar {
     30        float: right;
     31        width: 60px;
     32}
     33
     34.bp-dynamic-block-container ul.item-list li .item {
     35        margin-right: 70px;
     36}
  • new file src/bp-friends/css/blocks/friends.css

    diff --git src/bp-friends/css/blocks/friends.css src/bp-friends/css/blocks/friends.css
    new file mode 100644
    index 000000000..110c8aaa5
    - +  
     1.bp-dynamic-block-container .item-options {
     2        font-size: 0.5em;
     3        margin: 0 0 1em;
     4        padding: 1em 0;
     5}
     6
     7.bp-dynamic-block-container .item-options a.selected {
     8        font-weight: 600;
     9}
     10
     11.bp-dynamic-block-container ul.item-list {
     12        list-style: none;
     13        margin: 1em 0;
     14}
     15
     16.bp-dynamic-block-container ul.item-list li {
     17        margin-bottom: 1em;
     18}
     19
     20.bp-dynamic-block-container ul.item-list li:before, .bp-dynamic-block-container ul.item-list li:after {
     21        content: " ";
     22        display: table;
     23}
     24
     25.bp-dynamic-block-container ul.item-list li:after {
     26        clear: both;
     27}
     28
     29.bp-dynamic-block-container ul.item-list li .item-avatar {
     30        float: left;
     31        width: 60px;
     32}
     33
     34.bp-dynamic-block-container ul.item-list li .item {
     35        margin-left: 70px;
     36}
  • new file src/bp-friends/js/blocks/friends.js

    diff --git src/bp-friends/js/blocks/friends.js src/bp-friends/js/blocks/friends.js
    new file mode 100644
    index 000000000..611ea18c8
    - +  
     1// modules are defined as an array
     2// [ module function, map of requires ]
     3//
     4// map of requires is short require name -> numeric require
     5//
     6// anything defined in a previous bundle is accessed via the
     7// orig method which is the require for previous bundles
     8parcelRequire = (function (modules, cache, entry, globalName) {
     9  // Save the require from previous bundle to this closure if any
     10  var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
     11  var nodeRequire = typeof require === 'function' && require;
     12
     13  function newRequire(name, jumped) {
     14    if (!cache[name]) {
     15      if (!modules[name]) {
     16        // if we cannot find the module within our internal map or
     17        // cache jump to the current global require ie. the last bundle
     18        // that was added to the page.
     19        var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
     20        if (!jumped && currentRequire) {
     21          return currentRequire(name, true);
     22        }
     23
     24        // If there are other bundles on this page the require from the
     25        // previous one is saved to 'previousRequire'. Repeat this as
     26        // many times as there are bundles until the module is found or
     27        // we exhaust the require chain.
     28        if (previousRequire) {
     29          return previousRequire(name, true);
     30        }
     31
     32        // Try the node require function if it exists.
     33        if (nodeRequire && typeof name === 'string') {
     34          return nodeRequire(name);
     35        }
     36
     37        var err = new Error('Cannot find module \'' + name + '\'');
     38        err.code = 'MODULE_NOT_FOUND';
     39        throw err;
     40      }
     41
     42      localRequire.resolve = resolve;
     43      localRequire.cache = {};
     44
     45      var module = cache[name] = new newRequire.Module(name);
     46
     47      modules[name][0].call(module.exports, localRequire, module, module.exports, this);
     48    }
     49
     50    return cache[name].exports;
     51
     52    function localRequire(x){
     53      return newRequire(localRequire.resolve(x));
     54    }
     55
     56    function resolve(x){
     57      return modules[name][1][x] || x;
     58    }
     59  }
     60
     61  function Module(moduleName) {
     62    this.id = moduleName;
     63    this.bundle = newRequire;
     64    this.exports = {};
     65  }
     66
     67  newRequire.isParcelRequire = true;
     68  newRequire.Module = Module;
     69  newRequire.modules = modules;
     70  newRequire.cache = cache;
     71  newRequire.parent = previousRequire;
     72  newRequire.register = function (id, exports) {
     73    modules[id] = [function (require, module) {
     74      module.exports = exports;
     75    }, {}];
     76  };
     77
     78  var error;
     79  for (var i = 0; i < entry.length; i++) {
     80    try {
     81      newRequire(entry[i]);
     82    } catch (e) {
     83      // Save first error but execute all entries
     84      if (!error) {
     85        error = e;
     86      }
     87    }
     88  }
     89
     90  if (entry.length) {
     91    // Expose entry point to Node, AMD or browser globals
     92    // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
     93    var mainExports = newRequire(entry[entry.length - 1]);
     94
     95    // CommonJS
     96    if (typeof exports === "object" && typeof module !== "undefined") {
     97      module.exports = mainExports;
     98
     99    // RequireJS
     100    } else if (typeof define === "function" && define.amd) {
     101     define(function () {
     102       return mainExports;
     103     });
     104
     105    // <script>
     106    } else if (globalName) {
     107      this[globalName] = mainExports;
     108    }
     109  }
     110
     111  // Override the current require with this new one
     112  parcelRequire = newRequire;
     113
     114  if (error) {
     115    // throw error from earlier, _after updating parcelRequire_
     116    throw error;
     117  }
     118
     119  return newRequire;
     120})({"CSIX":[function(require,module,exports) {
     121"use strict";
     122
     123Object.defineProperty(exports, "__esModule", {
     124  value: true
     125});
     126exports.TYPES = void 0;
     127
     128/**
     129 * WordPress dependencies.
     130 */
     131var _wp = wp,
     132    __ = _wp.i18n.__;
     133/**
     134 * Friends ordering types.
     135 *
     136 * @type {Array}
     137 */
     138
     139var TYPES = [{
     140  label: __('Newest', 'buddypress'),
     141  value: 'newest'
     142}, {
     143  label: __('Active', 'buddypress'),
     144  value: 'active'
     145}, {
     146  label: __('Popular', 'buddypress'),
     147  value: 'popular'
     148}];
     149exports.TYPES = TYPES;
     150},{}],"qXsY":[function(require,module,exports) {
     151"use strict";
     152
     153Object.defineProperty(exports, "__esModule", {
     154  value: true
     155});
     156exports.default = void 0;
     157
     158var _constants = require("./constants");
     159
     160/**
     161 * WordPress dependencies.
     162 */
     163var _wp = wp,
     164    InspectorControls = _wp.blockEditor.InspectorControls,
     165    _wp$components = _wp.components,
     166    Disabled = _wp$components.Disabled,
     167    PanelBody = _wp$components.PanelBody,
     168    RangeControl = _wp$components.RangeControl,
     169    SelectControl = _wp$components.SelectControl,
     170    ToggleControl = _wp$components.ToggleControl,
     171    _wp$element = _wp.element,
     172    Fragment = _wp$element.Fragment,
     173    createElement = _wp$element.createElement,
     174    __ = _wp.i18n.__;
     175/**
     176 * BuddyPress dependencies.
     177 */
     178
     179var _bp = bp,
     180    ServerSideRender = _bp.blockComponents.ServerSideRender,
     181    currentPostId = _bp.blockData.currentPostId;
     182/**
     183 * Internal dependencies.
     184 */
     185
     186var editDynamicFriendsBlock = function editDynamicFriendsBlock(_ref) {
     187  var attributes = _ref.attributes,
     188      setAttributes = _ref.setAttributes;
     189  var postId = attributes.postId,
     190      maxFriends = attributes.maxFriends,
     191      friendDefault = attributes.friendDefault,
     192      linkTitle = attributes.linkTitle;
     193  var post = currentPostId();
     194
     195  if (!postId && post) {
     196    setAttributes({
     197      postId: post
     198    });
     199  }
     200
     201  return createElement(Fragment, null, createElement(InspectorControls, null, createElement(PanelBody, {
     202    title: __('Settings', 'buddypress'),
     203    initialOpen: true
     204  }, createElement(RangeControl, {
     205    label: __('Max friends to show', 'buddypress'),
     206    value: maxFriends,
     207    onChange: function onChange(value) {
     208      return setAttributes({
     209        maxFriends: value
     210      });
     211    },
     212    min: 1,
     213    max: 10,
     214    required: true
     215  }), createElement(SelectControl, {
     216    label: __('Default members to show', 'buddypress'),
     217    value: friendDefault,
     218    options: _constants.TYPES,
     219    onChange: function onChange(option) {
     220      setAttributes({
     221        friendDefault: option
     222      });
     223    }
     224  }), createElement(ToggleControl, {
     225    label: __('Link block title to Member\'s profile friends page', 'buddypress'),
     226    checked: !!linkTitle,
     227    onChange: function onChange() {
     228      setAttributes({
     229        linkTitle: !linkTitle
     230      });
     231    }
     232  }))), createElement(Disabled, null, createElement(ServerSideRender, {
     233    block: "bp/friends",
     234    attributes: attributes
     235  })));
     236};
     237
     238var _default = editDynamicFriendsBlock;
     239exports.default = _default;
     240},{"./constants":"CSIX"}],"fch3":[function(require,module,exports) {
     241"use strict";
     242
     243Object.defineProperty(exports, "__esModule", {
     244  value: true
     245});
     246exports.default = void 0;
     247
     248/**
     249 * WordPress dependencies.
     250 */
     251var _wp = wp,
     252    createBlock = _wp.blocks.createBlock;
     253/**
     254 * Transforms Legacy Widget to Friends Block.
     255 *
     256 * @type {Object}
     257 */
     258
     259var transforms = {
     260  from: [{
     261    type: 'block',
     262    blocks: ['core/legacy-widget'],
     263    isMatch: function isMatch(_ref) {
     264      var idBase = _ref.idBase,
     265          instance = _ref.instance;
     266
     267      if (!(instance !== null && instance !== void 0 && instance.raw)) {
     268        return false;
     269      }
     270
     271      return idBase === 'bp_core_friends_widget';
     272    },
     273    transform: function transform(_ref2) {
     274      var instance = _ref2.instance;
     275      return createBlock('bp/friends', {
     276        maxFriends: instance.raw.max_friends,
     277        friendDefault: instance.raw.friend_default,
     278        linkTitle: instance.raw.link_title
     279      });
     280    }
     281  }]
     282};
     283var _default = transforms;
     284exports.default = _default;
     285},{}],"Z2R5":[function(require,module,exports) {
     286"use strict";
     287
     288var _edit = _interopRequireDefault(require("./friends/edit"));
     289
     290var _transforms = _interopRequireDefault(require("./friends/transforms"));
     291
     292function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
     293
     294/**
     295 * WordPress dependencies.
     296 */
     297var _wp = wp,
     298    registerBlockType = _wp.blocks.registerBlockType,
     299    __ = _wp.i18n.__;
     300/**
     301 * Internal dependencies.
     302 */
     303
     304registerBlockType('bp/friends', {
     305  title: __('Friends List', 'buddypress'),
     306  description: __('A dynamic list of recently active, popular, and newest friends of the post author (when used into a page or post) or of the displayed member (when used in a widgetized area). If author/member data is not available the block is not displayed.', 'buddypress'),
     307  icon: {
     308    background: '#fff',
     309    foreground: '#d84800',
     310    src: 'buddicons-friends'
     311  },
     312  category: 'buddypress',
     313  attributes: {
     314    maxFriends: {
     315      type: 'number',
     316      default: 5
     317    },
     318    friendDefault: {
     319      type: 'string',
     320      default: 'active'
     321    },
     322    linkTitle: {
     323      type: 'boolean',
     324      default: false
     325    },
     326    postId: {
     327      type: 'number',
     328      default: 0
     329    }
     330  },
     331  edit: _edit.default,
     332  transforms: _transforms.default
     333});
     334},{"./friends/edit":"qXsY","./friends/transforms":"fch3"}]},{},["Z2R5"], null)
     335 No newline at end of file
  • new file src/bp-friends/js/friends.js

    diff --git src/bp-friends/js/friends.js src/bp-friends/js/friends.js
    new file mode 100644
    index 000000000..93de95628
    - +  
     1// modules are defined as an array
     2// [ module function, map of requires ]
     3//
     4// map of requires is short require name -> numeric require
     5//
     6// anything defined in a previous bundle is accessed via the
     7// orig method which is the require for previous bundles
     8parcelRequire = (function (modules, cache, entry, globalName) {
     9  // Save the require from previous bundle to this closure if any
     10  var previousRequire = typeof parcelRequire === 'function' && parcelRequire;
     11  var nodeRequire = typeof require === 'function' && require;
     12
     13  function newRequire(name, jumped) {
     14    if (!cache[name]) {
     15      if (!modules[name]) {
     16        // if we cannot find the module within our internal map or
     17        // cache jump to the current global require ie. the last bundle
     18        // that was added to the page.
     19        var currentRequire = typeof parcelRequire === 'function' && parcelRequire;
     20        if (!jumped && currentRequire) {
     21          return currentRequire(name, true);
     22        }
     23
     24        // If there are other bundles on this page the require from the
     25        // previous one is saved to 'previousRequire'. Repeat this as
     26        // many times as there are bundles until the module is found or
     27        // we exhaust the require chain.
     28        if (previousRequire) {
     29          return previousRequire(name, true);
     30        }
     31
     32        // Try the node require function if it exists.
     33        if (nodeRequire && typeof name === 'string') {
     34          return nodeRequire(name);
     35        }
     36
     37        var err = new Error('Cannot find module \'' + name + '\'');
     38        err.code = 'MODULE_NOT_FOUND';
     39        throw err;
     40      }
     41
     42      localRequire.resolve = resolve;
     43      localRequire.cache = {};
     44
     45      var module = cache[name] = new newRequire.Module(name);
     46
     47      modules[name][0].call(module.exports, localRequire, module, module.exports, this);
     48    }
     49
     50    return cache[name].exports;
     51
     52    function localRequire(x){
     53      return newRequire(localRequire.resolve(x));
     54    }
     55
     56    function resolve(x){
     57      return modules[name][1][x] || x;
     58    }
     59  }
     60
     61  function Module(moduleName) {
     62    this.id = moduleName;
     63    this.bundle = newRequire;
     64    this.exports = {};
     65  }
     66
     67  newRequire.isParcelRequire = true;
     68  newRequire.Module = Module;
     69  newRequire.modules = modules;
     70  newRequire.cache = cache;
     71  newRequire.parent = previousRequire;
     72  newRequire.register = function (id, exports) {
     73    modules[id] = [function (require, module) {
     74      module.exports = exports;
     75    }, {}];
     76  };
     77
     78  var error;
     79  for (var i = 0; i < entry.length; i++) {
     80    try {
     81      newRequire(entry[i]);
     82    } catch (e) {
     83      // Save first error but execute all entries
     84      if (!error) {
     85        error = e;
     86      }
     87    }
     88  }
     89
     90  if (entry.length) {
     91    // Expose entry point to Node, AMD or browser globals
     92    // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
     93    var mainExports = newRequire(entry[entry.length - 1]);
     94
     95    // CommonJS
     96    if (typeof exports === "object" && typeof module !== "undefined") {
     97      module.exports = mainExports;
     98
     99    // RequireJS
     100    } else if (typeof define === "function" && define.amd) {
     101     define(function () {
     102       return mainExports;
     103     });
     104
     105    // <script>
     106    } else if (globalName) {
     107      this[globalName] = mainExports;
     108    }
     109  }
     110
     111  // Override the current require with this new one
     112  parcelRequire = newRequire;
     113
     114  if (error) {
     115    // throw error from earlier, _after updating parcelRequire_
     116    throw error;
     117  }
     118
     119  return newRequire;
     120})({"pMhP":[function(require,module,exports) {
     121function _typeof(obj) { "@babel/helpers - typeof"; if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { _typeof = function _typeof(obj) { return typeof obj; }; } else { _typeof = function _typeof(obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; } return _typeof(obj); }
     122
     123function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
     124
     125function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
     126
     127function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
     128
     129function _get(target, property, receiver) { if (typeof Reflect !== "undefined" && Reflect.get) { _get = Reflect.get; } else { _get = function _get(target, property, receiver) { var base = _superPropBase(target, property); if (!base) return; var desc = Object.getOwnPropertyDescriptor(base, property); if (desc.get) { return desc.get.call(receiver); } return desc.value; }; } return _get(target, property, receiver || target); }
     130
     131function _superPropBase(object, property) { while (!Object.prototype.hasOwnProperty.call(object, property)) { object = _getPrototypeOf(object); if (object === null) break; } return object; }
     132
     133function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function"); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); if (superClass) _setPrototypeOf(subClass, superClass); }
     134
     135function _setPrototypeOf(o, p) { _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { o.__proto__ = p; return o; }; return _setPrototypeOf(o, p); }
     136
     137function _createSuper(Derived) { var hasNativeReflectConstruct = _isNativeReflectConstruct(); return function _createSuperInternal() { var Super = _getPrototypeOf(Derived), result; if (hasNativeReflectConstruct) { var NewTarget = _getPrototypeOf(this).constructor; result = Reflect.construct(Super, arguments, NewTarget); } else { result = Super.apply(this, arguments); } return _possibleConstructorReturn(this, result); }; }
     138
     139function _possibleConstructorReturn(self, call) { if (call && (_typeof(call) === "object" || typeof call === "function")) { return call; } return _assertThisInitialized(self); }
     140
     141function _assertThisInitialized(self) { if (self === void 0) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return self; }
     142
     143function _isNativeReflectConstruct() { if (typeof Reflect === "undefined" || !Reflect.construct) return false; if (Reflect.construct.sham) return false; if (typeof Proxy === "function") return true; try { Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); return true; } catch (e) { return false; } }
     144
     145function _getPrototypeOf(o) { _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { return o.__proto__ || Object.getPrototypeOf(o); }; return _getPrototypeOf(o); }
     146
     147/**
     148 * WordPress dependencies.
     149 */
     150var _wp = wp,
     151    _wp$i18n = _wp.i18n,
     152    __ = _wp$i18n.__,
     153    sprintf = _wp$i18n.sprintf;
     154/**
     155 * BuddyPress dependencies.
     156 */
     157
     158var _bp = bp,
     159    dynamicWidgetBlock = _bp.dynamicWidgetBlock;
     160/**
     161 * Front-end Friends block class.
     162 */
     163
     164var bpFriendsWidgetBlock = /*#__PURE__*/function (_dynamicWidgetBlock) {
     165  _inherits(bpFriendsWidgetBlock, _dynamicWidgetBlock);
     166
     167  var _super = _createSuper(bpFriendsWidgetBlock);
     168
     169  function bpFriendsWidgetBlock() {
     170    _classCallCheck(this, bpFriendsWidgetBlock);
     171
     172    return _super.apply(this, arguments);
     173  }
     174
     175  _createClass(bpFriendsWidgetBlock, [{
     176    key: "loop",
     177    value: function loop() {
     178      var friends = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
     179      var container = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : '';
     180      var type = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 'active';
     181
     182      var tmpl = _get(_getPrototypeOf(bpFriendsWidgetBlock.prototype), "useTemplate", this).call(this, 'bp-friends-item');
     183
     184      var selector = document.querySelector('#' + container);
     185      var output = '';
     186
     187      if (friends && friends.length) {
     188        friends.forEach(function (friend) {
     189          if ('active' === type && friend.last_activity) {
     190            /* translators: %s: a human time diff. */
     191            friend.extra = sprintf(__('Active %s', 'buddypress'), friend.last_activity.timediff);
     192          } else if ('popular' === type && friend.total_friend_count) {
     193            var friendsCount = parseInt(friend.total_friend_count, 10);
     194
     195            if (0 === friendsCount) {
     196              friend.extra = __('No friends', 'buddypress');
     197            } else if (1 === friendsCount) {
     198              friend.extra = __('1 friend', 'buddypress');
     199            } else {
     200              /* translators: %s: total friend count (more than 1). */
     201              friend.extra = sprintf(__('%s friends', 'buddypress'), friend.total_friend_count);
     202            }
     203          } else if ('newest' === type && friend.registered_since) {
     204            /* translators: %s is time elapsed since the registration date happened */
     205            friend.extra = sprintf(__('Registered %s', 'buddypress'), friend.registered_since);
     206          }
     207          /* translators: %s: member name */
     208
     209
     210          friend.avatar_alt = sprintf(__('Profile picture of %s', 'buddypress'), friend.name);
     211          output += tmpl(friend);
     212        });
     213      } else {
     214        output = '<div class="widget-error">' + __('Sorry, no members were found.', 'buddypress') + '</div>';
     215      }
     216
     217      selector.innerHTML = output;
     218    }
     219  }, {
     220    key: "start",
     221    value: function start() {
     222      var _this = this;
     223
     224      this.blocks.forEach(function (block, i) {
     225        var selector = block.selector;
     226        var type = block.query_args.type;
     227        var list = document.querySelector('#' + selector).closest('.bp-dynamic-block-container'); // Get default Block's type friends.
     228
     229        _get(_getPrototypeOf(bpFriendsWidgetBlock.prototype), "getItems", _this).call(_this, type, i); // Listen to Block's Nav item clics
     230
     231
     232        list.querySelectorAll('.item-options a').forEach(function (navItem) {
     233          navItem.addEventListener('click', function (event) {
     234            event.preventDefault(); // Changes the displayed filter.
     235
     236            event.target.closest('.item-options').querySelector('.selected').classList.remove('selected');
     237            event.target.classList.add('selected');
     238            var newType = event.target.getAttribute('data-bp-sort');
     239
     240            if (newType !== _this.blocks[i].query_args.type) {
     241              _get(_getPrototypeOf(bpFriendsWidgetBlock.prototype), "getItems", _this).call(_this, newType, i);
     242            }
     243          });
     244        });
     245      });
     246    }
     247  }]);
     248
     249  return bpFriendsWidgetBlock;
     250}(dynamicWidgetBlock);
     251
     252var settings = window.bpFriendsSettings || {};
     253var blocks = window.bpFriendsBlocks || {};
     254var bpFriends = new bpFriendsWidgetBlock(settings, blocks);
     255
     256if ('loading' === document.readyState) {
     257  document.addEventListener('DOMContentLoaded', bpFriends.start());
     258} else {
     259  bpFriends.start();
     260}
     261},{}]},{},["pMhP"], null)
     262 No newline at end of file
  • new file src/bp-friends/sass/blocks/friends.scss

    diff --git src/bp-friends/sass/blocks/friends.scss src/bp-friends/sass/blocks/friends.scss
    new file mode 100644
    index 000000000..35104d10d
    - +  
     1.bp-dynamic-block-container {
     2
     3        .item-options {
     4                font-size: 0.5em;
     5                margin: 0 0 1em;
     6                padding: 1em 0;
     7
     8                a.selected {
     9                        font-weight: 600;
     10                }
     11        }
     12
     13        ul.item-list {
     14                list-style: none;
     15                margin: 1em 0;
     16
     17                li {
     18                        margin-bottom: 1em;
     19
     20                        &:before,
     21                        &:after {
     22                                content: " ";
     23                                display: table;
     24                        }
     25
     26                        &:after {
     27                                clear: both;
     28                        }
     29
     30                        .item-avatar {
     31                                float: left;
     32                                width: 60px;
     33                        }
     34
     35                        .item {
     36                                margin-left: 70px;
     37                        }
     38                }
     39        }
     40}
  • src/bp-groups/js/blocks/groups.js

    diff --git src/bp-groups/js/blocks/groups.js src/bp-groups/js/blocks/groups.js
    index 30ac54b00..092956c2f 100644
    parcelRequire = (function (modules, cache, entry, globalName) {  
    117117  }
    118118
    119119  return newRequire;
    120 })({"LGpM":[function(require,module,exports) {
     120})({"jEQo":[function(require,module,exports) {
    121121function _arrayLikeToArray(arr, len) {
    122122  if (len == null || len > arr.length) len = arr.length;
    123123
    … … function _arrayWithoutHoles(arr) {  
    137137}
    138138
    139139module.exports = _arrayWithoutHoles;
    140 },{"./arrayLikeToArray":"LGpM"}],"lZpU":[function(require,module,exports) {
     140},{"./arrayLikeToArray":"jEQo"}],"lZpU":[function(require,module,exports) {
    141141function _iterableToArray(iter) {
    142142  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
    143143}
    144144
    145145module.exports = _iterableToArray;
    146 },{}],"Vzqv":[function(require,module,exports) {
     146},{}],"Dbv9":[function(require,module,exports) {
    147147var arrayLikeToArray = require("./arrayLikeToArray");
    148148
    149149function _unsupportedIterableToArray(o, minLen) {
    … … function _unsupportedIterableToArray(o, minLen) {  
    156156}
    157157
    158158module.exports = _unsupportedIterableToArray;
    159 },{"./arrayLikeToArray":"LGpM"}],"NCaH":[function(require,module,exports) {
     159},{"./arrayLikeToArray":"jEQo"}],"NCaH":[function(require,module,exports) {
    160160function _nonIterableSpread() {
    161161  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    162162}
    … … function _toConsumableArray(arr) {  
    176176}
    177177
    178178module.exports = _toConsumableArray;
    179 },{"./arrayWithoutHoles":"o3SL","./iterableToArray":"lZpU","./unsupportedIterableToArray":"Vzqv","./nonIterableSpread":"NCaH"}],"dEOc":[function(require,module,exports) {
     179},{"./arrayWithoutHoles":"o3SL","./iterableToArray":"lZpU","./unsupportedIterableToArray":"Dbv9","./nonIterableSpread":"NCaH"}],"DCTP":[function(require,module,exports) {
    180180function _arrayWithHoles(arr) {
    181181  if (Array.isArray(arr)) return arr;
    182182}
    183183
    184184module.exports = _arrayWithHoles;
    185 },{}],"RonT":[function(require,module,exports) {
     185},{}],"LoeL":[function(require,module,exports) {
    186186function _iterableToArrayLimit(arr, i) {
    187187  if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
    188188  var _arr = [];
    … … function _iterableToArrayLimit(arr, i) {  
    211211}
    212212
    213213module.exports = _iterableToArrayLimit;
    214 },{}],"sa4T":[function(require,module,exports) {
     214},{}],"MWEO":[function(require,module,exports) {
    215215function _nonIterableRest() {
    216216  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    217217}
    218218
    219219module.exports = _nonIterableRest;
    220 },{}],"xkYc":[function(require,module,exports) {
     220},{}],"DERy":[function(require,module,exports) {
    221221var arrayWithHoles = require("./arrayWithHoles");
    222222
    223223var iterableToArrayLimit = require("./iterableToArrayLimit");
    … … function _slicedToArray(arr, i) {  
    231231}
    232232
    233233module.exports = _slicedToArray;
    234 },{"./arrayWithHoles":"dEOc","./iterableToArrayLimit":"RonT","./unsupportedIterableToArray":"Vzqv","./nonIterableRest":"sa4T"}],"jS06":[function(require,module,exports) {
     234},{"./arrayWithHoles":"DCTP","./iterableToArrayLimit":"LoeL","./unsupportedIterableToArray":"Dbv9","./nonIterableRest":"MWEO"}],"jS06":[function(require,module,exports) {
    235235"use strict";
    236236
    237237Object.defineProperty(exports, "__esModule", {
    … … var editGroupsBlock = function editGroupsBlock(_ref) {  
    566566
    567567var _default = editGroupsBlock;
    568568exports.default = _default;
    569 },{"@babel/runtime/helpers/toConsumableArray":"I9dH","@babel/runtime/helpers/slicedToArray":"xkYc","./constants":"jS06"}],"jcTh":[function(require,module,exports) {
     569},{"@babel/runtime/helpers/toConsumableArray":"I9dH","@babel/runtime/helpers/slicedToArray":"DERy","./constants":"jS06"}],"jcTh":[function(require,module,exports) {
    570570"use strict";
    571571
    572572var _edit = _interopRequireDefault(require("./groups/edit"));
  • src/bp-members/js/blocks/members.js

    diff --git src/bp-members/js/blocks/members.js src/bp-members/js/blocks/members.js
    index 61f8c6b9e..a37f593c2 100644
    parcelRequire = (function (modules, cache, entry, globalName) {  
    117117  }
    118118
    119119  return newRequire;
    120 })({"LGpM":[function(require,module,exports) {
     120})({"jEQo":[function(require,module,exports) {
    121121function _arrayLikeToArray(arr, len) {
    122122  if (len == null || len > arr.length) len = arr.length;
    123123
    … … function _arrayWithoutHoles(arr) {  
    137137}
    138138
    139139module.exports = _arrayWithoutHoles;
    140 },{"./arrayLikeToArray":"LGpM"}],"lZpU":[function(require,module,exports) {
     140},{"./arrayLikeToArray":"jEQo"}],"lZpU":[function(require,module,exports) {
    141141function _iterableToArray(iter) {
    142142  if (typeof Symbol !== "undefined" && Symbol.iterator in Object(iter)) return Array.from(iter);
    143143}
    144144
    145145module.exports = _iterableToArray;
    146 },{}],"Vzqv":[function(require,module,exports) {
     146},{}],"Dbv9":[function(require,module,exports) {
    147147var arrayLikeToArray = require("./arrayLikeToArray");
    148148
    149149function _unsupportedIterableToArray(o, minLen) {
    … … function _unsupportedIterableToArray(o, minLen) {  
    156156}
    157157
    158158module.exports = _unsupportedIterableToArray;
    159 },{"./arrayLikeToArray":"LGpM"}],"NCaH":[function(require,module,exports) {
     159},{"./arrayLikeToArray":"jEQo"}],"NCaH":[function(require,module,exports) {
    160160function _nonIterableSpread() {
    161161  throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    162162}
    … … function _toConsumableArray(arr) {  
    176176}
    177177
    178178module.exports = _toConsumableArray;
    179 },{"./arrayWithoutHoles":"o3SL","./iterableToArray":"lZpU","./unsupportedIterableToArray":"Vzqv","./nonIterableSpread":"NCaH"}],"dEOc":[function(require,module,exports) {
     179},{"./arrayWithoutHoles":"o3SL","./iterableToArray":"lZpU","./unsupportedIterableToArray":"Dbv9","./nonIterableSpread":"NCaH"}],"DCTP":[function(require,module,exports) {
    180180function _arrayWithHoles(arr) {
    181181  if (Array.isArray(arr)) return arr;
    182182}
    183183
    184184module.exports = _arrayWithHoles;
    185 },{}],"RonT":[function(require,module,exports) {
     185},{}],"LoeL":[function(require,module,exports) {
    186186function _iterableToArrayLimit(arr, i) {
    187187  if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return;
    188188  var _arr = [];
    … … function _iterableToArrayLimit(arr, i) {  
    211211}
    212212
    213213module.exports = _iterableToArrayLimit;
    214 },{}],"sa4T":[function(require,module,exports) {
     214},{}],"MWEO":[function(require,module,exports) {
    215215function _nonIterableRest() {
    216216  throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
    217217}
    218218
    219219module.exports = _nonIterableRest;
    220 },{}],"xkYc":[function(require,module,exports) {
     220},{}],"DERy":[function(require,module,exports) {
    221221var arrayWithHoles = require("./arrayWithHoles");
    222222
    223223var iterableToArrayLimit = require("./iterableToArrayLimit");
    … … function _slicedToArray(arr, i) {  
    231231}
    232232
    233233module.exports = _slicedToArray;
    234 },{"./arrayWithHoles":"dEOc","./iterableToArrayLimit":"RonT","./unsupportedIterableToArray":"Vzqv","./nonIterableRest":"sa4T"}],"gr8I":[function(require,module,exports) {
     234},{"./arrayWithHoles":"DCTP","./iterableToArrayLimit":"LoeL","./unsupportedIterableToArray":"Dbv9","./nonIterableRest":"MWEO"}],"gr8I":[function(require,module,exports) {
    235235"use strict";
    236236
    237237Object.defineProperty(exports, "__esModule", {
    … … var editMembersBlock = function editMembersBlock(_ref) {  
    562562
    563563var _default = editMembersBlock;
    564564exports.default = _default;
    565 },{"@babel/runtime/helpers/toConsumableArray":"I9dH","@babel/runtime/helpers/slicedToArray":"xkYc","./constants":"gr8I"}],"XEHU":[function(require,module,exports) {
     565},{"@babel/runtime/helpers/toConsumableArray":"I9dH","@babel/runtime/helpers/slicedToArray":"DERy","./constants":"gr8I"}],"XEHU":[function(require,module,exports) {
    566566"use strict";
    567567
    568568var _edit = _interopRequireDefault(require("./members/edit"));
  • new file src/bp-templates/bp-legacy/buddypress/assets/widgets/friends.php

    diff --git src/bp-templates/bp-legacy/buddypress/assets/widgets/friends.php src/bp-templates/bp-legacy/buddypress/assets/widgets/friends.php
    new file mode 100644
    index 000000000..866d91691
    - +  
     1<?php
     2/**
     3 * Friends Widget Block template.
     4 *
     5 * @since 9.0.0
     6 *
     7 * @package BuddyPress
     8 * @subpackage bp-legacy
     9 * @version 9.0.0
     10 */
     11?>
     12<script type="html/template" id="tmpl-bp-friends-item">
     13        <li class="vcard">
     14                <div class="item-avatar">
     15                        <a href="{{{data.link}}}" class="bp-tooltip" data-bp-tooltip="{{data.name}}">
     16                                <img loading="lazy" src="{{{data.avatar_urls.thumb}}}" class="avatar user-{{data.id}}-avatar avatar-50 photo" width="50" height="50" alt="{{{data.avatar_alt}}}">
     17                        </a>
     18                </div>
     19
     20                <div class="item">
     21                        <div class="item-title fn"><a href="{{{data.link}}}">{{data.name}}</a></div>
     22                        <div class="item-meta">
     23                                <span class="activity">{{data.extra}}</span>
     24                        </div>
     25                </div>
     26        </li>
     27</script>
  • new file src/bp-templates/bp-nouveau/buddypress/assets/widgets/friends.php

    diff --git src/bp-templates/bp-nouveau/buddypress/assets/widgets/friends.php src/bp-templates/bp-nouveau/buddypress/assets/widgets/friends.php
    new file mode 100644
    index 000000000..6bb4fc72a
    - +  
     1<?php
     2/**
     3 * Friends Widget Block template.
     4 *
     5 * @since 9.0.0
     6 *
     7 * @package BuddyPress
     8 * @subpackage bp-nouveau
     9 * @version 9.0.0
     10 */
     11?>
     12<script type="html/template" id="tmpl-bp-friends-item">
     13        <li class="vcard">
     14                <div class="item-avatar">
     15                        <a href="{{{data.link}}}" class="bp-tooltip" data-bp-tooltip="{{data.name}}">
     16                                <img loading="lazy" src="{{{data.avatar_urls.thumb}}}" class="avatar user-{{data.id}}-avatar avatar-50 photo" width="50" height="50" alt="{{{data.avatar_alt}}}">
     17                        </a>
     18                </div>
     19
     20                <div class="item">
     21                        <div class="item-title fn"><a href="{{{data.link}}}">{{data.name}}</a></div>
     22                        <div class="item-meta">
     23                                <span class="activity">{{data.extra}}</span>
     24                        </div>
     25                </div>
     26        </li>
     27</script>
  • new file src/js/bp-core/js/dynamic-widget-block.js

    diff --git src/js/bp-core/js/dynamic-widget-block.js src/js/bp-core/js/dynamic-widget-block.js
    new file mode 100644
    index 000000000..b62550220
    - +  
     1/**
     2 * WordPress dependencies.
     3 */
     4const {
     5        url: {
     6                addQueryArgs,
     7        },
     8} = wp;
     9
     10/**
     11 * External dependencies.
     12 */
     13const {
     14        template,
     15} = lodash;
     16
     17// Use the bp global.
     18window.bp = window.bp || {};
     19
     20/**
     21 * Generic class to be used by Dynamic Widget Blocks.
     22 *
     23 * @since 9.0.0
     24 */
     25bp.dynamicWidgetBlock = class bpDynamicWidgetBlock {
     26        constructor( settings, blocks ) {
     27                const { path, root, nonce } = settings;
     28                this.path = path;
     29                this.root = root;
     30                this.nonce = nonce,
     31                this.blocks = blocks;
     32
     33                this.blocks.forEach( ( block, i ) => {
     34                        const { type } = block.query_args || 'active';
     35                        const { body } = block.preloaded || [];
     36
     37                        this.blocks[ i ].items = {
     38                                'active': [],
     39                                'newest': [],
     40                                'popular': [],
     41                                'alphabetical': [],
     42                        }
     43
     44                        if ( ! this.blocks[ i ].items[ type ].length && body && body.length ) {
     45                                this.blocks[ i ].items[ type ] = body;
     46                        }
     47                } );
     48        }
     49
     50        useTemplate( tmpl ) {
     51                const options = {
     52                        evaluate:    /<#([\s\S]+?)#>/g,
     53                        interpolate: /\{\{\{([\s\S]+?)\}\}\}/g,
     54                        escape:      /\{\{([^\}]+?)\}\}(?!\})/g,
     55                        variable:    'data'
     56                };
     57
     58                return template( document.querySelector( '#tmpl-' + tmpl ).innerHTML, options );
     59        }
     60
     61        loop() {
     62                // This method needs to be overriden.
     63        }
     64
     65        getItems( type = 'active', blockIndex = 0 ) {
     66                this.blocks[ blockIndex ].query_args.type = type;
     67
     68                if ( this.blocks[ blockIndex ].items[ type ].length ) {
     69                        this.loop( this.blocks[ blockIndex ].items[ type ], this.blocks[ blockIndex ].selector, type );
     70                } else {
     71                        fetch( addQueryArgs( this.root + this.path, this.blocks[ blockIndex ].query_args ), {
     72                                method: 'GET',
     73                                headers: {
     74                                        'X-WP-Nonce' : this.nonce,
     75                                }
     76                        } ).then(
     77                                ( response ) => response.json()
     78                        ).then(
     79                                ( data ) => {
     80                                        this.blocks[ blockIndex ].items[ type ] = data;
     81                                        this.loop( this.blocks[ blockIndex ].items[ type ], this.blocks[ blockIndex ].selector, type );
     82                                }
     83                        );
     84                }
     85        }
     86};
  • new file src/js/bp-friends/js/blocks/.babelrc

    diff --git src/js/bp-friends/js/blocks/.babelrc src/js/bp-friends/js/blocks/.babelrc
    new file mode 100644
    index 000000000..c4ff60626
    - +  
     1{
     2        "presets": ["@wordpress/default"]
     3}
  • new file src/js/bp-friends/js/blocks/friends.js

    diff --git src/js/bp-friends/js/blocks/friends.js src/js/bp-friends/js/blocks/friends.js
    new file mode 100644
    index 000000000..d735f14cb
    - +  
     1/**
     2 * WordPress dependencies.
     3 */
     4const {
     5        blocks: {
     6                registerBlockType,
     7        },
     8        i18n: {
     9                __,
     10        },
     11} = wp;
     12
     13/**
     14 * Internal dependencies.
     15 */
     16import editDynamicFriendsBlock from './friends/edit';
     17import transforms from './friends/transforms';
     18
     19registerBlockType( 'bp/friends', {
     20        title: __( 'Friends List', 'buddypress' ),
     21        description: __( 'A dynamic list of recently active, popular, and newest friends of the post author (when used into a page or post) or of the displayed member (when used in a widgetized area). If author/member data is not available the block is not displayed.', 'buddypress' ),
     22        icon: {
     23                background: '#fff',
     24                foreground: '#d84800',
     25                src: 'buddicons-friends',
     26        },
     27        category: 'buddypress',
     28        attributes: {
     29                maxFriends: {
     30                        type: 'number',
     31                        default: 5
     32                },
     33                friendDefault: {
     34                        type: 'string',
     35                        default: 'active',
     36                },
     37                linkTitle: {
     38                        type: 'boolean',
     39                        default: false,
     40                },
     41                postId: {
     42                        type: 'number',
     43                        default: 0,
     44                },
     45        },
     46        edit: editDynamicFriendsBlock,
     47        transforms: transforms,
     48} );
  • new file src/js/bp-friends/js/blocks/friends/constants.js

    diff --git src/js/bp-friends/js/blocks/friends/constants.js src/js/bp-friends/js/blocks/friends/constants.js
    new file mode 100644
    index 000000000..ff4f3dcb6
    - +  
     1/**
     2 * WordPress dependencies.
     3 */
     4const {
     5        i18n: {
     6                __,
     7        },
     8} = wp;
     9
     10/**
     11 * Friends ordering types.
     12 *
     13 * @type {Array}
     14 */
     15export const TYPES = [
     16        {
     17                label: __( 'Newest', 'buddypress' ),
     18                value: 'newest',
     19        },
     20        {
     21                label: __( 'Active', 'buddypress' ),
     22                value: 'active',
     23        },
     24        {
     25                label: __( 'Popular', 'buddypress' ),
     26                value: 'popular',
     27        },
     28];
  • new file src/js/bp-friends/js/blocks/friends/edit.js

    diff --git src/js/bp-friends/js/blocks/friends/edit.js src/js/bp-friends/js/blocks/friends/edit.js
    new file mode 100644
    index 000000000..a5928e51b
    - +  
     1/**
     2 * WordPress dependencies.
     3 */
     4const {
     5        blockEditor: {
     6                InspectorControls,
     7        },
     8        components: {
     9                Disabled,
     10                PanelBody,
     11                RangeControl,
     12                SelectControl,
     13                ToggleControl,
     14        },
     15        element: {
     16                Fragment,
     17                createElement,
     18        },
     19        i18n: {
     20                __,
     21        },
     22} = wp;
     23
     24/**
     25 * BuddyPress dependencies.
     26 */
     27const {
     28        blockComponents: {
     29                ServerSideRender,
     30        },
     31        blockData: {
     32                currentPostId,
     33        }
     34} = bp;
     35
     36/**
     37 * Internal dependencies.
     38 */
     39import { TYPES } from './constants';
     40
     41const editDynamicFriendsBlock = ( { attributes, setAttributes } ) => {
     42        const { postId, maxFriends, friendDefault, linkTitle } = attributes;
     43        const post = currentPostId();
     44
     45        if ( ! postId && post ) {
     46                setAttributes( { postId: post } );
     47        }
     48
     49        return (
     50                <Fragment>
     51                        <InspectorControls>
     52                                <PanelBody title={ __( 'Settings', 'buddypress' ) } initialOpen={ true }>
     53                                        <RangeControl
     54                                                label={ __( 'Max friends to show', 'buddypress' ) }
     55                                                value={ maxFriends }
     56                                                onChange={ ( value ) =>
     57                                                        setAttributes( { maxFriends: value } )
     58                                                }
     59                                                min={ 1 }
     60                                                max={ 10 }
     61                                                required
     62                                        />
     63                                        <SelectControl
     64                                                label={ __( 'Default members to show', 'buddypress' ) }
     65                                                value={ friendDefault }
     66                                                options={ TYPES }
     67                                                onChange={ ( option ) => {
     68                                                        setAttributes( { friendDefault: option } );
     69                                                } }
     70                                        />
     71                                        <ToggleControl
     72                                                label={ __( 'Link block title to Member\'s profile friends page', 'buddypress' ) }
     73                                                checked={ !! linkTitle }
     74                                                onChange={ () => {
     75                                                        setAttributes( { linkTitle: ! linkTitle } );
     76                                                } }
     77                                        />
     78                                </PanelBody>
     79                        </InspectorControls>
     80                        <Disabled>
     81                                <ServerSideRender block="bp/friends" attributes={ attributes } />
     82                        </Disabled>
     83                </Fragment>
     84        );
     85};
     86
     87export default editDynamicFriendsBlock;
  • new file src/js/bp-friends/js/blocks/friends/transforms.js

    diff --git src/js/bp-friends/js/blocks/friends/transforms.js src/js/bp-friends/js/blocks/friends/transforms.js
    new file mode 100644
    index 000000000..7788e77b4
    - +  
     1/**
     2 * WordPress dependencies.
     3 */
     4const {
     5        blocks: {
     6                createBlock,
     7        },
     8} = wp;
     9
     10/**
     11 * Transforms Legacy Widget to Friends Block.
     12 *
     13 * @type {Object}
     14 */
     15const transforms = {
     16        from: [
     17                {
     18                        type: 'block',
     19                        blocks: [ 'core/legacy-widget' ],
     20                        isMatch: ( { idBase, instance } ) => {
     21                                if ( ! instance?.raw ) {
     22                                        return false;
     23                                }
     24
     25                                return idBase === 'bp_core_friends_widget';
     26                        },
     27                        transform: ( { instance } ) => {
     28                                return createBlock( 'bp/friends', {
     29                                        maxFriends: instance.raw.max_friends,
     30                                        friendDefault: instance.raw.friend_default,
     31                                        linkTitle: instance.raw.link_title,
     32                                } );
     33                        },
     34                },
     35        ],
     36};
     37
     38export default transforms;
  • new file src/js/bp-friends/js/friends.js

    diff --git src/js/bp-friends/js/friends.js src/js/bp-friends/js/friends.js
    new file mode 100644
    index 000000000..bbb48948d
    - +  
     1/**
     2 * WordPress dependencies.
     3 */
     4const {
     5        i18n: {
     6                __,
     7                sprintf,
     8        },
     9} = wp;
     10
     11/**
     12 * BuddyPress dependencies.
     13 */
     14const {
     15        dynamicWidgetBlock,
     16} = bp;
     17
     18/**
     19 * Front-end Friends block class.
     20 */
     21class bpFriendsWidgetBlock extends dynamicWidgetBlock {
     22        loop( friends = [], container = '', type = 'active' ) {
     23                const tmpl = super.useTemplate( 'bp-friends-item' );
     24                const selector = document.querySelector( '#' + container );
     25                let output = '';
     26
     27                if ( friends && friends.length ) {
     28                        friends.forEach( ( friend ) => {
     29                                if ( 'active' === type && friend.last_activity ) {
     30                                        /* translators: %s: a human time diff. */
     31                                        friend.extra = sprintf( __( 'Active %s', 'buddypress' ), friend.last_activity.timediff );
     32                                } else if ( 'popular' === type && friend.total_friend_count ) {
     33                                        const friendsCount = parseInt( friend.total_friend_count, 10 );
     34
     35                                        if ( 0 === friendsCount ) {
     36                                                friend.extra = __( 'No friends', 'buddypress' );
     37                                        } else if ( 1 === friendsCount ) {
     38                                                friend.extra = __( '1 friend', 'buddypress' );
     39                                        } else {
     40                                                /* translators: %s: total friend count (more than 1). */
     41                                                friend.extra = sprintf( __( '%s friends', 'buddypress' ), friend.total_friend_count );
     42                                        }
     43                                } else if ( 'newest' === type && friend.registered_since ) {
     44                                        /* translators: %s is time elapsed since the registration date happened */
     45                                        friend.extra = sprintf( __( 'Registered %s', 'buddypress' ), friend.registered_since );
     46                                }
     47
     48                                /* translators: %s: member name */
     49                                friend.avatar_alt = sprintf( __( 'Profile picture of %s', 'buddypress' ), friend.name );
     50
     51                                output += tmpl( friend );
     52                        } );
     53                } else {
     54                        output = '<div class="widget-error">' + __( 'Sorry, no members were found.', 'buddypress' ) + '</div>';
     55                }
     56
     57                selector.innerHTML = output;
     58        }
     59
     60        start() {
     61                this.blocks.forEach( ( block, i ) => {
     62                        const { selector } = block;
     63                        const { type } = block.query_args;
     64                        const list = document.querySelector( '#' + selector ).closest( '.bp-dynamic-block-container' );
     65
     66                        // Get default Block's type friends.
     67                        super.getItems( type, i );
     68
     69                        // Listen to Block's Nav item clics
     70                        list.querySelectorAll( '.item-options a' ).forEach( ( navItem ) => {
     71                                navItem.addEventListener( 'click', ( event ) => {
     72                                        event.preventDefault();
     73
     74                                        // Changes the displayed filter.
     75                                        event.target.closest( '.item-options' ).querySelector( '.selected' ).classList.remove( 'selected' );
     76                                        event.target.classList.add( 'selected' );
     77
     78                                        const newType = event.target.getAttribute( 'data-bp-sort' );
     79
     80                                        if ( newType !== this.blocks[ i ].query_args.type ) {
     81                                                super.getItems( newType, i );
     82                                        }
     83                                } );
     84                        } );
     85                } );
     86        }
     87}
     88
     89const settings = window.bpFriendsSettings || {};
     90const blocks = window.bpFriendsBlocks || {};
     91const bpFriends = new bpFriendsWidgetBlock( settings, blocks );
     92
     93if ( 'loading' === document.readyState ) {
     94        document.addEventListener( 'DOMContentLoaded', bpFriends.start() );
     95} else {
     96        bpFriends.start();
     97}