Make WordPress Core

Ticket #21170: 21170.9.diff

File 21170.9.diff, 18.3 KB (added by adamsilverstein, 8 years ago)
  • new file src/wp-includes/js/wp-hooks.js

    diff --git src/wp-includes/js/wp-hooks.js src/wp-includes/js/wp-hooks.js
    new file mode 100644
    index 0000000000..e4e3dca03d
    - +  
     1( function( wp ) {
     2        'use strict';
     3
     4        /**
     5         * Contains the registered hooks, keyed by hook type. Each hook type is an
     6         * array of objects with priority and callback of each registered hook.
     7         */
     8        var HOOKS = {};
     9
     10        /**
     11         * Returns a function which, when invoked, will add a hook.
     12         *
     13         * @param  {string}   type Type for which hooks are to be added
     14         * @return {Function}      Hook added
     15         */
     16        function createAddHookByType( type ) {
     17                /**
     18                 * Adds the hook to the appropriate hooks container
     19                 *
     20                 * @param {string}   hook     Name of hook to add
     21                 * @param {Function} callback Function to call when the hook is run
     22                 * @param {?number}  priority Priority of this hook (default=10)
     23                 */
     24                return function( hook, callback, priority ) {
     25                        var hookObject, hooks;
     26                        if ( typeof hook !== 'string' || typeof callback !== 'function' ) {
     27                                return;
     28                        }
     29
     30                        // Assign default priority
     31                        if ( 'undefined' === typeof priority ) {
     32                                priority = 10;
     33                        } else {
     34                                priority = parseInt( priority, 10 );
     35                        }
     36
     37                        // Validate numeric priority
     38                        if ( isNaN( priority ) ) {
     39                                return;
     40                        }
     41
     42                        // Check if adding first of type
     43                        if ( ! HOOKS[ type ] ) {
     44                                HOOKS[ type ] = {};
     45                        }
     46
     47                        hookObject = {
     48                                callback: callback,
     49                                priority: priority
     50                        };
     51
     52                        if ( HOOKS[ type ].hasOwnProperty( hook ) ) {
     53                                // Append and re-sort amongst existing
     54                                hooks = HOOKS[ type ][ hook ];
     55                                hooks.push( hookObject );
     56                                hooks = sortHooks( hooks );
     57                        } else {
     58                                // First of its type needs no sort
     59                                hooks = [ hookObject ];
     60                        }
     61
     62                        HOOKS[ type ][ hook ] = hooks;
     63                };
     64        }
     65
     66        /**
     67         * Returns a function which, when invoked, will remove a specified hook.
     68         *
     69         * @param  {string}   type Type for which hooks are to be removed
     70         * @return {Function}      Hook remover
     71         */
     72        function createRemoveHookByType( type ) {
     73                /**
     74                 * Removes the specified hook by resetting its value.
     75                 *
     76                 * @param {string}    hook     Name of hook to remove
     77                 * @param {?Function} callback The specific callback to be removed. If
     78                 *                             omitted, clears all callbacks.
     79                 */
     80                return function( hook, callback ) {
     81                        var handlers, i;
     82
     83                        // Baily early if no hooks exist by this name
     84                        if ( ! HOOKS[ type ] || ! HOOKS[ type ].hasOwnProperty( hook ) ) {
     85                                return;
     86                        }
     87
     88                        if ( callback ) {
     89                                // Try to find specified callback to remove
     90                                handlers = HOOKS[ type ][ hook ];
     91                                for ( i = handlers.length - 1; i >= 0; i-- ) {
     92                                        if ( handlers[ i ].callback === callback ) {
     93                                                handlers.splice( i, 1 );
     94                                        }
     95                                }
     96                        } else {
     97                                // Reset hooks to empty
     98                                delete HOOKS[ type ][ hook ];
     99                        }
     100                };
     101        }
     102
     103        /**
     104         * Returns a function which, when invoked, will execute all registered
     105         * hooks of the specified type by calling upon runner with its hook name
     106         * and arguments.
     107         *
     108         * @param  {string}   type   Type for which hooks are to be run, one of 'action' or 'filter'.
     109         * @param  {Function} runner Function to invoke for each hook callback
     110         * @return {Function}        Hook runner
     111         */
     112        function createRunHookByType( type, runner ) {
     113                /**
     114                 * Runs the specified hook.
     115                 *
     116                 * @param  {string} hook The hook to run
     117                 * @param  {...*}   args Arguments to pass to the action/filter
     118                 * @return {*}           Return value of runner, if applicable
     119                 * @private
     120                 */
     121                return function( /* hook, ...args */ ) {
     122                        var args, hook;
     123
     124                        args = Array.prototype.slice.call( arguments );
     125                        hook = args.shift();
     126
     127                        if ( typeof hook === 'string' ) {
     128                                return runner( hook, args );
     129                        }
     130                };
     131        }
     132
     133        /**
     134         * Performs an action if it exists.
     135         *
     136         * @param {string} action The action to perform.
     137         * @param {...*}   args   Optional args to pass to the action.
     138         * @private
     139         */
     140        function runDoAction( action, args ) {
     141                var handlers, i;
     142                if ( HOOKS.actions ) {
     143                        handlers = HOOKS.actions[ action ];
     144                }
     145
     146                if ( ! handlers ) {
     147                        return;
     148                }
     149
     150                HOOKS.actions.current = action;
     151
     152                for ( i = 0; i < handlers.length; i++ ) {
     153                        handlers[ i ].callback.apply( null, args );
     154                        HOOKS.actions[ action ].runs = HOOKS.actions[ action ].runs ? HOOKS.actions[ action ].runs + 1 : 1;
     155                }
     156
     157        }
     158
     159        /**
     160         * Performs a filter if it exists.
     161         *
     162         * @param  {string} filter The filter to apply.
     163         * @param  {...*}   args   Optional args to pass to the filter.
     164         * @return {*}             The filtered value
     165         * @private
     166         */
     167        function runApplyFilters( filter, args ) {
     168                var handlers, i;
     169                if ( HOOKS.filters ) {
     170                        handlers = HOOKS.filters[ filter ];
     171                }
     172
     173                if ( ! handlers ) {
     174                        return args[ 0 ];
     175                }
     176
     177                HOOKS.filters.current = filter;
     178                HOOKS.filters[ filter ].runs = HOOKS.filters[ filter ].runs ? HOOKS.filters[ filter ].runs + 1 : 1;
     179
     180                for ( i = 0; i < handlers.length; i++ ) {
     181                        args[ 0 ] = handlers[ i ].callback.apply( null, args );
     182                }
     183                delete( HOOKS.filters.current );
     184
     185                return args[ 0 ];
     186        }
     187
     188        /**
     189         * Use an insert sort for keeping our hooks organized based on priority.
     190         *
     191         * @see http://jsperf.com/javascript-sort
     192         *
     193         * @param  {Array} hooks Array of the hooks to sort
     194         * @return {Array}       The sorted array
     195         * @private
     196         */
     197        function sortHooks( hooks ) {
     198                var i, tmpHook, j, prevHook;
     199                for ( i = 1; i < hooks.length; i++ ) {
     200                        tmpHook = hooks[ i ];
     201                        j = i;
     202                        while ( ( prevHook = hooks[ j - 1 ] ) && prevHook.priority > tmpHook.priority ) {
     203                                hooks[ j ] = hooks[ j - 1 ];
     204                                --j;
     205                        }
     206                        hooks[ j ] = tmpHook;
     207                }
     208
     209                return hooks;
     210        }
     211
     212
     213        /**
     214         * See what action is currently being executed.
     215         *
     216         * @param  {string} type   Type of hooks to check, one of 'action' or 'filter'.
     217         * @param {string}  action The name of the action to check for.
     218         *
     219         * @return {[type]}      [description]
     220         */
     221        function createCurrentHookByType( type ) {
     222                return function( action ) {
     223
     224                        // If the action was not passed, check for any current hook.
     225                        if ( 'undefined' === typeof action ) {
     226                                return false;
     227                        }
     228
     229                        // Return the current hook.
     230                        return HOOKS[ type ] && HOOKS[ type ].current ?
     231                                HOOKS[ type ].current :
     232                                false;
     233                };
     234        }
     235
     236
     237
     238        /**
     239         * Checks to see if an action is currently being executed.
     240         *
     241         * @param  {string} type   Type of hooks to check, one of 'action' or 'filter'.
     242         * @param {string}  action The name of the action to check for, if omitted will check for any action being performed.
     243         *
     244         * @return {[type]}      [description]
     245         */
     246        function createDoingHookByType( type ) {
     247                return function( action ) {
     248
     249                        // If the action was not passed, check for any current hook.
     250                        if ( 'undefined' === typeof action ) {
     251                                return 'undefined' !== typeof HOOKS[ type ].current;
     252                        }
     253
     254                        // Return the current hook.
     255                        return HOOKS[ type ] && HOOKS[ type ].current ?
     256                                action === HOOKS[ type ].current :
     257                                false;
     258                };
     259        }
     260
     261        /**
     262         * Retrieve the number of times an action is fired.
     263         *
     264         * @param  {string} type   Type for which hooks to check, one of 'action' or 'filter'.
     265         * @param {string}  action The action to check.
     266         *
     267         * @return {[type]}      [description]
     268         */
     269        function createDidHookByType( type ) {
     270                return function( action ) {
     271                        return HOOKS[ type ] && HOOKS[ type ][ action ] && HOOKS[ type ][ action ].runs ?
     272                                HOOKS[ type ][ action ].runs :
     273                                0;
     274                };
     275        }
     276
     277        /**
     278         * Check to see if an action is registered for a hook.
     279         *
     280         * @param  {string} type   Type for which hooks to check, one of 'action' or 'filter'.
     281         * @param {string}  action  The action to check.
     282         *
     283         * @return {bool}      Whether an action has been registered for a hook.
     284         */
     285        function createHasHookByType( type ) {
     286                return function( action ) {
     287                        return HOOKS[ type ] && HOOKS[ type ][ action ] ?
     288                                !! HOOKS[ type ][ action ] :
     289                                false;
     290                };
     291        }
     292
     293        /**
     294         * Remove all the actions registered to a hook,
     295         */
     296        function createRemoveAllByType( type ) {
     297                return function( action, type ) {
     298
     299                };
     300        }
     301
     302        wp.hooks = {
     303
     304                // Remove functions,
     305                removeFilter: createRemoveHookByType( 'filters' ),
     306                removeAction: createRemoveHookByType( 'actions' ),
     307
     308
     309                // Do action/apply filter functions.
     310                doAction:     createRunHookByType( 'actions', runDoAction ),
     311                applyFilters: createRunHookByType( 'filters', runApplyFilters ),
     312
     313                // Add functions.
     314                addAction: createAddHookByType( 'actions' ),
     315                addFilter: createAddHookByType( 'filters' ),
     316
     317                // Doing functions.
     318                doingAction: createDoingHookByType( 'actions' ), /* True for actions until next action fired. */
     319                doingFilter: createDoingHookByType( 'filters' ), /* True for filters while filter is being applied. */
     320
     321                // Did functions.
     322                didAction: createDidHookByType( 'actions' ),
     323                didFilter: createDidHookByType( 'filters' ),
     324
     325                // Has functions.
     326                hasAction: createHasHookByType( 'actions' ),
     327                hasFilter: createHasHookByType( 'filters' ),
     328
     329                // Remove all functions.
     330                removeAllActions: createRemoveAllByType( 'actions' ),
     331                removeAllFilters: createRemoveAllByType( 'filters' ),
     332
     333                // Current filter.
     334                currentFilter: createCurrentHookByType( 'filters' )
     335        };
     336} )( window.wp = window.wp || {} );
  • src/wp-includes/plugin.php

    diff --git src/wp-includes/plugin.php src/wp-includes/plugin.php
    index 86f1c3b319..86f9db8964 100644
    function doing_filter( $filter = null ) { 
    363363}
    364364
    365365/**
    366  * Retrieve the name of an action currently being processed.
     366 * Retrieve whether action currently being processed.
    367367 *
    368368 * @since 3.9.0
    369369 *
  • src/wp-includes/script-loader.php

    diff --git src/wp-includes/script-loader.php src/wp-includes/script-loader.php
    index 7562e2839b..4692f8801f 100644
    function wp_default_scripts( &$scripts ) { 
    8585
    8686        $scripts->add( 'wp-a11y', "/wp-includes/js/wp-a11y$suffix.js", array( 'jquery' ), false, 1 );
    8787
     88        $scripts->add( 'wp-hooks', "/wp-includes/js/wp-hooks$suffix.js", array(), false, 1 );
     89
    8890        $scripts->add( 'sack', "/wp-includes/js/tw-sack$suffix.js", array(), '1.6.1', 1 );
    8991
    9092        $scripts->add( 'quicktags', "/wp-includes/js/quicktags$suffix.js", array(), false, 1 );
  • tests/qunit/index.html

    diff --git tests/qunit/index.html tests/qunit/index.html
    index c41fffe63a..183c492d85 100644
     
    7676                <script src="../../src/wp-includes/js/customize-base.js"></script>
    7777                <script src="../../src/wp-includes/js/customize-models.js"></script>
    7878                <script src="../../src/wp-includes/js/shortcode.js"></script>
     79                <script src="../../src/wp-includes/js/wp-hooks.js"></script>
    7980                <script src="../../src/wp-admin/js/customize-controls.js"></script>
    8081                <script src="../../src/wp-includes/js/wp-api.js"></script>
    8182
     
    122123                <script src="wp-admin/js/customize-base.js"></script>
    123124                <script src="wp-admin/js/customize-header.js"></script>
    124125                <script src="wp-includes/js/shortcode.js"></script>
     126                <script src="wp-includes/js/wp-hooks.js"></script>
    125127                <script src="wp-includes/js/wp-api.js"></script>
    126128                <script src="wp-admin/js/customize-controls.js"></script>
    127129                <script src="wp-admin/js/customize-controls-utils.js"></script>
  • new file tests/qunit/wp-includes/js/wp-hooks.js

    diff --git tests/qunit/wp-includes/js/wp-hooks.js tests/qunit/wp-includes/js/wp-hooks.js
    new file mode 100644
    index 0000000000..d66cc50f43
    - +  
     1/* global wp */
     2( function( QUnit ) {
     3        QUnit.module( 'wp-hooks' );
     4
     5        function filter_a( str ) {
     6                return str + 'a';
     7        }
     8        function filter_b( str ) {
     9                return str + 'b';
     10        }
     11        function filter_c( str ) {
     12                return str + 'c';
     13        }
     14        function action_a() {
     15                window.actionValue += 'a';
     16        }
     17        function action_b() {
     18                window.actionValue += 'b';
     19        }
     20        function action_c() {
     21                window.actionValue += 'c';
     22        }
     23        function filter_check() {
     24                ok( wp.hooks.doingFilter( 'runtest.filter' ), 'The runtest.filter is running.' );
     25        }
     26        window.actionValue = '';
     27
     28        QUnit.test( 'add and remove a filter', function() {
     29                expect( 1 );
     30                wp.hooks.addFilter( 'test.filter', filter_a );
     31                wp.hooks.removeFilter( 'test.filter' );
     32                equal( wp.hooks.applyFilters( 'test.filter', 'test' ), 'test' );
     33        } );
     34
     35        QUnit.test( 'add a filter and run it', function() {
     36                expect( 1 );
     37                wp.hooks.addFilter( 'test.filter', filter_a );
     38                equal( wp.hooks.applyFilters( 'test.filter', 'test' ), 'testa' );
     39                wp.hooks.removeFilter( 'test.filter' );
     40        } );
     41
     42        QUnit.test( 'add 2 filters in a row and run them', function() {
     43                expect( 1 );
     44                wp.hooks.addFilter( 'test.filter', filter_a );
     45                wp.hooks.addFilter( 'test.filter', filter_b );
     46                equal( wp.hooks.applyFilters( 'test.filter', 'test' ), 'testab' );
     47                wp.hooks.removeFilter( 'test.filter' );
     48        } );
     49
     50        QUnit.test( 'add 3 filters with different priorities and run them', function() {
     51                expect( 1 );
     52                wp.hooks.addFilter( 'test.filter', filter_a );
     53                wp.hooks.addFilter( 'test.filter', filter_b, 2 );
     54                wp.hooks.addFilter( 'test.filter', filter_c, 8 );
     55                equal( wp.hooks.applyFilters( 'test.filter', 'test' ), 'testbca' );
     56                wp.hooks.removeFilter( 'test.filter' );
     57        } );
     58
     59        QUnit.test( 'add and remove an action', function() {
     60                expect( 1 );
     61                window.actionValue = '';
     62                wp.hooks.addAction( 'test.action', action_a );
     63                wp.hooks.removeAction( 'test.action' );
     64                wp.hooks.doAction( 'test.action' );
     65                equal( window.actionValue, '' );
     66        } );
     67
     68        QUnit.test( 'add an action and run it', function() {
     69                expect( 1 );
     70                window.actionValue = '';
     71                wp.hooks.addAction( 'test.action', action_a );
     72                wp.hooks.doAction( 'test.action' );
     73                equal( window.actionValue, 'a' );
     74                wp.hooks.removeAction( 'test.action' );
     75        } );
     76
     77        QUnit.test( 'add 2 actions in a row and then run them', function() {
     78                expect( 1 );
     79                window.actionValue = '';
     80                wp.hooks.addAction( 'test.action', action_a );
     81                wp.hooks.addAction( 'test.action', action_b );
     82                wp.hooks.doAction( 'test.action' );
     83                equal( window.actionValue, 'ab' );
     84                wp.hooks.removeAction( 'test.action' );
     85        } );
     86
     87        QUnit.test( 'add 3 actions with different priorities and run them', function() {
     88                expect( 1 );
     89                window.actionValue = '';
     90                wp.hooks.addAction( 'test.action', action_a );
     91                wp.hooks.addAction( 'test.action', action_b, 2 );
     92                wp.hooks.addAction( 'test.action', action_c, 8 );
     93                wp.hooks.doAction( 'test.action' );
     94                equal( window.actionValue, 'bca' );
     95                wp.hooks.removeAction( 'test.action' );
     96        } );
     97
     98        QUnit.test( 'pass in two arguments to an action', function() {
     99                var arg1 = 10,
     100                        arg2 = 20;
     101
     102                expect( 4 );
     103
     104                wp.hooks.addAction( 'test.action', function( a, b ) {
     105                        equal( arg1, a );
     106                        equal( arg2, b );
     107                } );
     108                wp.hooks.doAction( 'test.action', arg1, arg2 );
     109                wp.hooks.removeAction( 'test.action' );
     110
     111                equal( arg1, 10 );
     112                equal( arg2, 20 );
     113        } );
     114
     115        QUnit.test( 'fire action multiple times', function() {
     116                var func;
     117                expect( 2 );
     118
     119                func = function() {
     120                        ok( true );
     121                };
     122
     123                wp.hooks.addAction( 'test.action', func );
     124                wp.hooks.doAction( 'test.action' );
     125                wp.hooks.doAction( 'test.action' );
     126                wp.hooks.removeAction( 'test.action' );
     127        } );
     128
     129        QUnit.test( 'remove specific action callback', function() {
     130                window.actionValue = '';
     131                wp.hooks.addAction( 'test.action', action_a );
     132                wp.hooks.addAction( 'test.action', action_b, 2 );
     133                wp.hooks.addAction( 'test.action', action_c, 8 );
     134
     135                wp.hooks.removeAction( 'test.action', action_b );
     136                wp.hooks.doAction( 'test.action' );
     137                equal( window.actionValue, 'ca' );
     138                wp.hooks.removeAction( 'test.action' );
     139        } );
     140
     141        QUnit.test( 'remove specific filter callback', function() {
     142                wp.hooks.addFilter( 'test.filter', filter_a );
     143                wp.hooks.addFilter( 'test.filter', filter_b, 2 );
     144                wp.hooks.addFilter( 'test.filter', filter_c, 8 );
     145
     146                wp.hooks.removeFilter( 'test.filter', filter_b );
     147                equal( wp.hooks.applyFilters( 'test.filter', 'test' ), 'testca' );
     148                wp.hooks.removeFilter( 'test.filter' );
     149        } );
     150
     151        // Test doingAction, didAction, hasAction.
     152        QUnit.test( 'Test doingAction, didAction and hasAction.', function() {
     153
     154                // Reset state for testing.
     155                wp.hooks.removeAction( 'test.action' );
     156                wp.hooks.addAction( 'another.action', function(){} );
     157                wp.hooks.doAction( 'another.action' );
     158
     159                // Verify no action is running yet.
     160                ok( ! wp.hooks.doingAction( 'test.action' ), 'The test.action is not running.' );
     161                equal( wp.hooks.didAction( 'test.action' ), 0, 'The test.action has not run.' );
     162                ok( ! wp.hooks.hasAction( 'test.action' ), 'The test.action is not registered.' );
     163
     164                wp.hooks.addAction( 'test.action', action_a );
     165
     166                // Verify action added, not running yet.
     167                ok( ! wp.hooks.doingAction( 'test.action' ), 'The test.action is not running.' );
     168                equal( wp.hooks.didAction( 'test.action' ), 0, 'The test.action has not run.' );
     169                ok( wp.hooks.hasAction( 'test.action' ), 'The test.action is registered.' );
     170
     171                wp.hooks.doAction( 'test.action' );
     172
     173                // Verify action added and running.
     174                ok( wp.hooks.doingAction( 'test.action' ), 'The test.action is running.' );
     175                equal( wp.hooks.didAction( 'test.action' ), 1, 'The test.action has run once.' );
     176                ok( wp.hooks.hasAction( 'test.action' ), 'The test.action is registered.' );
     177
     178                wp.hooks.doAction( 'test.action' );
     179                equal( wp.hooks.didAction( 'test.action' ), 2, 'The test.action has run twice.' );
     180
     181                wp.hooks.removeAction( 'test.action' );
     182
     183                // Verify state is reset appropriately.
     184                ok( wp.hooks.doingAction( 'test.action' ), 'The test.action is running.' );
     185                equal( wp.hooks.didAction( 'test.action' ), 0, 'The test.action has not run.' );
     186                ok( ! wp.hooks.hasAction( 'test.action' ), 'The test.action is not registered.' );
     187
     188                wp.hooks.doAction( 'another.action' );
     189                ok( ! wp.hooks.doingAction( 'test.action' ), 'The test.action is running.' );
     190
     191                // Verify hasAction returns false when no matching action.
     192                ok( ! wp.hooks.hasAction( 'notatest.action' ), 'The notatest.action is registered.' );
     193
     194        } );
     195
     196        QUnit.test( 'Verify doingFilter, didFilter and hasFilter.', function() {
     197                expect( 4 );
     198                wp.hooks.addFilter( 'runtest.filter', filter_check );
     199
     200                // Verify filter added and running.
     201                var test = wp.hooks.applyFilters( 'runtest.filter', true );
     202                equal( wp.hooks.didFilter( 'runtest.filter' ), 1, 'The runtest.filter has run once.' );
     203                ok( wp.hooks.hasFilter( 'runtest.filter' ), 'The runtest.filter is registered.' );
     204                ok( ! wp.hooks.hasFilter( 'notatest.filter' ), 'The notatest.filter is not registered.' );
     205
     206                wp.hooks.removeFilter( 'runtest.filter' );
     207        } );
     208
     209
     210
     211} )( window.QUnit );