├── .github ├── CODEOWNERS └── workflows │ └── code-linting.yml ├── .gitattributes ├── .wordpress-org ├── banner-772x250.png ├── icon-128x128.png ├── icon-256x256.png └── banner-1544x500.png ├── src ├── core-components │ ├── inserter-listbox │ │ ├── context.js │ │ └── index.js │ └── no-results.js ├── pattern-explorer.js ├── core-hooks │ ├── use-patterns-state.js │ └── use-insertion-point.js ├── preview │ ├── pattern.js │ ├── pattern-list.js │ ├── header.js │ └── index.js ├── sidebar.js ├── style.scss └── index.js ├── .gitignore ├── composer.json ├── webpack.config.js ├── includes ├── add-pattern-category-type-support.php ├── core │ └── add-pattern-category-type-support.php ├── class-bpe-pattern-category-types-rest-controller.php └── class-bpe-block-pattern-category-types-registry.php ├── package.json ├── README.md ├── phpcs.xml ├── block-pattern-explorer.php ├── readme.txt ├── composer.lock └── LICENSE /.github/CODEOWNERS: -------------------------------------------------------------------------------- 1 | * @wpengine/developer-relations -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | -------------------------------------------------------------------------------- /.wordpress-org/banner-772x250.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wpengine/block-pattern-explorer/HEAD/.wordpress-org/banner-772x250.png -------------------------------------------------------------------------------- /.wordpress-org/icon-128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wpengine/block-pattern-explorer/HEAD/.wordpress-org/icon-128x128.png -------------------------------------------------------------------------------- /.wordpress-org/icon-256x256.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wpengine/block-pattern-explorer/HEAD/.wordpress-org/icon-256x256.png -------------------------------------------------------------------------------- /.wordpress-org/banner-1544x500.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wpengine/block-pattern-explorer/HEAD/.wordpress-org/banner-1544x500.png -------------------------------------------------------------------------------- /src/core-components/inserter-listbox/context.js: -------------------------------------------------------------------------------- 1 | /** 2 | * WordPress dependencies 3 | */ 4 | import { createContext } from '@wordpress/element'; 5 | 6 | const InserterListboxContext = createContext(); 7 | 8 | export default InserterListboxContext; 9 | -------------------------------------------------------------------------------- /src/core-components/inserter-listbox/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * WordPress dependencies 3 | */ 4 | import { __unstableUseCompositeState as useCompositeState } from '@wordpress/components'; // eslint-disable-line 5 | 6 | /** 7 | * Internal dependencies 8 | */ 9 | import InserterListboxContext from './context'; 10 | 11 | function InserterListbox( { children } ) { 12 | const compositeState = useCompositeState( { 13 | shift: true, 14 | wrap: 'horizontal', 15 | } ); 16 | return ( 17 | 18 | { children } 19 | 20 | ); 21 | } 22 | 23 | export default InserterListbox; 24 | -------------------------------------------------------------------------------- /src/core-components/no-results.js: -------------------------------------------------------------------------------- 1 | /** 2 | * WordPress dependencies 3 | */ 4 | import { __ } from '@wordpress/i18n'; 5 | import { Icon, blockDefault } from '@wordpress/icons'; 6 | 7 | function InserterNoResults( { icon, label } ) { 8 | return ( 9 |
10 |
11 | 15 |

16 | { label 17 | ? label 18 | : __( 'No results found.', 'block-pattern-explorer' ) } 19 |

20 |
21 |
22 | ); 23 | } 24 | 25 | export default InserterNoResults; 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Compiled source # 2 | ################### 3 | *.com 4 | *.class 5 | *.dll 6 | *.exe 7 | *.o 8 | *.so 9 | 10 | # Packages # 11 | ############ 12 | # It's better to unpack these files and commit the raw source 13 | # git has its own built in compression methods. 14 | *.7z 15 | *.dmg 16 | *.gz 17 | *.iso 18 | *.jar 19 | *.rar 20 | *.tar 21 | *.zip 22 | 23 | # Logs and databases # 24 | ###################### 25 | logs 26 | *.log 27 | *.sql 28 | *.sqlite 29 | 30 | # OS generated files # 31 | ###################### 32 | .DS_Store 33 | .DS_Store? 34 | ._* 35 | .Spotlight-V100 36 | .Trashes 37 | ehthumbs.db 38 | Thumbs.db 39 | 40 | # NPM # 41 | ####### 42 | node_modules/ 43 | 44 | # Composer # 45 | ############ 46 | vendor/ 47 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "wpengine/block-pattern-explorer", 3 | "type": "wordpress-plugin", 4 | "description": "An experimental plugin to preview and insert block patterns in the Block Editor.", 5 | "homepage": "https://github.com/wpengine/block-pattern-explorer", 6 | "license": "GPL-2.0-or-later", 7 | "require": { 8 | "php": ">=5.6" 9 | }, 10 | "require-dev": { 11 | "dealerdirect/phpcodesniffer-composer-installer": "^0.7.0", 12 | "squizlabs/php_codesniffer": "^3.4.2", 13 | "phpcompatibility/php-compatibility": "^9.2.0", 14 | "phpcompatibility/phpcompatibility-wp": "^2.1", 15 | "wp-coding-standards/wpcs": "^2.1.1" 16 | }, 17 | "scripts": { 18 | "lint": "@php ./vendor/bin/phpcs", 19 | "lint-fix": "@php ./vendor/bin/phpcbf" 20 | }, 21 | "config": { 22 | "allow-plugins": { 23 | "dealerdirect/phpcodesniffer-composer-installer": true 24 | } 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /webpack.config.js: -------------------------------------------------------------------------------- 1 | const path = require( 'path' ); 2 | const defaultConfig = require( '@wordpress/scripts/config/webpack.config' ); 3 | 4 | const RemoveEmptyScriptsPlugin = require( 'webpack-remove-empty-scripts' ); 5 | 6 | module.exports = { 7 | ...defaultConfig, 8 | 9 | entry: { 10 | 'block-pattern-explorer-editor' : path.resolve( process.cwd(), 'src/index.js' ), 11 | 'block-pattern-explorer-editor-styles' : path.resolve( process.cwd(), 'src/style.scss' ), 12 | }, 13 | 14 | output: { 15 | filename: '[name].js', 16 | path: path.resolve( process.cwd(), 'build/' ), 17 | }, 18 | 19 | module: { 20 | ...defaultConfig.module, 21 | rules: [ 22 | ...defaultConfig.module.rules, 23 | // Add additional rules as needed. 24 | ] 25 | }, 26 | 27 | plugins: [ 28 | ...defaultConfig.plugins, 29 | // Add additional plugins as needed. 30 | new RemoveEmptyScriptsPlugin(), 31 | ], 32 | }; 33 | -------------------------------------------------------------------------------- /includes/add-pattern-category-type-support.php: -------------------------------------------------------------------------------- 1 | register_routes(); 24 | } 25 | add_action( 'rest_api_init', __NAMESPACE__ . '\register_routes' ); 26 | 27 | /** 28 | * Include the pattern category type registry. 29 | */ 30 | if ( ! class_exists( 'BPE_Block_Pattern_Category_Types_Registry' ) ) { 31 | require_once BPE_ABSPATH . '/includes/class-bpe-block-pattern-category-types-registry.php'; 32 | } 33 | 34 | /** 35 | * Include our custom REST API controllers. 36 | */ 37 | if ( ! class_exists( 'BPE_Pattern_Category_Types_REST_Controller' ) ) { 38 | require_once BPE_ABSPATH . 'includes/class-bpe-pattern-category-types-rest-controller.php'; 39 | } 40 | -------------------------------------------------------------------------------- /includes/core/add-pattern-category-type-support.php: -------------------------------------------------------------------------------- 1 | get_all_registered(); 24 | 25 | return $editor_settings; 26 | } 27 | add_filter( 'block_editor_settings_all', __NAMESPACE__ . '\add_block_editor_settings', 10, 2 ); 28 | 29 | // Include the pattern category type registry. 30 | if ( ! class_exists( 'BPE_Block_Pattern_Category_Types_Registry' ) ) { 31 | require_once BPE_ABSPATH . '/includes/class-bpe-block-pattern-category-types-registry.php'; 32 | } 33 | -------------------------------------------------------------------------------- /.github/workflows/code-linting.yml: -------------------------------------------------------------------------------- 1 | name: Code Linting - PHP 2 | 3 | on: 4 | pull_request: 5 | branches: [trunk] 6 | push: 7 | branches: [trunk] 8 | 9 | jobs: 10 | phpcs_check: 11 | name: PHPCS check 12 | runs-on: ubuntu-latest 13 | steps: 14 | - name: Checkout 15 | uses: actions/checkout@5a4ac9002d0be2fb38bd78e4b4dbde5606d7042f # v2.3.4 16 | - name: Setup PHP 17 | uses: shivammathur/setup-php@a7f90656b3be3996d1ec5501e8e25d5d35aa9bb2 # v2.15.0 18 | with: 19 | php-version: 7.4 20 | - name: Get composer cache directory 21 | id: composer-cache 22 | run: | 23 | echo "::set-output name=dir::$(composer config cache-files-dir)" 24 | - name: Cache composer dependencies 25 | uses: actions/cache@c64c572235d810460d0d6876e9c705ad5002b353 # v2.1.6 26 | with: 27 | path: ${{ steps.composer-cache.outputs.dir }} 28 | key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} 29 | restore-keys: | 30 | ${{ runner.os }}-composer- 31 | - name: Install composer packages 32 | run: composer install --no-progress 33 | - name: Check PHP coding standards using PHPCS 34 | run: composer lint -- --runtime-set ignore_warnings_on_exit true --runtime-set testVersion 5.8- -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "block-pattern-explorer", 3 | "version": "0.2.0", 4 | "description": "An experimental plugin to preview and insert block patterns in the Block Editor.", 5 | "author": "Nick Diego", 6 | "license": "GPL-2.0-or-later", 7 | "main": "build/index.js", 8 | "scripts": { 9 | "build": "wp-scripts build", 10 | "format:js": "wp-scripts format-js", 11 | "lint:css": "wp-scripts lint-style", 12 | "lint:js": "wp-scripts lint-js", 13 | "lint:js:src": "wp-scripts lint-js ./src", 14 | "lint:js:src:fix": "wp-scripts lint-js ./src --fix", 15 | "start": "wp-scripts start", 16 | "packages-update": "wp-scripts packages-update" 17 | }, 18 | "devDependencies": { 19 | "@wordpress/scripts": "^22.4.0", 20 | "classnames": "^2.3.1", 21 | "lodash": "^4.17.21", 22 | "markdown-it": "^12.3.2", 23 | "webpack-remove-empty-scripts": "^0.8.0" 24 | }, 25 | "dependencies": { 26 | "@wordpress/a11y": "^3.6.0", 27 | "@wordpress/api-fetch": "^6.3.0", 28 | "@wordpress/block-editor": "^8.5.1", 29 | "@wordpress/blocks": "^11.5.1", 30 | "@wordpress/components": "^19.8.0", 31 | "@wordpress/compose": "^5.4.0", 32 | "@wordpress/data": "^6.6.0", 33 | "@wordpress/edit-post": "^6.3.1", 34 | "@wordpress/element": "^4.4.0", 35 | "@wordpress/i18n": "^4.6.0", 36 | "@wordpress/icons": "^8.2.0", 37 | "@wordpress/notices": "^3.6.0", 38 | "@wordpress/plugins": "^4.4.0", 39 | "@wordpress/url": "^3.7.0" 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/pattern-explorer.js: -------------------------------------------------------------------------------- 1 | /** 2 | * WordPress dependencies 3 | */ 4 | import { useState } from '@wordpress/element'; 5 | 6 | /** 7 | * Internal dependencies 8 | */ 9 | import PatternExplorerSidebar from './sidebar'; 10 | import PatternExplorerPreview from './preview'; 11 | 12 | /** 13 | * Render the block pattern inserter. 14 | * 15 | * @since 0.1.0 16 | * @param {Object} props All the props passed to this function 17 | * @return {string} Return the rendered JSX 18 | */ 19 | export default function PatternExplorer( props ) { 20 | const { 21 | allPatterns, 22 | initialCategory, 23 | patternCategories, 24 | patternCategoryTypes, 25 | } = props; 26 | const [ selectedCategory, setSelectedCategory ] = useState( 27 | initialCategory?.name 28 | ); 29 | const [ searchValue, setSearchValue ] = useState( '' ); 30 | 31 | return ( 32 |
33 | 41 | 47 |
48 | ); 49 | } 50 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Block Pattern Explorer 2 | 3 | [![License](https://img.shields.io/badge/license-GPL--2.0%2B-green.svg)](https://github.com/wpengine/block-pattern-explorer/blob/master/LICENSE.txt) 4 | 5 | ![Block Pattern Explorer](https://user-images.githubusercontent.com/4832319/149385531-404f1d6f-4401-4786-9bfe-50b0be212adc.png) 6 | 7 | The Block Pattern Explorer is an experimental WordPress plugin based **heavily** on the work currently being done in [Gutenberg](https://github.com/WordPress/gutenberg). 8 | 9 | The purpose of this project is to isolate the pattern explorer into a standalone plugin that WordPress users/developers can interact with immediately, provide feedback on, and begin implementing into their own websites. Ideally, this initiative will also help inform the direction of core development. 10 | 11 | Once the pattern explorer is fully integrated into WordPress proper, this project will be sunsetted in favor of the core offering. Below is a list of current pull requests that are related to the Block Pattern Explorer in Gutenberg. 12 | 13 | - [#35006](https://github.com/WordPress/gutenberg/pull/35006) 14 | - [#35773](https://github.com/WordPress/gutenberg/pull/35773) 15 | 16 | ## Requirements 17 | 18 | - WordPress 5.8+ 19 | - [Gutenberg](https://github.com/WordPress/gutenberg) plugin (Not required if using WordPress 5.9+) 20 | - PHP 7.1+ 21 | 22 | ## Development 23 | 24 | 1. Set up a local WordPress development environment, we recommend using [Local](https://localwp.com/). 25 | 2. Clone / download this repository into the `wp-content/plugins` folder. 26 | 3. Navigate to the `wp-content/plugins/block-pattern-explorer` folder in the command line. 27 | 4. Run `npm install` to install the plugin's dependencies within a `/node_modules/` folder. 28 | 5. Run `composer install` to install the additional WordPress composer tools within a `/vendor/` folder. 29 | 6. Run `npm run start` to compile and watch source files for changes while developing. 30 | 31 | Refer to `package.json` and `composer.json` for additional commands. 32 | -------------------------------------------------------------------------------- /phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | Rules for Block Pattern Explorer 4 | 5 | 6 | 7 | ./ 8 | 9 | */build/* 10 | */dist/* 11 | */vendor/* 12 | */node_modules/* 13 | */wordpress*/* 14 | */\.* 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | -------------------------------------------------------------------------------- /src/core-hooks/use-patterns-state.js: -------------------------------------------------------------------------------- 1 | /** 2 | * External dependencies 3 | */ 4 | import { map } from 'lodash'; 5 | 6 | /** 7 | * WordPress dependencies 8 | */ 9 | import { useCallback } from '@wordpress/element'; 10 | import { cloneBlock } from '@wordpress/blocks'; 11 | import { useDispatch, useSelect } from '@wordpress/data'; 12 | import { __, sprintf } from '@wordpress/i18n'; 13 | import { store as noticesStore } from '@wordpress/notices'; 14 | import { store as blockEditorStore } from '@wordpress/block-editor'; 15 | 16 | /** 17 | * Retrieves the block patterns inserter state. 18 | * 19 | * @param {Function} onInsert function called when inserter a list of blocks. 20 | * @param {string=} rootClientId Insertion's root client ID. 21 | * 22 | * @return {Array} Returns the patterns state. (patterns, categories, onSelect handler) 23 | */ 24 | const usePatternsState = ( onInsert, rootClientId ) => { 25 | const { patterns, patternCategories, patternCategoryTypes } = useSelect( 26 | ( select ) => { 27 | const { __experimentalGetAllowedPatterns, getSettings } = select( 28 | blockEditorStore 29 | ); 30 | 31 | // Fetch any register pattern category types with the custom REST 32 | // API endpoint. Eventually replace with core functionality. 33 | const { getEntityRecord } = select( 'core' ); 34 | const categoryTypes = getEntityRecord( 35 | 'block-pattern-explorer/v1', 36 | 'patternCategoryTypes' 37 | ); 38 | 39 | return { 40 | patterns: __experimentalGetAllowedPatterns( rootClientId ), 41 | patternCategories: getSettings() 42 | .__experimentalBlockPatternCategories, 43 | patternCategoryTypes: 44 | categoryTypes?.patternCategoryTypes ?? 'fetching', 45 | // This is new functionality and will need to ultimately be added to the 46 | // Gutenberg Patterns API. Category Types allow theme/plugin developers to 47 | // group pattern categories together in the new Pattern Explorer. 48 | // patternCategoryTypes: getSettings().__experimentalBlockPatternCategoryTypes, 49 | }; 50 | }, 51 | [ rootClientId ] 52 | ); 53 | 54 | const { createSuccessNotice } = useDispatch( noticesStore ); 55 | const onClickPattern = useCallback( ( pattern, blocks ) => { 56 | onInsert( 57 | map( blocks, ( block ) => cloneBlock( block ) ), 58 | pattern.name 59 | ); 60 | createSuccessNotice( 61 | sprintf( 62 | /* translators: %s: block pattern title. */ 63 | __( 'Block pattern "%s" inserted.', 'block-pattern-explorer' ), 64 | pattern.title 65 | ), 66 | { 67 | type: 'snackbar', 68 | } 69 | ); 70 | }, [] ); 71 | 72 | return [ 73 | patterns, 74 | patternCategories, 75 | patternCategoryTypes, 76 | onClickPattern, 77 | ]; 78 | }; 79 | 80 | export default usePatternsState; 81 | -------------------------------------------------------------------------------- /includes/class-bpe-pattern-category-types-rest-controller.php: -------------------------------------------------------------------------------- 1 | namespace, 37 | '/' . $this->rest_base, 38 | array( 39 | array( 40 | 'methods' => WP_REST_Server::READABLE, 41 | 'callback' => array( $this, 'get_pattern_category_types' ), 42 | 'permission_callback' => '__return_true', // Read only, so anyone can view. 43 | ), 44 | 'schema' => array( $this, 'get_public_item_schema' ), 45 | ) 46 | ); 47 | } 48 | 49 | /** 50 | * Get a collection of items 51 | * 52 | * @return WP_Error|WP_REST_Response 53 | */ 54 | public function get_pattern_category_types() { 55 | 56 | $pattern_category_types = BPE_Block_Pattern_Category_Types_Registry::get_instance()->get_all_registered(); 57 | 58 | if ( is_array( $pattern_category_types ) ) { 59 | // @TODO Possibly add a prepare_settings_for_response function here 60 | // in the future. 61 | return new WP_REST_Response( array( 'patternCategoryTypes' => $pattern_category_types ), 200 ); 62 | } else { 63 | return new WP_Error( '404', __( 'Something went wrong, the category types could not be found.', 'block-pattern-explorer' ), array( 'status' => 404 ) ); 64 | } 65 | } 66 | 67 | /** 68 | * Get the Settings schema, conforming to JSON Schema. 69 | * 70 | * @return array 71 | */ 72 | public function get_item_schema() { 73 | if ( $this->schema ) { 74 | // Since WordPress 5.3, the schema can be cached in the $schema property. 75 | return $this->schema; 76 | } 77 | 78 | $this->schema = array( 79 | '$schema' => 'http://json-schema.org/draft-04/schema#', 80 | 'title' => 'pattern-category-types', 81 | 'type' => 'array', 82 | 'items' => array( 83 | 'type' => 'object', 84 | 'properties' => array( 85 | 'name' => array( 86 | 'type' => 'string', 87 | ), 88 | 'label' => array( 89 | 'type' => 'string', 90 | ), 91 | ), 92 | ), 93 | ); 94 | 95 | return $this->schema; 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/preview/pattern.js: -------------------------------------------------------------------------------- 1 | /** 2 | * WordPress dependencies 3 | */ 4 | import { __, sprintf } from '@wordpress/i18n'; 5 | import { 6 | Button, 7 | __unstableCompositeItem as CompositeItem, // eslint-disable-line 8 | VisuallyHidden, 9 | } from '@wordpress/components'; 10 | import { BlockPreview } from '@wordpress/block-editor'; 11 | import { cloneBlock } from '@wordpress/blocks'; 12 | import { useInstanceId } from '@wordpress/compose'; 13 | import { useDispatch, dispatch } from '@wordpress/data'; 14 | 15 | /** 16 | * Renders the block pattern 'card'. 17 | * 18 | * @since 0.1.0 19 | * @param {Object} props All the props passed to this function 20 | * @return {string} Return the rendered JSX 21 | */ 22 | export default function Pattern( props ) { 23 | const { 24 | pattern, 25 | onInsertPattern, 26 | viewportWidth, 27 | composite, 28 | isBlock, 29 | clientId, 30 | } = props; 31 | const { title, categories = [], blocks } = pattern; // eslint-disable-line 32 | const { createSuccessNotice } = useDispatch( 'core/notices' ); 33 | const instanceId = useInstanceId( Pattern ); 34 | const descriptionId = `preview-pattern-card__info-description-${ instanceId }`; 35 | 36 | function insertPattern() { 37 | onInsertPattern( blocks.map( ( block ) => cloneBlock( block ) ) ); 38 | 39 | // If the inserter was rendered from a block, we need to remove that 40 | // original block. 41 | if ( isBlock ) { 42 | dispatch( 'core/block-editor' ).removeBlock( clientId ); 43 | } 44 | 45 | createSuccessNotice( 46 | sprintf( 47 | // Translators: Name of the pattern being inserted. 48 | __( 'Block pattern "%s" inserted.', 'block-pattern-explorer' ), 49 | pattern.title 50 | ), 51 | { type: 'snackbar' } 52 | ); 53 | } 54 | 55 | const baseClassName = 'block-pattern-explorer__preview-pattern-list__item'; 56 | 57 | return ( 58 |
65 | 72 | 76 | 77 |
78 |
{ title }
79 | { !! pattern.description && ( 80 | 81 | { pattern.description } 82 | 83 | ) } 84 | 87 |
88 |
89 | ); 90 | } 91 | -------------------------------------------------------------------------------- /src/preview/pattern-list.js: -------------------------------------------------------------------------------- 1 | /** 2 | * External dependencies 3 | */ 4 | import classnames from 'classnames'; 5 | import { isEmpty } from 'lodash'; 6 | 7 | /** 8 | * WordPress dependencies 9 | */ 10 | import { __ } from '@wordpress/i18n'; 11 | import { category, stretchFullWidth } from '@wordpress/icons'; 12 | import { 13 | __unstableComposite as Composite, // eslint-disable-line 14 | __unstableUseCompositeState as useCompositeState, // eslint-disable-line 15 | } from '@wordpress/components'; 16 | 17 | /** 18 | * Internal dependencies 19 | */ 20 | import InserterNoResults from './../core-components/no-results'; 21 | import InserterListbox from './../core-components/inserter-listbox'; 22 | import useInsertionPoint from './../core-hooks/use-insertion-point'; 23 | import Pattern from './pattern'; 24 | 25 | /** 26 | * Renders the grid of block pattern previews. 27 | * 28 | * @since 0.1.0 29 | * @param {Object} props All the props passed to this function 30 | * @return {string} Return the rendered JSX 31 | */ 32 | export default function PreviewPatternList( props ) { 33 | const { 34 | isGrid, 35 | isLoading, 36 | searchValue, 37 | shownPatterns, 38 | viewportWidth, 39 | } = props; 40 | 41 | const [ destinationRootClientId, onInsertBlocks ] = useInsertionPoint( { // eslint-disable-line 42 | shouldFocusBlock: true, 43 | } ); 44 | 45 | const isError = isEmpty( shownPatterns ) && ! searchValue && ! isLoading; 46 | const noSearchResults = isEmpty( shownPatterns ) && searchValue; 47 | const hasPatterns = ! isError && ! noSearchResults; 48 | 49 | const noPatternsMessage = 50 | ! hasPatterns && noSearchResults 51 | ? __( 'No search results found.', 'block-pattern-explorer' ) 52 | : __( 53 | 'No patterns were found for this category.', 54 | 'block-pattern-explorer' 55 | ); 56 | 57 | const composite = useCompositeState(); 58 | const baseClassName = 'block-pattern-explorer__preview-pattern-list'; 59 | 60 | return ( 61 | 62 | { ! hasPatterns && ( 63 | 67 | ) } 68 | { hasPatterns && ( 69 | 81 | { shownPatterns.map( ( pattern ) => ( 82 | 89 | ) ) } 90 | 91 | ) } 92 | 93 | ); 94 | } 95 | -------------------------------------------------------------------------------- /block-pattern-explorer.php: -------------------------------------------------------------------------------- 1 | array(), 72 | 'version' => BPE_VERSION, 73 | ); 74 | } 75 | 76 | /** 77 | * Load the plugin language file. 78 | * 79 | * @since 0.1.0 80 | * @return void 81 | */ 82 | function load_textdomain() { 83 | load_plugin_textdomain( 'block-pattern-explorer', false, BPE_ABSPATH . 'languages' ); 84 | } 85 | add_action( 'init', __NAMESPACE__ . '\load_textdomain' ); 86 | 87 | /** 88 | * Enqueue the editor scripts translations. 89 | * 90 | * @since 0.1.0 91 | * @return void 92 | */ 93 | function enqueue_script_translations() { 94 | wp_set_script_translations( 95 | 'block-pattern-explorer-editor-scripts', 96 | 'block-pattern-explorer', 97 | BPE_ABSPATH . 'languages' 98 | ); 99 | } 100 | add_action( 'enqueue_block_editor_assets', __NAMESPACE__ . '\enqueue_script_translations' ); 101 | 102 | // Custom pattern category type implementation. 103 | require_once BPE_ABSPATH . '/includes/add-pattern-category-type-support.php'; 104 | 105 | // (Experimental) Will be used once Block Editor settings are filterable in core. 106 | // include_once BPE_ABSPATH . '/includes/core/add-pattern-category-type-support.php'; 107 | -------------------------------------------------------------------------------- /src/preview/header.js: -------------------------------------------------------------------------------- 1 | /** 2 | * External dependencies 3 | */ 4 | import classnames from 'classnames'; 5 | 6 | /** 7 | * WordPress dependencies 8 | */ 9 | import { __, _n, sprintf } from '@wordpress/i18n'; 10 | import { 11 | Button, 12 | DropdownMenu, 13 | MenuGroup, 14 | MenuItem, 15 | Spinner, 16 | } from '@wordpress/components'; 17 | import { check, stretchFullWidth, category } from '@wordpress/icons'; 18 | 19 | /** 20 | * Renders the block pattern preview header. 21 | * 22 | * @since 0.1.0 23 | * @param {Object} props All the props passed to this function 24 | * @return {string} Return the rendered JSX 25 | */ 26 | export default function PreviewHeader( props ) { 27 | const { 28 | viewportWidth, 29 | setViewportWidth, 30 | isGrid, 31 | setIsGrid, 32 | shownPatterns, 33 | searchValue, 34 | isLoading, 35 | } = props; 36 | 37 | const widths = [ 38 | { 39 | label: __( 'Desktop', 'block-pattern-explorer' ), 40 | slug: 'desktop', 41 | value: 1300, 42 | active: viewportWidth === 1300, 43 | }, 44 | { 45 | label: __( 'Tablet', 'block-pattern-explorer' ), 46 | slug: 'tablet', 47 | value: 778, 48 | active: viewportWidth === 778, 49 | }, 50 | { 51 | label: __( 'Mobile', 'block-pattern-explorer' ), 52 | slug: 'mobile', 53 | value: 358, 54 | active: viewportWidth === 358, 55 | }, 56 | ]; 57 | 58 | function toggleWidths( width ) { 59 | if ( ! width.active ) { 60 | setViewportWidth( width.value ); 61 | } 62 | } 63 | 64 | const baseClassName = 'block-pattern-explorer__preview-header'; 65 | 66 | return ( 67 |
68 |
69 | { isLoading && } 70 | { searchValue && 71 | searchValue.length > 1 && 72 | sprintf( 73 | // translators: %1$d: Number of patterns. %2$s: The search input. 74 | _n( 75 | '%1$d search result for "%2$s"', 76 | '%1$d search results for "%2$s"', 77 | shownPatterns.length, 78 | 'block-pattern-explorer' 79 | ), 80 | shownPatterns.length, 81 | searchValue 82 | ) } 83 |
84 |
85 | 95 | { () => ( 96 | 97 | { widths.map( ( width ) => ( 98 | toggleWidths( width ) } 105 | > 106 | { width.label } 107 | 108 | ) ) } 109 | 110 | ) } 111 | 112 |
128 |
129 | ); 130 | } 131 | -------------------------------------------------------------------------------- /readme.txt: -------------------------------------------------------------------------------- 1 | === Block Pattern Explorer === 2 | Author URI: https://wwww.nickdiego.com 3 | Contributors: ndiego, bgardner, wpengine 4 | Tags: patterns, blocks, block patterns, starter content 5 | Requires at least: 5.8 6 | Tested up to: 5.9 7 | Requires PHP: 7.1 8 | Stable tag: 0.3.0 9 | License: GPLv2 or later 10 | License URI: https://www.gnu.org/licenses/gpl-2.0.html 11 | 12 | An experimental plugin to preview and insert block patterns in the Block Editor. 13 | 14 | == Description == 15 | 16 | An experimental plugin to preview and insert block patterns in the Block Editor (Gutenberg). 17 | 18 | Please note that no block patterns are included with this plugin. Patterns must be provided by your theme or another plugin. You can also use the patterns provided by WordPress if enabled by your theme. 19 | 20 | Furthermore, this plugin should be used in conjunction with the [Gutenberg plugin](https://wordpress.org/plugins/gutenberg/) until WordPress 5.9 is officially released on January 25, 2022. 21 | 22 | === Mission === 23 | 24 | The Block Pattern Explorer is heavily influenced by the work currently being done in the Gutenberg [GitHub repository](https://github.com/WordPress/gutenberg) on pattern previews. 25 | 26 | The purpose of this project is to isolate the pattern explorer into a standalone plugin that WordPress users/developers can interact with immediately, provide feedback on, and begin implementing into their own websites. Ideally, this initiative will also help inform the direction of core development. 27 | 28 | Once the pattern explorer is fully integrated into WordPress proper, this project will be sunsetted in favor of the core offering. 29 | 30 | == Screenshots == 31 | 32 | 1. Inserting a pattern from the upcoming Twenty Twenty-Two theme into the Block Editor using the block pattern explorer. 33 | 34 | === Stay Connected === 35 | 36 | Stay up-to-date on the Block Pattern Explorer, and Gutenberg development, using the links below. The plugin is also being built transparently on GitHub, so give it a star and follow along! 😉 37 | 38 | * [Follow on Twitter](https://twitter.com/nickmdiego) 39 | * [View on GitHub](https://github.com/wpengine/block-pattern-explorer) 40 | * [Gutenberg plugin](https://wordpress.org/plugins/gutenberg/) 41 | * [Gutenberg on GitHub](https://github.com/WordPress/gutenberg) 42 | 43 | == Installation == 44 | 45 | 1. You have a couple options: 46 | * Go to Plugins → Add New and search for "Block Pattern Explorer". Once found, click "Install". 47 | * Download the Block Pattern Explorer from WordPress.org and make sure the folder is zipped. Then upload via Plugins → Add New → Upload. 48 | 2. Activate the plugin through the 'Plugins' menu in WordPress. 49 | 3. Once activated, navigate to the Block Editor and you will see the "Insert Pattern" button in header toolbar. See the plugin screenshots for reference. 50 | 51 | == Changelog == 52 | 53 | = 0.3.0 - 2022-01-13 = 54 | 55 | **Changed** 56 | 57 | * Replaced custom search component with core version. 58 | * Updated modal styling to match core pattern explorer. 59 | * Updated screenshots. 60 | 61 | **Fixed** 62 | 63 | * Fixed API bug causing the pattern explorer to be inaccessible on themes that do not utilize pattern category types. 64 | * Fixed linting and code quality errors. 65 | 66 | = 0.2.1 - 2021-11-23 = 67 | 68 | **Changed** 69 | 70 | * The button used to launch the Pattern Explorer is now disabled while pattern category types are being retrieved from the REST API. 71 | * Updated tooltip on the button used to launch the Pattern Explorer. 72 | 73 | = 0.2.0 - 2021-11-22 = 74 | 75 | **Added** 76 | 77 | * Added support for the experimental block pattern category types. 78 | 79 | = 0.1.0 - 2021-11-09 = 80 | 81 | Initial release! 🎉 82 | -------------------------------------------------------------------------------- /src/sidebar.js: -------------------------------------------------------------------------------- 1 | /** 2 | * WordPress dependencies 3 | */ 4 | import { __ } from '@wordpress/i18n'; 5 | import { 6 | MenuGroup, 7 | MenuItem, 8 | SearchControl, 9 | VisuallyHidden, 10 | } from '@wordpress/components'; 11 | import { useMemo } from '@wordpress/element'; 12 | 13 | /** 14 | * Renders the block pattern category sidebar control. 15 | * 16 | * @since 0.1.0 17 | * @param {Object} props All the props passed to this function 18 | * @return {string} Return the rendered JSX 19 | */ 20 | export default function PatternExplorerSidebar( props ) { 21 | const { 22 | patternCategories, 23 | patternCategoryTypes, 24 | selectedCategory, 25 | setSelectedCategory, 26 | searchValue, 27 | setSearchValue, 28 | } = props; 29 | 30 | function onClickCategory( category ) { 31 | setSelectedCategory( category ); 32 | setSearchValue( '' ); 33 | } 34 | 35 | const registeredCategoryTypes = useMemo( 36 | () => 37 | patternCategoryTypes.map( 38 | ( patternCategoryType ) => patternCategoryType.name 39 | ), 40 | [ patternCategoryTypes ] 41 | ); 42 | 43 | const baseClassName = 'block-pattern-explorer__sidebar'; 44 | 45 | return ( 46 |
47 |
48 | 53 |
54 | { patternCategoryTypes.map( ( categoryType ) => { 55 | const categoriesOfType = patternCategories.filter( 56 | ( category ) => { 57 | // If the selected category is uncategorized, return all 58 | // pattern categories without assigned category types. 59 | if ( categoryType.name === 'uncategorized' ) { 60 | return ( 61 | ! category?.categoryTypes || 62 | category.categoryTypes.every( 63 | ( type ) => 64 | ! registeredCategoryTypes.includes( 65 | type 66 | ) 67 | ) 68 | ); 69 | } 70 | return category.categoryTypes?.includes( 71 | categoryType.name 72 | ); 73 | } 74 | ); 75 | 76 | // If there are no categories in the current type, bail. 77 | if ( ! categoriesOfType.length ) { 78 | return null; 79 | } 80 | 81 | return ( 82 |
86 | { categoryType?.hideLabelFromVision ? ( 87 | 88 | { categoryType.label } 89 | 90 | ) : ( 91 |

94 | { categoryType.label } 95 |

96 | ) } 97 |
100 | 103 | { categoriesOfType.map( ( category ) => { 104 | return ( 105 | 115 | onClickCategory( category.name ) 116 | } 117 | > 118 | { category.label } 119 | 120 | ); 121 | } ) } 122 | 123 |
124 |
125 | ); 126 | } ) } 127 |
128 | ); 129 | } 130 | -------------------------------------------------------------------------------- /src/preview/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * External dependencies 3 | */ 4 | import { isEmpty } from 'lodash'; 5 | 6 | /** 7 | * WordPress dependencies 8 | */ 9 | import { _n, sprintf } from '@wordpress/i18n'; 10 | import { useEffect, useMemo, useState } from '@wordpress/element'; 11 | import { useAsyncList, useDebounce } from '@wordpress/compose'; 12 | import { speak } from '@wordpress/a11y'; 13 | 14 | /** 15 | * Internal dependencies 16 | */ 17 | import PreviewHeader from './header'; 18 | import PreviewPatternList from './pattern-list'; 19 | 20 | const INITIAL_INSERTER_RESULTS = 3; 21 | 22 | /** 23 | * Renders the grid of block pattern previews. 24 | * 25 | * @since 0.1.0 26 | * @param {Object} props All the props passed to this function 27 | * @return {string} Return the rendered JSX 28 | */ 29 | export default function PatternExplorerPreview( props ) { 30 | const { 31 | allPatterns, 32 | patternCategories, 33 | selectedCategory, 34 | searchValue, 35 | } = props; 36 | const [ viewportWidth, setViewportWidth ] = useState( 1300 ); 37 | const [ isGrid, setIsGrid ] = useState( true ); 38 | 39 | const debouncedSpeak = useDebounce( speak, 500 ); 40 | 41 | const registeredPatternCategories = useMemo( 42 | () => 43 | patternCategories.map( 44 | ( patternCategory ) => patternCategory.name 45 | ), 46 | [ patternCategories ] 47 | ); 48 | 49 | const filteredPatterns = useMemo( () => { 50 | let results = []; 51 | 52 | // Only start searching after the user has typed 2+ letters. 53 | const isSearching = searchValue && searchValue.length > 1; 54 | 55 | if ( isSearching ) { 56 | results = allPatterns.filter( ( pattern ) => { 57 | const input = searchValue.toLowerCase(); 58 | const title = pattern.title.toLowerCase(); 59 | 60 | // First check if the title matches. 61 | if ( title.includes( input ) ) { 62 | return true; 63 | } 64 | 65 | // Then check if any keywords match. 66 | if ( pattern?.keywords && ! isEmpty( pattern?.keywords ) ) { 67 | const keywordMatches = pattern.keywords.filter( 68 | ( keyword ) => keyword.includes( input ) 69 | ); 70 | 71 | return ! isEmpty( keywordMatches ); 72 | } 73 | 74 | return false; 75 | } ); 76 | } 77 | 78 | // Filter the pattern associated with the current category. 79 | if ( ! isSearching ) { 80 | results = allPatterns.filter( ( pattern ) => { 81 | // If the selected category is uncategorized, return all block 82 | // patterns without assigned categories. 83 | if ( selectedCategory === 'uncategorized' ) { 84 | return ( 85 | ! pattern.categories?.length || 86 | pattern.categories.every( 87 | ( category ) => 88 | ! registeredPatternCategories.includes( 89 | category 90 | ) 91 | ) 92 | ); 93 | } 94 | return pattern.categories?.includes( selectedCategory ); 95 | } ); 96 | } 97 | 98 | return results; 99 | }, [ searchValue, selectedCategory, allPatterns ] ); 100 | 101 | const shownPatterns = useAsyncList( filteredPatterns, { 102 | step: INITIAL_INSERTER_RESULTS, 103 | } ); 104 | 105 | // Are patterns still being loaded? 106 | const isLoading = shownPatterns.length < filteredPatterns.length; 107 | 108 | // Announce search results on change and only when loading is finished. 109 | // TODO: This needs work, not updating when search field is cleared. 110 | useEffect( () => { 111 | if ( ! searchValue || isLoading ) { 112 | return; 113 | } 114 | const count = filteredPatterns.length; 115 | const resultsFoundMessage = sprintf( 116 | /* translators: %d: number of patterns found. */ 117 | _n( 118 | '%d pattern found.', 119 | '%d patterns found.', 120 | count, 121 | 'block-pattern-explorer' 122 | ), 123 | count 124 | ); 125 | debouncedSpeak( resultsFoundMessage ); 126 | }, [ searchValue, debouncedSpeak ] ); 127 | 128 | const baseClassName = 'block-pattern-explorer__preview'; 129 | 130 | return ( 131 |
132 | 141 | 148 |
149 | ); 150 | } 151 | -------------------------------------------------------------------------------- /src/core-hooks/use-insertion-point.js: -------------------------------------------------------------------------------- 1 | /** 2 | * External dependencies 3 | */ 4 | import { castArray } from 'lodash'; 5 | 6 | /** 7 | * WordPress dependencies 8 | */ 9 | import { useDispatch, useSelect } from '@wordpress/data'; 10 | import { isUnmodifiedDefaultBlock } from '@wordpress/blocks'; 11 | import { _n, sprintf } from '@wordpress/i18n'; 12 | import { speak } from '@wordpress/a11y'; 13 | import { useCallback } from '@wordpress/element'; 14 | import { store as blockEditorStore } from '@wordpress/block-editor'; 15 | 16 | /** 17 | * @typedef WPInserterConfig 18 | * @property {string=} rootClientId If set, insertion will be into the block with this ID. 19 | * @property {number=} insertionIndex If set, insertion will be into this explicit position. 20 | * @property {string=} clientId If set, insertion will be after the block with this ID. 21 | * @property {boolean=} isAppender Whether the inserter is an appender or not. 22 | * @property {Function=} onSelect Called after insertion. 23 | */ 24 | 25 | /** 26 | * Returns the insertion point state given the inserter config. 27 | * 28 | * @param {WPInserterConfig} config Inserter Config. 29 | * @return {Array} Insertion Point State (rootClientID, onInsertBlocks and onToggle). 30 | */ 31 | export default function useInsertionPoint( { 32 | rootClientId = '', 33 | insertionIndex, 34 | clientId, 35 | isAppender, 36 | onSelect, 37 | shouldFocusBlock = true, 38 | } ) { 39 | const { getSelectedBlock } = useSelect( blockEditorStore ); 40 | const { destinationRootClientId, destinationIndex } = useSelect( 41 | ( select ) => { 42 | const { 43 | getSelectedBlockClientId, 44 | getBlockRootClientId, 45 | getBlockIndex, 46 | getBlockOrder, 47 | } = select( blockEditorStore ); 48 | const selectedBlockClientId = getSelectedBlockClientId(); 49 | 50 | let _destinationRootClientId = rootClientId; 51 | let _destinationIndex; 52 | 53 | if ( insertionIndex !== undefined ) { 54 | // Insert into a specific index. 55 | _destinationIndex = insertionIndex; 56 | } else if ( clientId ) { 57 | // Insert after a specific client ID. 58 | _destinationIndex = getBlockIndex( 59 | clientId, 60 | _destinationRootClientId 61 | ); 62 | } else if ( ! isAppender && selectedBlockClientId ) { 63 | _destinationRootClientId = getBlockRootClientId( 64 | selectedBlockClientId 65 | ); 66 | _destinationIndex = 67 | getBlockIndex( 68 | selectedBlockClientId, 69 | _destinationRootClientId 70 | ) + 1; 71 | } else { 72 | // Insert at the end of the list. 73 | _destinationIndex = getBlockOrder( _destinationRootClientId ) 74 | .length; 75 | } 76 | 77 | return { 78 | destinationRootClientId: _destinationRootClientId, 79 | destinationIndex: _destinationIndex, 80 | }; 81 | }, 82 | [ rootClientId, insertionIndex, clientId, isAppender ] 83 | ); 84 | 85 | const { 86 | replaceBlocks, 87 | insertBlocks, 88 | showInsertionPoint, 89 | hideInsertionPoint, 90 | } = useDispatch( blockEditorStore ); 91 | 92 | const onInsertBlocks = useCallback( 93 | ( blocks, meta, shouldForceFocusBlock = false ) => { 94 | const selectedBlock = getSelectedBlock(); 95 | 96 | if ( 97 | ! isAppender && 98 | selectedBlock && 99 | isUnmodifiedDefaultBlock( selectedBlock ) 100 | ) { 101 | replaceBlocks( 102 | selectedBlock.clientId, 103 | blocks, 104 | null, 105 | shouldFocusBlock || shouldForceFocusBlock ? 0 : null, 106 | meta 107 | ); 108 | } else { 109 | insertBlocks( 110 | blocks, 111 | destinationIndex, 112 | destinationRootClientId, 113 | true, 114 | shouldFocusBlock || shouldForceFocusBlock ? 0 : null, 115 | meta 116 | ); 117 | } 118 | const message = sprintf( 119 | // translators: %d: the name of the block that has been added 120 | _n( 121 | '%d block added.', 122 | '%d blocks added.', 123 | castArray( blocks ).length 124 | ), 125 | castArray( blocks ).length 126 | ); 127 | speak( message ); 128 | 129 | if ( onSelect ) { 130 | onSelect(); 131 | } 132 | }, 133 | [ 134 | isAppender, 135 | getSelectedBlock, 136 | replaceBlocks, 137 | insertBlocks, 138 | destinationRootClientId, 139 | destinationIndex, 140 | onSelect, 141 | shouldFocusBlock, 142 | ] 143 | ); 144 | 145 | const onToggleInsertionPoint = useCallback( 146 | ( show ) => { 147 | if ( show ) { 148 | showInsertionPoint( destinationRootClientId, destinationIndex ); 149 | } else { 150 | hideInsertionPoint(); 151 | } 152 | }, 153 | [ 154 | showInsertionPoint, 155 | hideInsertionPoint, 156 | destinationRootClientId, 157 | destinationIndex, 158 | ] 159 | ); 160 | 161 | return [ destinationRootClientId, onInsertBlocks, onToggleInsertionPoint ]; 162 | } 163 | -------------------------------------------------------------------------------- /includes/class-bpe-block-pattern-category-types-registry.php: -------------------------------------------------------------------------------- 1 | registered_category_types[ $category_type_name ] = array_merge( 54 | array( 'name' => $category_type_name ), 55 | $category_type_properties 56 | ); 57 | 58 | return true; 59 | } 60 | 61 | /** 62 | * Unregisters a pattern category type. 63 | * 64 | * @since 0.2.0 65 | * 66 | * @param string $category_type_name Pattern category type name including namespace. 67 | * @return bool True if the pattern category type was unregistered with success and false otherwise. 68 | */ 69 | public function unregister( $category_type_name ) { 70 | if ( ! $this->is_registered( $category_type_name ) ) { 71 | _doing_it_wrong( 72 | __METHOD__, 73 | esc_html( 74 | sprintf( 75 | /* translators: %s: Block pattern categpry type name. */ 76 | __( 77 | 'Block pattern category type "%s" not found.', 78 | 'block-pattern-explorer' 79 | ), 80 | $category_type_name 81 | ) 82 | ), 83 | '0.2.0' 84 | ); 85 | return false; 86 | } 87 | 88 | unset( $this->registered_category_types[ $category_type_name ] ); 89 | 90 | return true; 91 | } 92 | 93 | /** 94 | * Retrieves an array containing the properties of a registered pattern category type. 95 | * 96 | * @since 0.2.0 97 | * 98 | * @param string $category_type_name Pattern category type name including namespace. 99 | * @return array Registered pattern category type properties. 100 | */ 101 | public function get_registered( $category_type_name ) { 102 | if ( ! $this->is_registered( $category_type_name ) ) { 103 | return null; 104 | } 105 | 106 | return $this->registered_category_types[ $category_type_name ]; 107 | } 108 | 109 | /** 110 | * Retrieves all registered pattern category types. 111 | * 112 | * @since 0.2.0 113 | * 114 | * @return array Array of arrays containing the registered pattern category types. 115 | */ 116 | public function get_all_registered() { 117 | return array_values( $this->registered_category_types ); 118 | } 119 | 120 | /** 121 | * Checks if a pattern category type is registered. 122 | * 123 | * @since 0.2.0 124 | * 125 | * @param string $category_type_name Pattern category name including namespace. 126 | * @return bool True if the pattern category type is registered, false otherwise. 127 | */ 128 | public function is_registered( $category_type_name ) { 129 | return isset( $this->registered_category_types[ $category_type_name ] ); 130 | } 131 | 132 | /** 133 | * Utility method to retrieve the main instance of the class. 134 | * 135 | * The instance will be created if it does not exist yet. 136 | * 137 | * @since 0.2.0 138 | * 139 | * @return BPE_Block_Pattern_Category_Types_Registry The main instance. 140 | */ 141 | public static function get_instance() { 142 | if ( null === self::$instance ) { 143 | self::$instance = new self(); 144 | } 145 | 146 | return self::$instance; 147 | } 148 | } 149 | 150 | /** 151 | * Registers a new pattern category type. 152 | * 153 | * Note: This function is purposefully not namespaced/prefixed. It is designed 154 | * to emulate a similar function that will be proposed for inclusion in core. 155 | * 156 | * @since 0.2.0 157 | * 158 | * @param string $category_type_name Pattern category type name including namespace. 159 | * @param array $category_type_properties Array containing the properties of the category type. 160 | * @return bool True if the pattern category type was registered with success and false otherwise. 161 | */ 162 | // phpcs:ignore 163 | function register_block_pattern_category_type( $category_type_name, $category_type_properties ) { 164 | return BPE_Block_Pattern_Category_Types_Registry::get_instance()->register( $category_type_name, $category_type_properties ); 165 | } 166 | 167 | /** 168 | * Unregisters a pattern category type. 169 | * 170 | * Note: This function is purposefully not namespaced/prefixed. It is designed 171 | * to emulate a similar function that will be proposed for inclusion in core. 172 | * 173 | * @since 0.2.0 174 | * 175 | * @param string $category_type_name Pattern category type name including namespace. 176 | * @return bool True if the pattern category type was unregistered with success and false otherwise. 177 | */ 178 | // phpcs:ignore 179 | function unregister_block_pattern_category_type( $category_type_name ) { 180 | return BPE_Block_Pattern_Category_Types_Registry::get_instance()->unregister( $category_type_name ); 181 | } 182 | -------------------------------------------------------------------------------- /src/style.scss: -------------------------------------------------------------------------------- 1 | .block-pattern-explorer__modal { 2 | .components-modal__content { 3 | flex: 1; /* Will likely not be needed in WP 5.9 */ 4 | overflow: auto; 5 | padding: 0; 6 | 7 | &:before { 8 | margin-bottom: 0; 9 | } 10 | } 11 | } 12 | 13 | .block-pattern-explorer { 14 | align-items: stretch; 15 | display: flex; 16 | height: 100%; 17 | 18 | &.is-error { 19 | display: block; 20 | margin: 24px 32px; 21 | } 22 | 23 | .components-notice { 24 | margin: 0; 25 | 26 | .components-notice__content { 27 | margin-top: 8px; 28 | margin-bottom: 8px; 29 | } 30 | 31 | &.is-error { 32 | background-color: #f8ebea; 33 | } 34 | 35 | p { 36 | margin: 12px 0 0; 37 | 38 | &:first-child { 39 | margin-top: 0; 40 | } 41 | } 42 | } 43 | 44 | .block-pattern-explorer__preview { 45 | display: flex; 46 | flex-direction: column; 47 | flex-shrink: 0; 48 | overflow: auto; 49 | padding: 32px 32px 100px; 50 | width: calc(100% - 281px); 51 | 52 | .block-editor-inserter__no-results { 53 | align-items: center; 54 | display: flex; 55 | height: 100%; 56 | justify-content: center; 57 | } 58 | } 59 | 60 | .block-pattern-explorer__preview-header { 61 | align-items: center; 62 | display: inline-flex; 63 | justify-content: space-between; 64 | margin-bottom: 2rem; 65 | 66 | &__search-results { 67 | display: inline-flex; 68 | 69 | .components-spinner { 70 | margin: 0 12px 0 0; 71 | } 72 | } 73 | 74 | &__controls { 75 | display: inline-flex; 76 | 77 | .viewport-toggle { 78 | margin-right: 6px; 79 | } 80 | 81 | &>button { 82 | margin-left: 6px; 83 | } 84 | } 85 | 86 | /* Temp fix for DropdownMenu component. */ 87 | .components-popover__content { 88 | margin-top: -50px; 89 | margin-right: 48px !important; 90 | } 91 | } 92 | 93 | .block-pattern-explorer__preview-pattern-list { 94 | width: 100%; 95 | 96 | &>div { 97 | margin-bottom: 2rem; 98 | } 99 | 100 | &.preview-tablet { 101 | &>div { 102 | max-width: 790px; 103 | margin: 0 auto 4rem; 104 | } 105 | } 106 | 107 | &.preview-mobile { 108 | &>div { 109 | max-width: 358px; 110 | margin: 0 auto 4rem; 111 | } 112 | } 113 | 114 | &.is-grid { 115 | display: grid; 116 | grid-gap: 32px; 117 | grid-template: inherit; 118 | grid-template-columns: repeat(1,1fr); 119 | 120 | @media (min-width: 1080px) { 121 | grid-template-columns: repeat(2,1fr); 122 | } 123 | 124 | @media ( min-width: 1440px ) { 125 | grid-template-columns: repeat(3,1fr); 126 | } 127 | 128 | &>div { 129 | margin-bottom: 0; 130 | } 131 | 132 | &.preview-tablet, 133 | &.preview-mobile { 134 | &>div { 135 | margin: 0; 136 | } 137 | } 138 | 139 | .block-editor-block-preview__container { 140 | max-height: 400px; 141 | overflow: scroll; 142 | } 143 | } 144 | 145 | &.no-results { 146 | align-items: center; 147 | display: flex; 148 | height: 100%; 149 | justify-content: center; 150 | } 151 | 152 | &__item { 153 | border: 1px solid #dddddd; 154 | border-radius: 2px; 155 | display: flex; 156 | flex-direction: column; 157 | justify-content: space-between; 158 | position: relative; 159 | transition: all .05s ease-in-out; 160 | width: 100%; 161 | 162 | &:hover { 163 | border-color: var(--wp-admin-theme-color); 164 | } 165 | 166 | &-preview { 167 | align-items: center; 168 | background: #f0f0f0; 169 | cursor: pointer; 170 | display: flex; 171 | flex-grow: 1; 172 | min-height: 200px; 173 | 174 | img { 175 | width: 100%; 176 | } 177 | } 178 | 179 | &-actions { 180 | align-items: center; 181 | background: #fff; 182 | border-top: 1px solid #ddd; 183 | display: flex; 184 | justify-content: space-between; 185 | padding: 10px; 186 | } 187 | 188 | &-title { 189 | font-size: 12px; 190 | padding: 6px; 191 | text-align: center; 192 | } 193 | } 194 | } 195 | 196 | .block-pattern-explorer__preview-loading { 197 | display: flex; 198 | justify-content: center; 199 | margin: 64px 0; 200 | width: 100%; 201 | } 202 | 203 | .block-pattern-explorer__sidebar { 204 | border-right: 1px solid #ddd; 205 | display: flex; 206 | flex-direction: column; 207 | flex-shrink: 0; 208 | overflow-y: scroll; 209 | padding: 32px; 210 | width: 280px; 211 | 212 | &__search { 213 | margin-bottom: 16px; 214 | 215 | .components-base-control__field { 216 | margin-bottom: 0; 217 | } 218 | } 219 | 220 | &__category-type { 221 | &__title { 222 | color: #757575; 223 | font-size: 11px; 224 | font-weight: 500; 225 | margin: 0; 226 | padding: 16px 12px 0; 227 | text-transform: uppercase; 228 | } 229 | 230 | &__categories { 231 | padding: 16px 0; 232 | } 233 | } 234 | } 235 | } 236 | -------------------------------------------------------------------------------- /src/index.js: -------------------------------------------------------------------------------- 1 | /** 2 | * External dependencies. 3 | */ 4 | import { isEmpty } from 'lodash'; 5 | 6 | /** 7 | * WordPress dependencies. 8 | */ 9 | import { __ } from '@wordpress/i18n'; 10 | import { render, useState, useMemo, useCallback } from '@wordpress/element'; 11 | import { dispatch, subscribe } from '@wordpress/data'; 12 | import { Button, Modal } from '@wordpress/components'; 13 | import { layout } from '@wordpress/icons'; 14 | 15 | /** 16 | * Internal dependencies 17 | */ 18 | import PatternExplorer from './pattern-explorer'; 19 | import usePatternsState from './core-hooks/use-patterns-state'; 20 | 21 | /** 22 | * Render the header toolbar button and the accompanying pattern explorer modal. 23 | * 24 | * @since 0.1.0 25 | * @return {string} Return the rendered JSX for the Pattern Explorer Button 26 | */ 27 | function HeaderToolbarButton() { 28 | const [ isModalOpen, setIsModalOpen ] = useState( false ); 29 | const [ allPatterns, allCategories, allCategoryTypes ] = usePatternsState(); 30 | 31 | const fetchedCategoryTypes = 32 | allCategoryTypes === 'fetching' ? [] : allCategoryTypes; 33 | 34 | // Check if a pattern has an assigned pattern category. 35 | const hasRegisteredCategory = useCallback( 36 | ( pattern ) => { 37 | if ( ! pattern.categories || ! pattern.categories.length ) { 38 | return false; 39 | } 40 | 41 | return pattern.categories.some( ( cat ) => 42 | allCategories.some( ( category ) => category.name === cat ) 43 | ); 44 | }, 45 | [ allCategories ] 46 | ); 47 | 48 | // Check if a pattern category has an assigned pattern category type. 49 | const hasRegisteredCategoryType = useCallback( 50 | ( category ) => { 51 | if ( ! category.categoryTypes || ! category.categoryTypes.length ) { 52 | return false; 53 | } 54 | 55 | return category.categoryTypes.some( ( type ) => 56 | fetchedCategoryTypes.some( 57 | ( categoryType ) => categoryType.name === type 58 | ) 59 | ); 60 | }, 61 | [ fetchedCategoryTypes ] 62 | ); 63 | 64 | // Remove any categories without patterns. 65 | const populatedCategories = useMemo( () => { 66 | const categories = allCategories 67 | .filter( ( category ) => 68 | allPatterns.some( ( pattern ) => 69 | pattern.categories?.includes( category.name ) 70 | ) 71 | ) 72 | .sort( ( { name: currentName }, { name: nextName } ) => { 73 | if ( ! [ currentName, nextName ].includes( 'featured' ) ) { 74 | return 0; 75 | } 76 | return currentName === 'featured' ? -1 : 1; 77 | } ); 78 | 79 | // If there are patterns without categories, create Uncategorized. 80 | if ( 81 | allPatterns.some( 82 | ( pattern ) => ! hasRegisteredCategory( pattern ) 83 | ) && 84 | ! categories.find( 85 | ( category ) => category.name === 'uncategorized' 86 | ) 87 | ) { 88 | categories.push( { 89 | name: 'uncategorized', 90 | label: __( 'Uncategorized', 'block-pattern-explorer' ), 91 | } ); 92 | } 93 | 94 | return categories; 95 | }, [ allPatterns, allCategories ] ); 96 | 97 | // Remove any pattern category type without populated pattern categories. 98 | const populatedCategoryTypes = useMemo( () => { 99 | const categoryTypes = fetchedCategoryTypes.filter( ( type ) => 100 | populatedCategories.some( ( category ) => 101 | category.categoryTypes?.includes( type.name ) 102 | ) 103 | ); 104 | 105 | // If there are categories without types, create the Uncategorized type. 106 | if ( 107 | populatedCategories.some( 108 | ( category ) => ! hasRegisteredCategoryType( category ) 109 | ) && 110 | ! categoryTypes.find( ( type ) => type.name === 'uncategorized' ) 111 | ) { 112 | categoryTypes.unshift( { 113 | name: 'uncategorized', 114 | label: __( 'Uncategorized', 'block-pattern-explorer' ), 115 | hideLabelFromVision: true, 116 | } ); 117 | } 118 | 119 | return categoryTypes; 120 | }, [ populatedCategories, fetchedCategoryTypes ] ); 121 | 122 | // Could expand on this in the future, i.e. allow for a configurable 123 | // initial category. For now the initial category is the first category in 124 | // the first category type. 125 | const initialCategory = populatedCategories.filter( ( category ) => { 126 | // If the first category type is 'uncategorized', filter all categories 127 | // without types and all categories with the type 'uncategorized'. 128 | if ( populatedCategoryTypes[ 0 ].name === 'uncategorized' ) { 129 | return ( 130 | ! category.categoryTypes || 131 | ! category.categoryTypes.length || 132 | category.categoryTypes?.includes( 'uncategorized' ) 133 | ); 134 | } 135 | 136 | // If the first type is not 'uncategorized', filter all the categories in the 137 | // first type. 138 | return category.categoryTypes?.includes( 139 | populatedCategoryTypes[ 0 ].name 140 | ); 141 | } )[ 0 ]; 142 | 143 | // If there are no patterns, do not display the pattern explorer button. 144 | if ( isEmpty( allPatterns ) ) { 145 | return null; 146 | } 147 | 148 | return ( 149 | <> 150 |