diff --git a/plugins/woocommerce-blocks/.distignore b/plugins/woocommerce-blocks/.distignore new file mode 100644 index 00000000000..b802f683f53 --- /dev/null +++ b/plugins/woocommerce-blocks/.distignore @@ -0,0 +1,42 @@ +/.github +/.git +/.wordpress-org +/.sources +/bin +/docs +/node_modules +/patches +/storybook +/tests +/playwright-report + +.editorconfig +.env +.distignore +.eslintignore +.eslintrc.js +.gitattributes +.gitignore +.nvmrc +.prettierrc +.stylelintrc.json +.travis.yml +.wp-env.json +babel.config.js +blocks.ini +composer.json +composer.lock +docker-compose.yml +global.d.ts +package.json +package-lock.json +phpcs.xml +phpunit.xml.dist +postcss.config.js +README.md +renovate.json +tsconfig.json +tsconfig.base.json +webpack.config.js +woocommerce-gutenberg-products-block.zip +checklist.xml diff --git a/plugins/woocommerce-blocks/.editorconfig b/plugins/woocommerce-blocks/.editorconfig new file mode 100644 index 00000000000..e71bb8db345 --- /dev/null +++ b/plugins/woocommerce-blocks/.editorconfig @@ -0,0 +1,24 @@ +# This file is for unifying the coding style for different editors and IDEs +# editorconfig.org + +# WordPress Coding Standards +# https://make.wordpress.org/core/handbook/coding-standards/ + +root = true + +[*] +charset = utf-8 +end_of_line = lf +indent_size = 4 +tab_width = 4 +indent_style = tab +insert_final_newline = true +trim_trailing_whitespace = true + +[*.txt] +trim_trailing_whitespace = false + +[*.yml] +trim_trailing_whitespace = false +indent_style = space +indent_size = 2 diff --git a/plugins/woocommerce-blocks/.env b/plugins/woocommerce-blocks/.env new file mode 100644 index 00000000000..53b93779bd9 --- /dev/null +++ b/plugins/woocommerce-blocks/.env @@ -0,0 +1,16 @@ +# WordPress container environment +WORDPRESS_DB_HOST=db +WORDPRESS_DB_NAME=wordpress +WORDPRESS_DB_USER=wordpress +WORDPRESS_DB_PASSWORD=wordpress + +# WordPress CLI environment +WORDPRESS_PORT=8889 +WORDPRESS_BASE_URL=http://localhost:8889 +WORDPRESS_HOST=wordpress-www:80 +WORDPRESS_TITLE=WooCommerce Core E2E Test Suite +WORDPRESS_LOGIN=admin +WORDPRESS_PASSWORD=password +WORDPRESS_EMAIL=admin@woocommercecoree2etestsuite.com +WP_VERSION=latest +WOO_VERSION=latest diff --git a/plugins/woocommerce-blocks/.eslintignore b/plugins/woocommerce-blocks/.eslintignore new file mode 100644 index 00000000000..b3005136eed --- /dev/null +++ b/plugins/woocommerce-blocks/.eslintignore @@ -0,0 +1,14 @@ +!.eslintrc.js +build +build-module +coverage +languages +node_modules +vendor +legacy +reports +tests/e2e-jest/specs/backend/__fixtures__ +tests/e2e-jest/specs/backend/__snapshots__ + +storybook/dist +assets/js/interactivity diff --git a/plugins/woocommerce-blocks/.eslintrc.js b/plugins/woocommerce-blocks/.eslintrc.js new file mode 100644 index 00000000000..2d837d7a918 --- /dev/null +++ b/plugins/woocommerce-blocks/.eslintrc.js @@ -0,0 +1,291 @@ +const restrictedImports = [ + { + name: 'lodash', + importNames: [ + 'camelCase', + 'capitalize', + 'castArray', + 'chunk', + 'clamp', + 'clone', + 'cloneDeep', + 'compact', + 'concat', + 'countBy', + 'debounce', + 'deburr', + 'defaults', + 'defaultTo', + 'delay', + 'difference', + 'differenceWith', + 'dropRight', + 'each', + 'escape', + 'escapeRegExp', + 'every', + 'extend', + 'filter', + 'find', + 'findIndex', + 'findKey', + 'findLast', + 'first', + 'flatMap', + 'flatten', + 'flattenDeep', + 'flow', + 'flowRight', + 'forEach', + 'fromPairs', + 'has', + 'identity', + 'includes', + 'invoke', + 'isArray', + 'isBoolean', + 'isEqual', + 'isFinite', + 'isFunction', + 'isMatch', + 'isNil', + 'isNumber', + 'isObject', + 'isObjectLike', + 'isPlainObject', + 'isString', + 'isUndefined', + 'keyBy', + 'keys', + 'last', + 'lowerCase', + 'map', + 'mapKeys', + 'maxBy', + 'memoize', + 'merge', + 'negate', + 'noop', + 'nth', + 'omit', + 'omitBy', + 'once', + 'orderby', + 'overEvery', + 'partial', + 'partialRight', + 'pick', + 'pickBy', + 'random', + 'reduce', + 'reject', + 'repeat', + 'reverse', + 'setWith', + 'size', + 'snakeCase', + 'some', + 'sortBy', + 'startCase', + 'startsWith', + 'stubFalse', + 'stubTrue', + 'sum', + 'sumBy', + 'take', + 'throttle', + 'times', + 'toString', + 'trim', + 'truncate', + 'unescape', + 'unionBy', + 'uniq', + 'uniqBy', + 'uniqueId', + 'uniqWith', + 'upperFirst', + 'values', + 'without', + 'words', + 'xor', + 'zip', + ], + message: + 'This Lodash method is not recommended. Please use native functionality instead. If using `memoize`, please use `memize` instead.', + }, +]; + +module.exports = { + env: { + browser: true, + }, + root: true, + extends: [ + 'plugin:@woocommerce/eslint-plugin/recommended', + 'plugin:you-dont-need-lodash-underscore/compatible', + 'plugin:storybook/recommended', + ], + globals: { + wcBlocksMiddlewareConfig: 'readonly', + fetchMock: true, + jQuery: 'readonly', + IntersectionObserver: 'readonly', + // @todo Move E2E related ESLint configuration into custom config. + // + // We should have linting properties only included for files that they + // are specific to as opposed to globally. + page: 'readonly', + browser: 'readonly', + context: 'readonly', + jestPuppeteer: 'readonly', + }, + settings: { + jsdoc: { mode: 'typescript' }, + // List of modules that are externals in our webpack config. + // This helps the `import/no-extraneous-dependencies` and + //`import/no-unresolved` rules account for them. + 'import/core-modules': [ + '@woocommerce/block-data', + '@woocommerce/blocks-checkout', + '@woocommerce/blocks-components', + '@woocommerce/price-format', + '@woocommerce/settings', + '@woocommerce/shared-context', + '@woocommerce/shared-hocs', + '@woocommerce/data', + '@wordpress/a11y', + '@wordpress/api-fetch', + '@wordpress/block-editor', + '@wordpress/compose', + '@wordpress/data', + '@wordpress/core-data', + '@wordpress/editor', + '@wordpress/escape-html', + '@wordpress/hooks', + '@wordpress/keycodes', + '@wordpress/url', + '@woocommerce/blocks-test-utils', + '@woocommerce/e2e-utils', + '@woocommerce/e2e-mocks', + 'babel-jest', + 'dotenv', + 'jest-environment-puppeteer', + 'lodash/kebabCase', + 'lodash', + 'prop-types', + 'react', + 'requireindex', + 'react-transition-group', + ], + 'import/resolver': { + node: {}, + webpack: {}, + typescript: {}, + }, + }, + rules: { + 'woocommerce/feature-flag': 'off', + 'react-hooks/exhaustive-deps': 'error', + 'react/jsx-fragments': [ 'error', 'syntax' ], + '@wordpress/no-global-active-element': 'warn', + '@wordpress/i18n-text-domain': [ + 'error', + { + allowedTextDomain: [ 'woo-gutenberg-products-block' ], + }, + ], + 'no-restricted-imports': [ + 'error', + { + paths: restrictedImports, + }, + ], + '@typescript-eslint/no-restricted-imports': [ + 'error', + { + paths: [ + { + name: 'react', + message: + 'Please use React API through `@wordpress/element` instead.', + allowTypeImports: true, + }, + ], + }, + ], + camelcase: [ + 'error', + { + properties: 'never', + ignoreGlobals: true, + }, + ], + 'react/react-in-jsx-scope': 'off', + }, + overrides: [ + { + files: [ '**/tests/e2e-jest/**' ], + rules: { + 'jest/no-disabled-tests': 'off', + }, + }, + { + files: [ '**/bin/**.js', '**/storybook/**.js', '**/stories/**.js' ], + rules: { + 'you-dont-need-lodash-underscore/omit': 'off', + }, + }, + { + files: [ '*.ts', '*.tsx' ], + parser: '@typescript-eslint/parser', + extends: [ + 'plugin:@woocommerce/eslint-plugin/recommended', + 'plugin:you-dont-need-lodash-underscore/compatible', + 'plugin:@typescript-eslint/recommended', + ], + rules: { + '@typescript-eslint/no-explicit-any': 'error', + 'no-use-before-define': 'off', + '@typescript-eslint/no-use-before-define': [ 'error' ], + 'jsdoc/require-param': 'off', + 'no-shadow': 'off', + '@typescript-eslint/no-shadow': [ 'error' ], + '@typescript-eslint/no-unused-vars': [ + 'error', + { ignoreRestSiblings: true }, + ], + camelcase: 'off', + '@typescript-eslint/naming-convention': [ + 'error', + { + selector: [ 'method', 'variableLike' ], + format: [ 'camelCase', 'PascalCase', 'UPPER_CASE' ], + leadingUnderscore: 'allowSingleOrDouble', + filter: { + regex: 'webpack_public_path__', + match: false, + }, + }, + { + selector: 'typeProperty', + format: [ 'camelCase', 'snake_case' ], + filter: { + regex: 'API_FETCH_WITH_HEADERS|Block', + match: false, + }, + }, + ], + 'react/react-in-jsx-scope': 'off', + }, + }, + { + files: [ './assets/js/mapped-types.ts' ], + rules: { + '@typescript-eslint/no-explicit-any': 'off', + '@typescript-eslint/no-shadow': 'off', + 'no-shadow': 'off', + }, + }, + ], +}; diff --git a/plugins/woocommerce-blocks/.gitattributes b/plugins/woocommerce-blocks/.gitattributes new file mode 100644 index 00000000000..fe40586d798 --- /dev/null +++ b/plugins/woocommerce-blocks/.gitattributes @@ -0,0 +1,32 @@ +# Ignore all hidden files and directories +/.* export-ignore + +# Ignore all markdown files +/*.md export-ignore + +# Ignore following directories and contents +/node_modules* export-ignore +/tests export-ignore +/bin export-ignore +/docs export-ignore +/storybook export-ignore + +# Ignore following configuration files +/phpcs.xml export-ignore +/phpunit.* export-ignore +/composer.lock export-ignore +/composer.json export-ignore +/CODEOWNERS export-ignore +/renovate.json export-ignore +/webpack.config.js export-ignore +/postcss.config.js export-ignore +/bundlesize.config.json export-ignore +/package.json export-ignore +/package-lock.json export-ignore +/babel.config.js export-ignore +/docker-compose.yml export-ignore +/globals.d.ts export-ignore +/tsconfig.json export-ignore +/tsconfig.base.json export-ignore +/tsconfig.base export-ignore +/webpack.config.js export-ignore diff --git a/plugins/woocommerce-blocks/.github/CODE_OF_CONDUCT.md b/plugins/woocommerce-blocks/.github/CODE_OF_CONDUCT.md new file mode 100644 index 00000000000..e0d865b5a5f --- /dev/null +++ b/plugins/woocommerce-blocks/.github/CODE_OF_CONDUCT.md @@ -0,0 +1,46 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, gender identity and expression, level of experience, nationality, personal appearance, race, religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment include: + +- Using welcoming and inclusive language +- Being respectful of differing viewpoints and experiences +- Gracefully accepting constructive criticism +- Focusing on what is best for the community +- Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +- The use of sexualized language or imagery and unwelcome sexual attention or advances +- Trolling, insulting/derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or electronic address, without explicit permission +- Other conduct which could reasonably be considered inappropriate in a professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces when an individual is representing the project or its community. Examples of representing a project or community include using an official project email address, posting via an official social media account, or acting as an appointed representative at an online or offline event. Representation of a project may be further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by contacting the project team at support@woocommerce.com. The project team will review and investigate all complaints, and will respond in a way that it deems appropriate to the circumstances. The project team is obligated to maintain confidentiality with regard to the reporter of an incident. Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good faith may face temporary or permanent repercussions as determined by other members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, available at [http://contributor-covenant.org/version/1/4][version] + +[homepage]: http://contributor-covenant.org +[version]: http://contributor-covenant.org/version/1/4/ diff --git a/plugins/woocommerce-blocks/.github/CONTRIBUTING.md b/plugins/woocommerce-blocks/.github/CONTRIBUTING.md new file mode 100644 index 00000000000..ac7d5023b32 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/CONTRIBUTING.md @@ -0,0 +1,15 @@ +# Contributing + +Thanks for your interest in contributing to WooCommerce Blocks! + +If you wish to contribute code, to get started we recommend first reading our [Getting Started Guide](../docs/contributors/getting-started.md). + +All other documentation for contributors can be found [in the docs directory](../docs/README.md). + +## Guidelines + +Like the WooCommerce project, we want to ensure a welcoming environment for everyone. With that in mind, all contributors are expected to follow our [Code of Conduct](./CODE_OF_CONDUCT.md). + +## Reporting Security Issues + +Please see [SECURITY.md](./SECURITY.md). diff --git a/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/---bug-report.md b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/---bug-report.md new file mode 100644 index 00000000000..ad1fc9e029e --- /dev/null +++ b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/---bug-report.md @@ -0,0 +1,54 @@ +--- +name: "\U0001F41E Bug report" +about: Let us know if something isn't working as you expect it to. +labels: 'type: bug' +--- + +## Describe the bug + +A clear and concise description of what the bug is. + +## To reproduce + +Steps to reproduce the behavior: + +1. Go to '...' +2. Click on '....' +3. Scroll down to '....' +4. See error + +## Expected behavior + +A clear and concise description of what you expected to happen. + +## Screenshots + +If applicable, add screenshots to help explain your problem. + +## Environment + +### WordPress (please complete the following information): + +- WordPress version: [e.g. 5.9] +- Gutenberg version (if installed): [e.g. 12.0.0] +- WooCommerce version: [e.g. 6.1] +- WooCommerce Blocks version: [e.g. 7.0.0] +- Site language: +- Any other plugins installed: + +### Desktop (please complete the following information): + +- OS: [e.g. macOS, Windows] +- Browser [e.g. chrome, safari] +- Version [e.g. 22] + +### Smartphone (please complete the following information): + +- Device: [e.g. iPhone6] +- OS: [e.g. iOS8.1] +- Browser [e.g. stock browser, safari] +- Version [e.g. 22] + +## Additional context + +Add any other context about the problem here. diff --git a/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--cart-checkout-feedback.md b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--cart-checkout-feedback.md new file mode 100644 index 00000000000..1aa2ed31f7e --- /dev/null +++ b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--cart-checkout-feedback.md @@ -0,0 +1,15 @@ +--- +name: "\U0001F4AC Feedback – Cart & Checkout Blocks" +about: Submit feedback about the new block-based Cart & Checkout. +labels: "type: feedback", "◼️ block: cart", "◼️ block: checkout" +--- + + + +## What do you like about the Cart & Checkout blocks? + +## What do you think is missing from the Cart & Checkout blocks? diff --git a/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--doc-feedback.md b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--doc-feedback.md new file mode 100644 index 00000000000..36d6d71920d --- /dev/null +++ b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--doc-feedback.md @@ -0,0 +1,9 @@ +--- +name: '📖 Feedback – Documentation' +about: Submit feedback or report an issue about some documentation. +labels: 'type: documentation' +--- + + diff --git a/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--feature-request.md b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--feature-request.md new file mode 100644 index 00000000000..2a7b6232068 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--feature-request.md @@ -0,0 +1,18 @@ +--- +name: "✨ Feature request" +about: If you have an idea to improve an existing WooCommerce + Gutenberg related + feature, please let us know or submit a Pull Request! +labels: "type: enhancement" +--- + +## Is your feature request related to a problem? Please describe. +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +## Describe the solution you'd like +A clear and concise description of what you want to happen. + +## Describe alternatives you've considered +A clear and concise description of any alternative solutions or features you've considered. + +## Additional context +Add any other context or screenshots about the feature request here. diff --git a/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--support-question.md b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--support-question.md new file mode 100644 index 00000000000..a83f6b5320b --- /dev/null +++ b/plugins/woocommerce-blocks/.github/ISSUE_TEMPLATE/--support-question.md @@ -0,0 +1,22 @@ +--- +name: "❓ Support Question" +about: If you have a question please see our docs or use our forums, helpdesk, or + Slack Community! +labels: "type: support" +--- + +We don't offer technical support on GitHub so we recommend using the following: + +## Reading our documentation +Usage docs can be found here: https://docs.woocommerce.com/ + +If you have a problem, you may want to start with the self help guide here: https://docs.woocommerce.com/document/woocommerce-self-service-guide/ + +**Technical support for premium extensions or if you're a WooCommerce.com customer** + from a human being - submit a ticket via the helpdesk +https://woocommerce.com/contact-us/ + +## General usage and development questions +- WooCommerce Slack Community: https://woocommerce.com/community-slack/ +- WordPress.org Forums: https://wordpress.org/support/plugin/woocommerce +- The WooCommerce Help and Share Facebook group diff --git a/plugins/woocommerce-blocks/.github/SECURITY.md b/plugins/woocommerce-blocks/.github/SECURITY.md new file mode 100644 index 00000000000..109d7303448 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/SECURITY.md @@ -0,0 +1,5 @@ +# Reporting Security Issues + +The WooCommerce team take security bugs seriously. We appreciate your efforts to responsibly disclose your findings, and will make every effort to acknowledge your contributions. + +For security related issues and how to report them, please visit the [Automattic Security](https://automattic.com/security/) page. diff --git a/plugins/woocommerce-blocks/.github/automate-team-review-assignment-config.yml b/plugins/woocommerce-blocks/.github/automate-team-review-assignment-config.yml new file mode 100644 index 00000000000..55e04ebd60a --- /dev/null +++ b/plugins/woocommerce-blocks/.github/automate-team-review-assignment-config.yml @@ -0,0 +1,17 @@ +when: + - author: + teamIs: + - rubik + ignore: + nameIs: + assign: + teams: + - rubik + - author: + teamIs: + - woo-fse + ignore: + nameIs: + assign: + teams: + - woo-fse diff --git a/plugins/woocommerce-blocks/.github/comments-aggregator/README.md b/plugins/woocommerce-blocks/.github/comments-aggregator/README.md new file mode 100644 index 00000000000..667f6eef86f --- /dev/null +++ b/plugins/woocommerce-blocks/.github/comments-aggregator/README.md @@ -0,0 +1,50 @@ +# comments-aggregator + +> This GitHub Action helps you keep the PR page clean by merging comments/reports by multiple workflows into a single comment. + +![screenshot](./screenshot.png) + +## Usage + +This action is meant to be used as the poster/commenter. Instead of having existing actions post the comment by themselves, set those comments as the action output, then feed that output to `comments-aggregator` to let this action manage those comments for you. + +```yml + - name: Compare Assets + uses: ./.github/compare-assets + id: compare-assets + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + compare: assets-list/assets.json + create-comment: false + - name: Append report + uses: ./.github/comments-aggregator + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + section-id: compare-assets-with-trunk + content: ${{steps.compare-assets.outputs.comment}} +``` + +## Inputs + +- **`repo-token`** (required): This is the GitHub token. This is required to manipulate PR comments. +- **`section-id`** (required): The unique ID that helps this action to update the correct part of the aggregated comment. +- **`content`** (option): The comment content. Default to empty. If nothing was provided, this action will stop gracefully. +- **`order`** (optional): The order of the comment part inside the aggregated comment. Default to 10. + +## More examples + +### Message contains GitHub Event properties + +```yml + - name: Add release ZIP URL as comment to the PR + uses: ./.github/comments-aggregator + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + section-id: release-zip-url + order: 1 + content: | + The release ZIP for this PR is accessible via: + ``` + https://wcblocks.wpcomstaging.com/wp-content/uploads/woocommerce-gutenberg-products-block-${{ github.event.pull_request.number }}.zip + ``` +``` diff --git a/plugins/woocommerce-blocks/.github/comments-aggregator/action.yml b/plugins/woocommerce-blocks/.github/comments-aggregator/action.yml new file mode 100644 index 00000000000..e26a436f1e5 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/comments-aggregator/action.yml @@ -0,0 +1,19 @@ +name: 'Comments Aggregator' +description: 'Merge bot comments into one comment to keep PR page clean' +inputs: + repo-token: + description: 'GitHub token' + required: true + section-id: + description: 'Comment section ID for the action to know which part to update' + required: true + content: + description: 'Comment content' + default: '' + order: + description: 'Order of the comment' + required: false + default: 10 +runs: + using: 'node16' + main: 'index.js' diff --git a/plugins/woocommerce-blocks/.github/comments-aggregator/index.js b/plugins/woocommerce-blocks/.github/comments-aggregator/index.js new file mode 100644 index 00000000000..5eb0b925b1e --- /dev/null +++ b/plugins/woocommerce-blocks/.github/comments-aggregator/index.js @@ -0,0 +1,84 @@ +/** + * External dependencies + */ +const { getOctokit, context } = require( '@actions/github' ); +const { setFailed, getInput } = require( '@actions/core' ); + +/** + * Internal dependencies + */ +const { updateComment, isMergedComment } = require( './utils' ); + +const runner = async () => { + try { + const token = getInput( 'repo-token', { required: true } ); + const octokit = getOctokit( token ); + const payload = context.payload; + const repo = payload.repository.name; + const owner = payload.repository.owner.login; + + // Only run this action on pull requests. + if ( ! payload.pull_request?.number ) { + return; + } + + const sectionId = getInput( 'section-id', { + required: true, + } ); + + const content = getInput( 'content' ); + const order = getInput( 'order' ); + + if ( ! sectionId || ! content ) { + return; + } + + let commentId, commentBody; + + const currentComments = await octokit.rest.issues.listComments( { + owner, + repo, + issue_number: payload.pull_request.number, + } ); + + if ( + Array.isArray( currentComments.data ) && + currentComments.data.length > 0 + ) { + const comment = currentComments.data.find( ( comment ) => + isMergedComment( comment ) + ); + + if ( comment ) { + commentId = comment.id; + commentBody = comment.body; + } + } + + commentBody = updateComment( commentBody, { + sectionId, + content, + order, + } ); + + if ( commentId ) { + await octokit.rest.issues.updateComment( { + owner, + repo, + comment_id: commentId, + body: commentBody, + } ); + } else { + await octokit.rest.issues.createComment( { + owner, + repo, + issue_number: payload.pull_request.number, + body: commentBody, + } ); + } + } catch ( error ) { + setFailed( error.message ); + } +}; + +runner(); diff --git a/plugins/woocommerce-blocks/.github/comments-aggregator/screenshot.png b/plugins/woocommerce-blocks/.github/comments-aggregator/screenshot.png new file mode 100644 index 00000000000..db6b666cf88 Binary files /dev/null and b/plugins/woocommerce-blocks/.github/comments-aggregator/screenshot.png differ diff --git a/plugins/woocommerce-blocks/.github/comments-aggregator/utils.js b/plugins/woocommerce-blocks/.github/comments-aggregator/utils.js new file mode 100644 index 00000000000..341830c90af --- /dev/null +++ b/plugins/woocommerce-blocks/.github/comments-aggregator/utils.js @@ -0,0 +1,89 @@ +const identifier = ``; +const separator = ''; +const footerText = + '[comments-aggregator](https://github.com/woocommerce/woocommerce-blocks/tree/trunk/.github/comments-aggregator)'; +const footer = `\n> ${ footerText }\n${ identifier }`; + +function getSectionId( section ) { + const match = section.match( /-- section-id: ([^\s]+) --/ ); + return match ? match[ 1 ] : null; +} + +function getSectionOrder( section ) { + const match = section.match( /-- section-order: ([^\s]+) --/ ); + return match ? match[ 1 ] : null; +} + +function parseComment( comment ) { + if ( ! comment ) { + return []; + } + const sections = comment.split( separator ); + return sections + .map( ( section ) => { + const sectionId = getSectionId( section ); + const order = getSectionOrder( section ); + /** + * This also remove the footer as it doesn't have a section id. This + * is intentional as we want the footer to always be the last + * section. + */ + if ( ! sectionId ) { + return null; + } + return { + id: sectionId, + order: parseInt( order, 10 ), + content: section.trim(), + }; + } ) + .filter( Boolean ); +} + +function updateSection( sections, data ) { + const { sectionId, content, order } = data; + const index = sections.findIndex( ( section ) => section.id === sectionId ); + const formattedContent = `\n\n\n\n${ content }`; + if ( index === -1 ) { + sections.push( { + id: sectionId, + content: formattedContent, + } ); + } else { + sections[ index ].content = formattedContent; + } + + return sections; +} + +function appendFooter( sections ) { + return sections.concat( { + id: 'footer', + content: footer, + } ); +} + +function sortSections( sections ) { + return sections.sort( ( a, b ) => a.order - b.order ); +} + +function combineSections( sections ) { + return sections + .map( ( section ) => section.content ) + .join( `\n\n${ separator }\n\n` ); +} + +exports.updateComment = function ( comment, data ) { + let sections = parseComment( comment ); + sections = updateSection( sections, data ); + sections = sortSections( sections ); + sections = appendFooter( sections ); + return combineSections( sections ); +}; + +exports.isMergedComment = function ( comment ) { + return ( + comment.body.includes( identifier ) && + comment.user.login === 'github-actions[bot]' + ); +}; diff --git a/plugins/woocommerce-blocks/.github/compare-assets/action.yml b/plugins/woocommerce-blocks/.github/compare-assets/action.yml new file mode 100644 index 00000000000..704f11f9311 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/compare-assets/action.yml @@ -0,0 +1,19 @@ +name: 'Compare Assets' +description: 'Compares two assets files created by DependencyExtractionWebpackPlugin and reports the differences.' +inputs: + repo-token: + description: 'GitHub token' + required: true + compare: + description: 'Path to assets file to compare the build assets with.' + required: true + create-comment: + description: 'Create a dedicate comment for this report?' + required: false + default: true +outputs: + comment: + description: 'Markdown comment' +runs: + using: 'node16' + main: 'index.js' diff --git a/plugins/woocommerce-blocks/.github/compare-assets/index.js b/plugins/woocommerce-blocks/.github/compare-assets/index.js new file mode 100644 index 00000000000..4e68cf12a59 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/compare-assets/index.js @@ -0,0 +1,158 @@ +/** + * External dependencies + */ +const { getOctokit, context } = require( '@actions/github' ); +const { setFailed, getInput, setOutput } = require( '@actions/core' ); + +const runner = async () => { + try { + const token = getInput( 'repo-token', { required: true } ); + const octokit = getOctokit( token ); + const payload = context.payload; + const repo = payload.repository.name; + const owner = payload.repository.owner.login; + const oldAssets = require( '../../' + + getInput( 'compare', { + required: true, + } ) ); + + if ( ! oldAssets ) { + return; + } + + const newAssets = require( '../../build/assets.json' ); + + if ( ! newAssets ) { + return; + } + + const createComment = getInput( 'create-comment' ); + + const changes = Object.fromEntries( + Object.entries( newAssets ) + .map( ( [ key, { dependencies = [] } ] ) => { + const oldDependencies = + oldAssets[ key ]?.dependencies || []; + const added = dependencies.filter( + ( dependency ) => + ! oldDependencies.includes( dependency ) + ); + const removed = oldDependencies.filter( + ( dependency ) => ! dependencies.includes( dependency ) + ); + return added.length || removed.length + ? [ + key, + { + added, + removed, + }, + ] + : null; + } ) + .filter( Boolean ) + ); + + let reportCommentId; + + { + const currentComments = await octokit.rest.issues.listComments( { + owner, + repo, + issue_number: payload.pull_request.number, + } ); + + if ( + Array.isArray( currentComments.data ) && + currentComments.data.length > 0 + ) { + const comment = currentComments.data.find( + ( comment ) => + comment.body.includes( 'Script Dependencies Report' ) && + comment.user.login === 'github-actions[bot]' + ); + + if ( comment ) { + reportCommentId = comment.id; + } + } + } + + let commentBody = ''; + + if ( Object.keys( changes ).length > 0 ) { + let reportContent = ''; + + Object.entries( changes ).forEach( + ( [ handle, { added, removed } ] ) => { + const addedDeps = added.length + ? '`' + added.join( '`, `' ) + '`' + : ''; + const removedDeps = removed.length + ? '`' + removed.join( '`, `' ) + '`' + : ''; + + let icon = ''; + + if ( added.length && removed.length ) { + icon = '❓'; + } else if ( added.length ) { + icon = '⚠️'; + } else if ( removed.length ) { + icon = '🎉'; + } + + reportContent += + `| \`${ handle }\` | ${ addedDeps } | ${ removedDeps } | ${ icon } |` + + '\n'; + } + ); + + commentBody = + '## Script Dependencies Report' + + '\n\n' + + 'The `compare-assets` action has detected some changed script dependencies between this branch and ' + + 'trunk. Please review and confirm the following are correct before merging.' + + '\n\n' + + '| Script Handle | Added | Removed | |' + + '\n' + + '| ------------- | ------| ------- | -- |' + + '\n' + + reportContent + + '\n\n' + + '__This comment was automatically generated by the `./github/compare-assets` action.__'; + } else { + commentBody = + '## Script Dependencies Report' + + '\n\n' + + 'There is no changed script dependency between this branch and trunk.' + + '\n\n' + + '__This comment was automatically generated by the `./github/compare-assets` action.__'; + } + + if ( createComment !== 'true' ) { + setOutput( 'comment', commentBody ); + return; + } + + if ( reportCommentId ) { + await octokit.rest.issues.updateComment( { + owner, + repo, + comment_id: reportCommentId, + body: commentBody, + } ); + } else { + await octokit.rest.issues.createComment( { + owner, + repo, + issue_number: payload.pull_request.number, + body: commentBody, + } ); + } + } catch ( error ) { + setFailed( error.message ); + } +}; + +runner(); diff --git a/plugins/woocommerce-blocks/.github/config.yml b/plugins/woocommerce-blocks/.github/config.yml new file mode 100644 index 00000000000..dce61b7efde --- /dev/null +++ b/plugins/woocommerce-blocks/.github/config.yml @@ -0,0 +1,3 @@ +todo: + blobLines: 10 + label: false diff --git a/plugins/woocommerce-blocks/.github/dependabot.yml b/plugins/woocommerce-blocks/.github/dependabot.yml new file mode 100644 index 00000000000..e6d8a18f8a5 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/dependabot.yml @@ -0,0 +1,35 @@ +# Basic set up for three package managers + +version: 2 +updates: + - package-ecosystem: 'github-actions' + directory: '/' + schedule: + interval: 'monthly' + open-pull-requests-limit: 10 + labels: + - "skip-changelog" + - "type: dependencies" + - "github_actions" + + # Maintain dependencies for npm + - package-ecosystem: 'npm' + directory: '/' + schedule: + interval: 'weekly' + open-pull-requests-limit: 10 + labels: + - "skip-changelog" + - "type: dependencies" + - "javascript" + + # Maintain dependencies for Composer + - package-ecosystem: 'composer' + directory: '/' + schedule: + interval: 'weekly' + open-pull-requests-limit: 10 + labels: + - "skip-changelog" + - "type: dependencies" + - "php" diff --git a/plugins/woocommerce-blocks/.github/label-sync-config.json b/plugins/woocommerce-blocks/.github/label-sync-config.json new file mode 100644 index 00000000000..a2d66df2514 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/label-sync-config.json @@ -0,0 +1,151 @@ +[ + { + "name": "category: accessibility", + "color": "5804ea", + "aliases": [ "scope: accessibility" ], + "description": "The issue/PR is related to accessibility." + }, + { + "name": "category: duplicate", + "color": "5804ea", + "aliases": [], + "description": "The issue/PR is a duplicate of another issue." + }, + { + "name": "category: i18n", + "color": "5804ea", + "aliases": [ "scope: i18n" ], + "description": "The issue/PR is related to internationalization." + }, + { + "name": "category: performance", + "color": "5804ea", + "aliases": [ "type: performance" ], + "description": "The issue/PR is related to performance." + }, + { + "name": "category: refactor", + "color": "5804ea", + "aliases": [ "type: refactor" ], + "description": "The issue/PR is related to refactoring." + }, + { + "name": "category: won't fix", + "color": "5804ea", + "aliases": [], + "description": "The issue won’t be fixed." + }, + { + "name": "good first issue", + "color": "1eff05", + "aliases": [ "type: good first issue", "[Type] Good First Change" ], + "description": "The issue is a good candidate for the first community contribution/for a newcomer to the team." + }, + { + "name": "impact: high", + "color": "d73a4a", + "aliases": [], + "description": "This issue impacts a lot of users as reported by our Happiness Engineers." + }, + { + "name": "needs design", + "color": "ed95d2", + "aliases": [ "action: needs design", "[Status] Needs Design" ], + "description": "The issue requires design input/work from a designer." + }, + { + "name": "needs docs", + "color": "ed95d2", + "aliases": [], + "description": "The issue/PR requires documentation to be added." + }, + { + "name": "needs feedback", + "color": "ed95d2", + "aliases": [ "action: needs feedback", "[Status] Needs Discussion" ], + "description": "The issue/PR needs a response from any of the parties involved in the issue." + }, + { + "name": "needs tests", + "color": "ed95d2", + "aliases": [ "scope: tests", "[Type] E2E" ], + "description": "The issue/PR needs tests before it can move forward." + }, + { + "name": "priority: critical", + "color": "d73a4a", + "aliases": [ "[Pri] CRITICAL" ], + "description": "The issue is critical—e.g. a fatal error, security problem affecting many customers." + }, + { + "name": "priority: high", + "color": "d93f0b", + "aliases": [ "[Pri] High" ], + "description": "The issue/PR is high priority—it affects lots of customers substantially, but not critically." + }, + { + "name": "priority: low", + "color": "e2f78c", + "aliases": [ "[Pri] Low" ], + "description": "The issue/PR is low priority—not many people are affected or there’s a workaround, etc." + }, + { + "name": "status: blocked", + "color": "d73a4a", + "aliases": [ "status: blocked", "[Status] Blocked" ], + "description": "The issue is blocked from progressing, waiting for another piece of work to be done." + }, + { + "name": "status: on hold", + "color": "d93f0b", + "aliases": [], + "description": "The issue is currently not prioritized." + }, + { + "name": "type: bug", + "color": "d73a4a", + "aliases": [ "type: bug", "[Type] Bug" ], + "description": "The issue is a confirmed bug." + }, + { + "name": "type: documentation", + "color": "0075ca", + "aliases": [ "scope: documentation" ], + "description": "This issue is a request for better documentation." + }, + { + "name": "type: enhancement", + "color": "0075ca", + "aliases": [ "type: enhancement", "[Type] Enhancement" ], + "description": "The issue is a request for an enhancement." + }, + { + "name": "type: question", + "color": "0075ca", + "aliases": [ "type: support", "[Type] Question" ], + "description": "The issue is a question about how code works." + }, + { + "name": "type: task", + "color": "0075ca", + "aliases": [ "[Type] Task" ], + "description": "The issue is an internally driven task (e.g. from another A8c team)." + }, + { + "name": "type: technical debt", + "color": "0075ca", + "aliases": [ "[Type] Technical Debt" ], + "description": "This issue/PR represents/solves the technical debt of the project." + }, + { + "name": "type: compatibility", + "color": "0075ca", + "aliases": [ "[Type] Compatibility" ] + }, + { + "name": "status: needs review", + "color": "fbca04", + "aliases": [ "[Status] Needs Review" ], + "description": "PR that needs review" + } +] diff --git a/plugins/woocommerce-blocks/.github/monitor-typescript-errors/action.yml b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/action.yml new file mode 100644 index 00000000000..6e88f1ace61 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/action.yml @@ -0,0 +1,22 @@ +name: 'Typescript Monitor' +description: 'Check TypesScript errors' +inputs: + repo-token: + description: 'GitHub token' + required: true + checkstyle: + description: 'Path checkstyle.xml file of current PR/branch' + required: true + checkstyle-trunk: + description: 'Path checkstyle.xml file of trunk' + required: true + create-comment: + description: 'Create a dedicate comment for this report?' + required: false + default: true +outputs: + comment: + description: 'Markdown comment' +runs: + using: 'node16' + main: 'index.js' diff --git a/plugins/woocommerce-blocks/.github/monitor-typescript-errors/index.js b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/index.js new file mode 100644 index 00000000000..29544181123 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/index.js @@ -0,0 +1,73 @@ +const fs = require( 'fs' ); +const { getOctokit, context } = require( '@actions/github' ); +const { getInput, setOutput } = require( '@actions/core' ); +const { parseXml, getFilesWithNewErrors } = require( './utils/xml' ); +const { generateMarkdownMessage } = require( './utils/markdown' ); +const { addComment } = require( './utils/github' ); + +const runner = async () => { + const token = getInput( 'repo-token', { required: true } ); + const octokit = getOctokit( token ); + const payload = context.payload; + const repo = payload.repository.name; + const owner = payload.repository.owner.login; + const fileName = getInput( 'checkstyle', { + required: true, + } ); + const trunkFileName = getInput( 'checkstyle-trunk', { + required: true, + } ); + const createComment = getInput( 'create-comment' ); + + const newCheckStyleFile = fs.readFileSync( fileName ); + const newCheckStyleFileParsed = parseXml( newCheckStyleFile ); + const currentCheckStyleFile = fs.readFileSync( trunkFileName ); + const currentCheckStyleFileContentParsed = parseXml( + currentCheckStyleFile + ); + + const { header } = generateMarkdownMessage( newCheckStyleFileParsed ); + const filesWithNewErrors = getFilesWithNewErrors( + newCheckStyleFileParsed, + currentCheckStyleFileContentParsed + ); + + const message = + header + + '\n' + + ( filesWithNewErrors.length > 0 + ? `⚠️ ⚠️ This PR introduces new TS errors on ${ filesWithNewErrors.length } files: \n` + + '
\n' + + filesWithNewErrors.join( '\n\n' ) + + '\n' + + '
' + : '🎉 🎉 This PR does not introduce new TS errors.' ); + + if ( process.env[ 'CURRENT_BRANCH' ] !== 'trunk' ) { + if ( createComment !== 'true' ) { + setOutput( 'comment', message ); + } else { + await addComment( { + octokit, + owner, + repo, + message, + payload, + } ); + } + } + + /** + * @todo: Airtable integration is failing auth, so we're disabling it for now. + * Issue opened: https://github.com/woocommerce/woocommerce-blocks/issues/8961 + */ + // if ( process.env[ 'CURRENT_BRANCH' ] === 'trunk' ) { + // try { + // await addRecord( currentCheckStyleFileContentParsed.totalErrors ); + // } catch ( error ) { + // setFailed( error ); + // } + // } +}; + +runner(); diff --git a/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/airtable.js b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/airtable.js new file mode 100644 index 00000000000..5d1dcdca607 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/airtable.js @@ -0,0 +1,38 @@ +const axios = require( 'axios' ).default; + +const BASE_URL = 'https://api.airtable.com/v0'; +const TABLE_ID = 'appIIlxUVxOks06sZ'; +const API_KEY = process.env[ 'AIRTABLE_API_KEY' ]; + +const TABLE_NAME = 'TypeScript Migration'; +const TYPESCRIPT_ERRORS_COLUMN_NAME = 'TypeScript Errors'; +const DATE_COLUMN_NAME = 'Date'; + +// https://community.airtable.com/t/datetime-date-field-woes/32121 +const generateDateValueForAirtable = () => { + const today = new Date(); + const string = today.toLocaleDateString(); + + return new Date( string ); +}; + +exports.addRecord = async ( errorsNumber ) => + axios.post( + `${ BASE_URL }/${ TABLE_ID }/${ TABLE_NAME }`, + { + records: [ + { + fields: { + [ TYPESCRIPT_ERRORS_COLUMN_NAME ]: errorsNumber, + [ DATE_COLUMN_NAME ]: generateDateValueForAirtable(), + }, + }, + ], + typecast: true, + }, + { + headers: { + Authorization: `Bearer ${ API_KEY }`, + }, + } + ); diff --git a/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/github.js b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/github.js new file mode 100644 index 00000000000..2b49d0f3aae --- /dev/null +++ b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/github.js @@ -0,0 +1,44 @@ +const getReportCommentId = async ( { octokit, owner, repo, payload } ) => { + const currentComments = await octokit.rest.issues.listComments( { + owner, + repo, + issue_number: payload.pull_request.number, + } ); + + if ( + Array.isArray( currentComments.data ) && + currentComments.data.length > 0 + ) { + const comment = currentComments.data.find( + ( comment ) => + comment.body.includes( 'TypeScript Errors Report' ) && + comment.user.login === 'github-actions[bot]' + ); + + return comment?.id; + } +}; + +exports.addComment = async ( { octokit, owner, repo, message, payload } ) => { + const commentId = await getReportCommentId( { + octokit, + owner, + repo, + payload, + } ); + + if ( commentId ) { + return await octokit.rest.issues.updateComment( { + owner, + repo, + comment_id: commentId, + body: message, + } ); + } + await octokit.rest.issues.createComment( { + owner, + repo, + issue_number: payload.pull_request.number, + body: message, + } ); +}; diff --git a/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/markdown.js b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/markdown.js new file mode 100644 index 00000000000..901b0b9701e --- /dev/null +++ b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/markdown.js @@ -0,0 +1,27 @@ +exports.generateMarkdownMessage = ( dataFromParsedXml ) => { + const header = generateHeader( dataFromParsedXml ); + const body = generateBody( dataFromParsedXml ); + + return { header, body }; +}; + +const generateHeader = ( dataFromParsedXml ) => { + return ` +## TypeScript Errors Report + +- Files with errors: ${ dataFromParsedXml.totalFilesWithErrors } +- Total errors: ${ dataFromParsedXml.totalErrors } +`; +}; + +const generateBody = ( dataFromParsedXml ) => { + const files = dataFromParsedXml.files; + + return Object.keys( files ).map( ( file ) => { + return ` +Files with errors: + File: ${ file } + ${ files[ file ].map( ( error ) => `- ${ error }` ).join( '\r\n' ) } + `; + } ); +}; diff --git a/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/xml.js b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/xml.js new file mode 100644 index 00000000000..67f99e0dc3e --- /dev/null +++ b/plugins/woocommerce-blocks/.github/monitor-typescript-errors/utils/xml.js @@ -0,0 +1,72 @@ +const { XMLParser } = require( 'fast-xml-parser' ); + +exports.parseXml = ( filePath ) => { + const parser = new XMLParser( { + ignoreAttributes: false, + attributeNamePrefix: '', + attributesGroupName: '', + } ); + const parsedFile = parser.parse( filePath ); + + return getDataFromParsedXml( parsedFile ); +}; + +const getErrorInfo = ( error ) => { + const line = error.line; + const column = error.column; + const message = error.message; + + return { + line, + column, + message, + }; +}; + +const getDataFromParsedXml = ( parsedXml ) => { + const data = parsedXml.checkstyle.file; + + return data.reduce( + ( acc, { name, error } ) => { + const pathFile = name; + const hasMultipleErrors = Array.isArray( error ); + + return { + files: { + [ pathFile ]: hasMultipleErrors + ? error.map( getErrorInfo ) + : [ getErrorInfo( error ) ], + ...acc.files, + }, + totalErrors: + acc.totalErrors + ( hasMultipleErrors ? error.length : 1 ), + totalFilesWithErrors: acc.totalFilesWithErrors + 1, + }; + }, + { + totalErrors: 0, + totalFilesWithErrors: 0, + } + ); +}; + +exports.getFilesWithNewErrors = ( + newCheckStyleFileParsed, + currentCheckStyleFileParsed +) => { + const newFilesReport = newCheckStyleFileParsed.files; + const currentFilesReport = currentCheckStyleFileParsed.files; + + return Object.keys( newFilesReport ) + .sort( ( a, b ) => a.localeCompare( b ) ) + .reduce( + ( acc, pathfile ) => + typeof currentFilesReport[ pathfile ] === 'undefined' || + currentFilesReport[ pathfile ] === null || + newFilesReport[ pathfile ].length > + currentFilesReport[ pathfile ].length + ? [ ...acc, pathfile ] + : acc, + [] + ); +}; diff --git a/plugins/woocommerce-blocks/.github/patch-initial-checklist.md b/plugins/woocommerce-blocks/.github/patch-initial-checklist.md new file mode 100644 index 00000000000..a964e2fd890 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/patch-initial-checklist.md @@ -0,0 +1,106 @@ +# Patch release steps + +The release pull request has been created! This checklist is a guide to follow for the remainder of the patch release process. You can check off each item in this list once completed. + +- [ ] Checkout the release branch locally. + +## Initial Preparation + +- [ ] Close the milestone of the release you are going to ship. That will prevent newly approved PRs to be automatically assigned to that milestone. +- [ ] Check that the release automation correctly added the changelog to `readme.txt` +- [ ] Ensure you pull your changes from the remote, since GitHub Actions will have added new commits to the branch. + - [ ] Check the version and date in the changelog section within `readme.txt`, e.g. `= {{version}} - YYYY-MM-DD =` + - [ ] Check the changelog matches the one in the pull request description above. +- [ ] Run `npm run change-versions` to update the version numbers in several files. Write the version number you are releasing: {{version}}. +- [ ] Update compatibility sections (if applicable). +- [ ] Cherry-pick into the release branch all fixes that need to be included in this release (assuming they were merged into `trunk`). +- [ ] Push above changes to the release branch. + +## Create the Testing Notes + +- [ ] Run `npm ci` +- [ ] Run `npm run package-plugin:deploy`. This will create a zip of the current branch build locally. + - Note: The zip file is functionally equivalent to what gets released except the version bump. +- [ ] Create the testing notes for the release. + - [ ] For each pull request that belongs to the current release, grab the `User Facing Testing` notes from the PR's description. + - If a PR has the `Should be tested by the development team exclusively` checkbox checked, create a new section called 'Testing notes for the development team' and copy the `User Facing Testing` notes from the PR to this section. + - If a PR has the `Experimental` checkbox checked, do not include it in the testing instructions. + - If a PR has the `Do not include in the Testing Notes` checkbox checked, as the description suggests, do not include it in the release instructions. + - [ ] Add the notes to `docs/internal-developers/testing/releases` + - [ ] Update the `docs/internal-developers/testing/releases/README.md` file index. +- [ ] Copy a link to the release zip you created earlier into the testing notes. To generate the link you can upload the zip as an attachment in a GitHub comment and then just copy the path (without publishing the comment). +- [ ] Commit and push the testing docs to the release branch. + +## Smoke testing + +Each porter is responsible for testing the PRs that fall under the focus of their own team. Shared functionality should be tested by both porters. This means that the Rubik porter will mostly test checkout blocks and Store API endpoints, while the Kirigami porter will test the product related blocks and Store API endpoints. + +- [ ] Smoke test the built release zip. Refer to the [Smoke testing checklist](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/docs/internal-developers/testing/smoke-testing.md) for critical functionality. +- [ ] Test in a clean environment. Create a Jurassic.Ninja site, upload your zip, then smoke test it. +- [ ] Ask the porters of Rubik/Kirigami/Origami to test the built zip as well and to approve the PR if everything looks good. We recommend creating threads of p2 to track which test cases were tested. +- [ ] Confirm all GitHub checks have passed on this PR prior to approving. + +After testing: + +- If all PRs are testing as expected, continue with the release. +- If one or more PRs are not testing as expected: ping the PR authors and the porter of the relevant team and ask them if the change is a release blocker or not (you can also ping the team lead if any of them is not available). In general, if it's not a regression or there is no product/marketing reason why that PR is a blocker, all other PRs should default to not being blockers. + - If there are blockers: stop the release and ask the PR author to fix them. If the PR author is AFK, ping the porter of their team. + - If some PRs are not testing as expected but they are not blockers: revert the relevant commits, remove the changes from testing steps and changelog, open an issue (or reopen the original one) and proceed with the release. + - If minor issues are discovered during the testing, each team is responsible for logging them in Github. + +## Deploy the update + +- [ ] Make sure you've got `hub` installed (`brew install hub`) and make sure `hub api user` returns JSON with information about your GitHub user account. If it doesn't: + - Create a [GitHub access token](https://github.com/settings/tokens) with the `repo` permission. + - Set the environment variables: `GITHUB_USERNAME` with your GitHub Username, and `GITHUB_TOKEN` with the token you just generated. (You may want to add these to `.bashrc` or the equivalent) + - Run `hub api user` again and ensure JSON with information about your GitHub user account is returned. +- [ ] Execute `npm run deploy` + - **ALERT**: This script will ask you if this release will be deployed to WordPress.org. You should only answer yes for this release **if it's the latest release and you want to deploy to WordPress.org**. Otherwise, answer no. If you answer yes, you will get asked additional verification by the `npm run deploy` script about deploying a patch release to WordPress.org. + +## If this release is deployed to WordPress.org + +- [ ] An email confirmation is required before the new version will be released, so check your email in order to confirm the release. +- [ ] Edit the [GitHub release](https://github.com/woocommerce/woocommerce-gutenberg-products-block/releases) and copy changelog into the release notes. Ensure there is a release with the correct version, the one you entered above. +- [ ] The `#woo-blocks-repo` slack instance will be notified about the progress with the WordPress.org deploy. Watch for that. If anything goes wrong, an error will be reported and you can followup via the GitHub actions tab and the log for that workflow. +- [ ] After the wp.org workflow completes, confirm the following + - [ ] Confirm svn tag is correct, e.g. [{{version}}](https://plugins.svn.wordpress.org/woo-gutenberg-products-block/tags/{{version}}/) + - [ ] Changelog, Version, and Last Updated on [WP.org plugin page](https://wordpress.org/plugins/woo-gutenberg-products-block/) is correct. + - [ ] Confirm [WooCommerce.com plugin page](https://woocommerce.com/products/woocommerce-gutenberg-products-block/) is updated. Note: this can take several hours, feel free to check it the following day. + - [ ] Download zip and smoke test. + - [ ] Test updating plugin from previous version. + +## After Workflow completes + +- [ ] Move the changes to the changelog, testing steps and required versions that you did in the previous steps to `trunk`. You can do so copy-and-pasting the changes in a new commit directly to `trunk`, or cherry-picking the commits that introduced those changes. +- [ ] Update the schedules p2 with the shipped date for the release (PdToLP-K-p2). +- [ ] Edit the GitHub milestone of the release you just shipped and add the current date as the due date (this is used to track ship date as well). + +## Pull request in WooCommerce Core for Package update + +This only needs done if the patch release needs to be included in WooCommerce Core. Reviewing and merging the PR is your team's responsibility, except in the case of `Fix Release Request`. In this case, the WooCommerce release manager reviews and merges the PR. + +- [ ] Create a pull request for updating the package in the [WooCommerce Core Repository](https://github.com/woocommerce/woocommerce/) that [bumps the package version](https://github.com/woocommerce/woocommerce/blob/747cb6b7184ba9fdc875ab104da5839cfda8b4be/plugins/woocommerce/composer.json) for the Woo Blocks package to the version you are releasing. Reviewing and merging the PR is your team's responsibility. [See this example](https://github.com/woocommerce/woocommerce/pull/32627). + - [ ] Set the base branch (the branch that your PR will be merged into) to the correct one. It must be: - `trunk` if the WC Blocks version you are releasing is higher than the one in core (you can find the current WC Blocks version in core in `plugins/woocommerce/composer.json`) - `release/x.y` if the WC Blocks version in core is higher than the one you are releasing (`x.y` must be the version of WC core that will include the version of WC Blocks you are releasing) + - [ ] Increase the version of `woocommerce/woocommerce-blocks` in the `plugins/woocommerce/composer.json` file + - [ ] Inside `plugins/woocommerce/`, run `composer update woocommerce/woocommerce-blocks` and make sure `composer.lock` was updated + - [ ] Run `pnpm --filter=woocommerce changelog add` to create a new changelog file similar to this one [plugins/woocommerce/changelog/update-woocommerce-blocks-7.4.1](https://github.com/woocommerce/woocommerce/blob/5040a10d01896bcf40fd0ac538f2b7bc584ffe0a/plugins/woocommerce/changelog/update-woocommerce-blocks-7.4.1). The file will be auto-generated with your answers. For the _Significance_ entry we’ll always use `patch`. For the changelog enter "Update WooCommerce Blocks to X.X.X". + - [ ] Verify and make any additional edits to the pull request description for things like: Changelog to be included with WooCommerce core, additional communication that might be needed elsewhere, additional marketing communication notes that may be needed, etc. + +### Testing the PR + +- [ ] Build WC core from that branch with `pnpm run --filter='woocommerce' build ` (you might need to [install the dependencies first](https://github.com/woocommerce/woocommerce#prerequisites)) and: + - [ ] Make sure the correct version of WC Blocks is being loaded. This can be done testing at least one of the testing steps from the release. + - [ ] Complete the [Smoke testing checklist](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/docs/internal-developers/testing/smoke-testing.md). +- [ ] After the checklist is complete and the testing is done, select the porter of your team to review the PR. Once approved, make sure you merge the PR. + +## Publish Posts + +You only need to post public release announcements and update relevant public facing docs if this patch release is deployed to WP.org. Otherwise, you can skip this section. + +- [ ] Post release announcement on [WooCommerce Developer Blog](https://developer.woocommerce.com/category/release-post/woocommerce-blocks-release-notes/). + - Ping porters from each team to know which changelog entries need to be highlighted. Ask them to write a short text and optionally provide a screenshot. They can use previous posts for inspiration, we usually try to highlight new features or API changes. + - Ensure the release notes are included in the post verbatim. + - Don't forget to use category `WooCommerce Blocks Release Notes` for the post. +- [ ] Announce the release internally (`#woo-announcements` slack). +- [ ] Go through the description of the release pull request and edit it to update all the sections and checklist instructions there. +- [ ] Merge this PR into the base branch: `release/x.y.0`. diff --git a/plugins/woocommerce-blocks/.github/patch-release-pull-request.md b/plugins/woocommerce-blocks/.github/patch-release-pull-request.md new file mode 100644 index 00000000000..658fbee6bab --- /dev/null +++ b/plugins/woocommerce-blocks/.github/patch-release-pull-request.md @@ -0,0 +1,40 @@ +# Patch release + +This is the patch release pull request for WooCommerce Blocks plugin `{{version}}`. + +## Changelog + +--- + +```md +{{changelog}} +``` + +--- + +## Communication + +### Prepared Updates + +Please leave a comment on this PR with links to the following: + +- [ ] Release announcement (announcement post on developer.woocommerce.com published after release). + +{{#if devNoteItems}} +**Developer Notes** - The following issues require developer notes in the release post: + +{{devNoteItems}} +{{/if}} + +- [ ] Happiness engineering or Happiness/Support (if special instructions needed). +- [ ] Relevant developer documentation (if applicable). + +## Quality + +> This section is for things related to quality around the release. + +- [ ] Testing Instructions are included in this PR + +- [ ] Any performance impacts are documented. + +--- diff --git a/plugins/woocommerce-blocks/.github/pull_request_template.md b/plugins/woocommerce-blocks/.github/pull_request_template.md new file mode 100644 index 00000000000..722ecd6889b --- /dev/null +++ b/plugins/woocommerce-blocks/.github/pull_request_template.md @@ -0,0 +1,61 @@ + + +## What + +Fixes # + +## Why + + + +## Testing Instructions + + + +_Please consider any edge cases this change may have, and also other areas of the product this may impact._ + +1. +2. +3. + +* [ ] Do not include in the Testing Notes +* [ ] Should be tested by the development team exclusively + +## Screenshots or screencast + + + +| Before | After | +| ------ | ----- | +| | | + +## WooCommerce Visibility + + +Required: + +* [ ] WooCommerce Core +* [ ] Feature plugin +* [ ] Experimental +* [ ] N/A + +## Checklist + +Required: + +* [ ] This PR has either a `[type]` label or a `[skip-changelog]` label. +* [ ] This PR is assigned to a milestone. + +Conditional: + +* [ ] This PR has a UI change and has been cross-browser tested at different viewport sizes on both the frontend and in the editor. +* [ ] This PR has a changelog description (if `[skip-changelog]` label is not present). +* [ ] This PR adds/removes a feature flag & I've updated [this doc](https://github.com/woocommerce/woocommerce-blocks/blob/trunk/docs/internal-developers/blocks/feature-flags-and-experimental-interfaces.md). +* [ ] This PR adds/removes an experimental interfaces, and I've updated [this doc](https://github.com/woocommerce/woocommerce-blocks/blob/trunk/docs/internal-developers/blocks/feature-flags-and-experimental-interfaces.md). +* [ ] This PR has been accessibility tested. +* [ ] This PR has had any necessary documentation added/updated. + +## Changelog + + +> Add suggested changelog entry here. diff --git a/plugins/woocommerce-blocks/.github/release-automation-config.json b/plugins/woocommerce-blocks/.github/release-automation-config.json new file mode 100644 index 00000000000..d0c9296d69d --- /dev/null +++ b/plugins/woocommerce-blocks/.github/release-automation-config.json @@ -0,0 +1,3 @@ +{ + "labelsToOmit": [ "skip-changelog", "type: build" ] +} diff --git a/plugins/woocommerce-blocks/.github/release-initial-checklist.md b/plugins/woocommerce-blocks/.github/release-initial-checklist.md new file mode 100644 index 00000000000..733f3432e3b --- /dev/null +++ b/plugins/woocommerce-blocks/.github/release-initial-checklist.md @@ -0,0 +1,140 @@ +# Release Steps + +The release pull request has been created! This checklist is a guide to follow for the remainder of the release process. You can check off each item in this list once completed. + +- [ ] Checkout the release branch locally. + +## Initial Preparation + +- [ ] Close the milestone of the release you are going to ship. That will prevent newly approved PRs to be automatically assigned to that milestone. +- [ ] Create a milestone for the next version. +- [ ] Manually add the changelog entries of all affected PRs to `readme.txt`. (Technically, this should be an automated process, but it seems to broke recently. Please change this entry back, once the automated process works again.) +- [ ] Ensure you pull your changes from the remote, since GitHub Actions will have added new commits to the branch. + - [ ] Check the version and date in the changelog section within `readme.txt`, e.g. `= {{version}} - YYYY-MM-DD =` + - [ ] Check the changelog matches the one in the pull request description above. +- [ ] Run `npm run change-versions` to update the version numbers in several files. Write the version number you are releasing: {{version}}. +- [ ] Update compatibility sections (if applicable). + - [ ] Update _Requires at least_, _Tested up to_, and _Requires PHP_ sections at the top of `readme.txt`. Note, this should also be the latest WordPress version available at time of release. + - [ ] Update _Requires at least_, _Requires PHP_, _WC requires at least_, and _WC tested up to_ at the top of `woocommerce-gutenberg-products-block.php`. Note, this should include requiring the latest WP version at the time of release. For _WC requires at least_, use L1 (we publicly communicate L0 but technically support L1 to provide some space for folks to update). So this means if the current version of WooCommerce core is 5.8.0, then you'll want to put 5.7.0 here. + - [ ] If necessary, update the value of `$minimum_wp_version` at the top of the `woocommerce-gutenberg-products-block.php` file to the latest available version of WordPress. + - [ ] Check the minimum WP version supported by **WooCommerce Core** (you can find it in [its readme.txt - line `Requires at least`](https://github.com/woocommerce/woocommerce/blob/trunk/plugins/woocommerce/readme.txt#L4)). If necessary, update it in `phpcs.xml`. It would be this line: ``. +- [ ] Push above changes to the release branch. + +## Create the Testing Notes + +- [ ] Run `npm ci` +- [ ] Run `npm run package-plugin:deploy`. This will create a zip of the current branch build locally. + - Note: The zip file is functionally equivalent to what gets released except the version bump. +- [ ] Create the testing notes for the release. + - [ ] For each pull request that belongs to the current release, grab the `User Facing Testing` notes from the PR's description. + - If a PR has the `Should be tested by the development team exclusively` checkbox checked, create a new section called 'Testing notes for the development team' and copy the `User Facing Testing` notes from the PR to this section. + - If a PR has the `Experimental` checkbox checked, do not include it in the testing instructions. + - If a PR has the `Do not include in the Testing Notes` checkbox checked, as the description suggests, do not include it in the release instructions. + - [ ] Add the notes to `docs/internal-developers/testing/releases` + - [ ] Update the `docs/internal-developers/testing/releases/README.md` file index. +- [ ] Copy a link to the release zip you created earlier into the testing notes. To generate the link you can upload the zip as an attachment in a GitHub comment and then just copy the path (without publishing the comment). +- [ ] Commit and push the testing docs to the release branch. + +## Smoke testing + +Each porter is responsible for testing the PRs that fall under the focus of their own team. Shared functionality should be tested by both porters. This means that the Rubik porter will mostly test checkout blocks and Store API endpoints, while the Kirigami porter will test the product related blocks and Store API endpoints. + +- [ ] Smoke test the built release zip. Refer to the [Smoke testing checklist](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/docs/internal-developers/testing/smoke-testing.md) for critical functionality. +- [ ] Test in a clean environment. Create a Jurassic.Ninja site, upload your zip, then smoke test it. +- [ ] Ask the porters of Rubik/Kirigami/Origami to test the built zip as well and to approve the PR if everything looks good. We recommend creating threads of p2 to track which test cases were tested. +- [ ] Confirm all GitHub checks have passed on this PR prior to approving. + +After testing: + +- If all PRs are testing as expected, continue with the release. +- If one or more PRs are not testing as expected: ping the PR authors and the porter of the relevant team and ask them if the change is a release blocker or not (you can also ping the team lead if any of them is not available). In general, if it's not a regression or there is no product/marketing reason why that PR is a blocker, all other PRs should default to not being blockers. + - If there are blockers: stop the release and ask the PR author to fix them. If the PR author is AFK, ping the porter of their team. + - If some PRs are not testing as expected but they are not blockers: revert the relevant commits, remove the changes from testing steps and changelog, open an issue (or reopen the original one) and proceed with the release. + - If minor issues are discovered during the testing, each team is responsible for logging them in Github. + +## Deploy the update + +- [ ] Make sure you've got `hub` installed (`brew install hub`) and make sure `hub api user` returns JSON with information about your GitHub user account. If it doesn't: + - Create a [GitHub access token](https://github.com/settings/tokens) with the `repo` permission. + - Set the environment variables: `GITHUB_USERNAME` with your GitHub Username, and `GITHUB_TOKEN` with the token you just generated. (You may want to add these to `.bashrc` or the equivalent) + - Run `hub api user` again and ensure JSON with information about your GitHub user account is returned. +- [ ] Execute `npm run deploy` + - The script will ask you to enter the version number to tag. Please enter the version we're releasing right now. Do not publish any dev tags as a release. + - **ALERT**: This script will ask you if this release will be deployed to WordPress.org. You should answer yes for this release even if it is a pre-release. + - A GitHub release will automatically be created and this will trigger a workflow that automatically deploys the plugin to WordPress.org. + +## If this release is deployed to WordPress.org + +- [ ] An email confirmation is required before the new version will be released, so check your email in order to confirm the release. +- [ ] Edit the [GitHub release](https://github.com/woocommerce/woocommerce-gutenberg-products-block/releases) and copy changelog into the release notes. Ensure there is a release with the correct version, the one you entered above. +- [ ] The `#woo-blocks-repo` slack instance will be notified about the progress with the WordPress.org deploy. Watch for that. If anything goes wrong, an error will be reported and you can followup via the GitHub actions tab and the log for that workflow. +- [ ] After the wp.org workflow completes, confirm the following + - [ ] Confirm svn tag is correct, e.g. [{{version}}](https://plugins.svn.wordpress.org/woo-gutenberg-products-block/tags/{{version}}/) + - [ ] Changelog, Version, and Last Updated on [WP.org plugin page](https://wordpress.org/plugins/woo-gutenberg-products-block/) is correct. + - [ ] Confirm [WooCommerce.com plugin page](https://woocommerce.com/products/woocommerce-gutenberg-products-block/) is updated. Note: this can take several hours, feel free to check it the following day. + - [ ] Download zip and smoke test. + - [ ] Test updating plugin from previous version. + +## After Workflow completes + +- [ ] Move the changes to the changelog, testing steps and required versions that you did in the previous steps to `trunk`. You can do so copy-and-pasting the changes in a new commit directly to `trunk`, or cherry-picking the commits that introduced those changes. +- [ ] Run `npm run change-versions` to update the version in `trunk` to the next version of the plugin and include the `dev` suffix. For example, if you released 2.5.0, you should update the version in `trunk` to 2.6.0-dev. +- [ ] Update the schedules p2 with the shipped date for the release (PdToLP-K-p2). +- [ ] Edit the GitHub milestone of the release you just shipped and add the current date as the due date (this is used to track ship date as well). + +## Pull request in WooCommerce Core for Package update + +**🆕 These steps need to be done for every WooCommerce Blocks release that _isn't_ a patch release**. More information can be found here on why: pdToLP-Of-p2. + +- [ ] Remind whoever is porter this week to audit our codebase to ensure this [experimental interface document](https://github.com/woocommerce/woocommerce-blocks/blob/trunk/docs/internal-developers/blocks/feature-flags-and-experimental-interfaces.md) is up to date. See Pca54o-rM-p2 for more details. +- [ ] Create a pull request for updating the package in the [WooCommerce Core Repository](https://github.com/woocommerce/woocommerce/) that [bumps the package version](https://github.com/woocommerce/woocommerce/blob/747cb6b7184ba9fdc875ab104da5839cfda8b4be/plugins/woocommerce/composer.json) for the Woo Blocks package to the version you are releasing. Reviewing and merging the PR is your team's responsibility. [See this example](https://github.com/woocommerce/woocommerce/pull/32627). + - [ ] Increase the version of `woocommerce/woocommerce-blocks` in the `plugins/woocommerce/composer.json` file + - [ ] Inside `plugins/woocommerce/`, run `composer update woocommerce/woocommerce-blocks` and make sure `composer.lock` was updated + - [ ] Run `pnpm --filter=woocommerce changelog add` to create a new changelog file similar to this one [plugins/woocommerce/changelog/update-woocommerce-blocks-7.4.1](https://github.com/woocommerce/woocommerce/blob/5040a10d01896bcf40fd0ac538f2b7bc584ffe0a/plugins/woocommerce/changelog/update-woocommerce-blocks-7.4.1). The file will be auto-generated with your answers. For the _Significance_ entry we’ll always use `minor`. For the changelog enter "Update WooCommerce Blocks to X.X.X". + - [ ] Verify and make any additional edits to the pull request description for things like: Changelog to be included with WooCommerce core, additional communication that might be needed elsewhere, additional marketing communication notes that may be needed, etc. + +The PR description can follow [this example](https://github.com/woocommerce/woocommerce/pull/32627). + +- It lists all the WooCommerce Blocks versions that are being included since the last version that you edited in `plugins/woocommerce/composer.json`. Each version should have a link for the `Release PR`, `Testing instructions` and `Release post` (if available). +- The changelog should be aggregated from all the releases included in the package bump and grouped per type: `Enhancements`, `Bug Fixes`, `Various` etc. This changelog will be used in the release notes for the WooCommerce release. That's why it should only list the PRs that have WooCommerce Core in the WooCommerce Visibility section of their description. Don't include changes available in the feature plugin or development builds. + +### Testing the PR + +- [ ] Build WC core from that branch with `pnpm run --filter='woocommerce' build ` (you might need to [install the dependencies first](https://github.com/woocommerce/woocommerce#prerequisites)) and: + - [ ] Make sure the correct version of WC Blocks is being loaded. This can be done testing at least one of the testing steps from the release. + - [ ] Complete the [Smoke testing checklist](https://github.com/woocommerce/woocommerce-gutenberg-products-block/blob/trunk/docs/internal-developers/testing/smoke-testing.md). +- [ ] After the checklist is complete and the testing is done, select the porter of your team to review the PR. Once approved, make sure you merge the PR. + +### Monthly Releases only + +If this is a monthly release, you'll need to do the following steps as well: + +- [ ] Make sure you join the `#woo-core-releases` Slack channel to represent Woo Blocks for the release of WooCommerce core this version is included in. +- [ ] Search the release thread of the WooCommerce core version in WooCommerce P2 (example: p6q8Tx-2gl-p2). + - [ ] Subscribe to it, so you are aware of any news/changes. + - [ ] Make sure you are listed as the _Blocks Package_ lead or add yourself if you aren't. + +## Publish posts + +- [ ] Post release announcement on [WooCommerce Developer Blog](https://developer.woocommerce.com/category/release-post/woocommerce-blocks-release-notes/). + - Ping porters from each team to know which changelog entries need to be highlighted. Ask them to write a short text and optionally provide a screenshot. They can use previous posts for inspiration, we usually try to highlight new features or API changes. + - Ensure the release notes are included in the post verbatim. + - Don't forget to use category `WooCommerce Blocks Release Notes` for the post. + - If any of the PRs in this release is labelled with `needs dev-note`, include it in the post. +- [ ] Document highlights so they can be used in the WC core release post (do this even if the release you are doing is not merged into WC core): + - Check which WC core version will include the WC Blocks release you just did (reference: PdToLP-K-p2). + - Go to the _Release highlights_ page (PdToLP-xh-p2) and edit the _WC Blocks features merged in WC core X.Y_ page corresponding to the correct release (create it and add it to the list if it doesn't exist yet). + - Edit that page and write all highlights from the release you just made which will be available in WC core. Skip all features which are only available in the feature plugin. Make the text user-friendly, as it will be part of a public post when WC core is released (you can use what you wrote in the release announcement in the step above). + - If you are doing a release that gets merged into WC core: + - Go to its Release Thread and search the _Feature Highlights_ comment (example: p6q8Tx-2gl-p2). + - Edit the linked draft post and copy and paste all highlights from the _WC Blocks features merged in WC core X.Y_ page. + - Leave a comment under the _Feature Highlights_ comment in the release thread mentioning that you updated the draft with the features included in WC Blocks X.Y. +- [ ] Announce the release internally (`#woo-announcements` slack). +- [ ] Update user-facing documentation as needed. When the plugin is released, ensure user-facing documentation is kept up to date with new blocks and compatibility information. The dev team should update documents in collaboration with support team and WooCommerce docs guild. In particular, please review and update as needed: + - Are there any new blocks in this release? Ensure they have adequate user documentation. + - Ensure any major improvements or changes are documented. +- [ ] Update minimum supported versions (WordPress, WooCommerce Core) and other requirements where necessary, including: + - [WCCOM product page](https://woocommerce.com/products/woocommerce-gutenberg-products-block/) + - [WooCommerce blocks main documentation page](https://docs.woocommerce.com/document/woocommerce-blocks/) +- [ ] Go through the description of the release pull request and edit it to update all the sections and checklist instructions there. +- [ ] Close this PR. diff --git a/plugins/woocommerce-blocks/.github/release-pull-request.md b/plugins/woocommerce-blocks/.github/release-pull-request.md new file mode 100644 index 00000000000..00a25f3bbf2 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/release-pull-request.md @@ -0,0 +1,40 @@ +# Release Pull Request + +This is the release pull request for WooCommerce Blocks plugin `{{version}}`. + +## Changelog + +--- + +```md +{{changelog}} +``` + +--- + +## Communication + +### Prepared Updates + +Please leave a comment on this PR with links to the following: + +- [ ] Release announcement (announcement post on developer.woocommerce.com published after release). + +{{#if devNoteItems}} +**Developer Notes** - The following issues require developer notes in the release post: + +{{devNoteItems}} +{{/if}} + +- [ ] Happiness engineering or Happiness/Support (if special instructions needed). +- [ ] Relevant developer documentation (if applicable). + +## Quality + +> This section is for things related to quality around the release. + +- [ ] Testing Instructions are included in this PR + +- [ ] Any performance impacts are documented. + +--- diff --git a/plugins/woocommerce-blocks/.github/workflows/auto-merge-dependabot.yml b/plugins/woocommerce-blocks/.github/workflows/auto-merge-dependabot.yml new file mode 100644 index 00000000000..1f2daa6fa8a --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/auto-merge-dependabot.yml @@ -0,0 +1,66 @@ +name: Dependabot auto-merge +on: pull_request + +permissions: + pull-requests: write + contents: write + repository-projects: write + +jobs: + dependabot: + runs-on: ubuntu-latest + if: ${{ github.actor == 'dependabot[bot]' }} + steps: + - name: Dependabot metadata + id: metadata + uses: dependabot/fetch-metadata@v1.6.0 + with: + github-token: "${{ secrets.GITHUB_TOKEN }}" + + - name: Enable auto-merge for Dependabot PRs + # Automatically merge the following dependency upgrades: + if: "${{ steps.metadata.outputs.dependency-names == '@actions/core' || + steps.metadata.outputs.dependency-names == '@automattic/color-studio' || + steps.metadata.outputs.dependency-names == '@babel/cli' || + steps.metadata.outputs.dependency-names == '@babel/core' || + steps.metadata.outputs.dependency-names == '@babel/plugin-proposal-class-properties' || + steps.metadata.outputs.dependency-names == '@babel/plugin-syntax-jsx' || + steps.metadata.outputs.dependency-names == '@babel/polyfill' || + steps.metadata.outputs.dependency-names == '@types/classnames' || + steps.metadata.outputs.dependency-names == '@types/dinero.js' || + steps.metadata.outputs.dependency-names == '@types/dompurify' || + steps.metadata.outputs.dependency-names == '@types/gtag.js' || + steps.metadata.outputs.dependency-names == '@types/jest' || + steps.metadata.outputs.dependency-names == '@types/jest-environment-puppeteer' || + steps.metadata.outputs.dependency-names == '@types/jquery' || + steps.metadata.outputs.dependency-names == '@types/lodash' || + steps.metadata.outputs.dependency-names == '@types/puppeteer' || + steps.metadata.outputs.dependency-names == '@types/react' || + steps.metadata.outputs.dependency-names == '@types/react-dom' || + steps.metadata.outputs.dependency-names == '@types/wordpress__block-editor' || + steps.metadata.outputs.dependency-names == '@types/wordpress__blocks' || + steps.metadata.outputs.dependency-names == '@types/wordpress__data' || + steps.metadata.outputs.dependency-names == '@types/wordpress__data-controls' || + steps.metadata.outputs.dependency-names == '@types/wordpress__editor' || + steps.metadata.outputs.dependency-names == '@types/wordpress__notices' || + steps.metadata.outputs.dependency-names == '@typescript-eslint/eslint-plugin' || + steps.metadata.outputs.dependency-names == '@typescript-eslint/parser' || + steps.metadata.outputs.dependency-names == 'chalk' || + steps.metadata.outputs.dependency-names == 'circular-dependency-plugin' || + steps.metadata.outputs.dependency-names == 'commander' || + steps.metadata.outputs.dependency-names == 'copy-webpack-plugin' || + steps.metadata.outputs.dependency-names == 'eslint-import-resolver-typescript' || + steps.metadata.outputs.dependency-names == 'gh-pages' || + steps.metadata.outputs.dependency-names == 'markdown-it' || + steps.metadata.outputs.dependency-names == 'promptly' || + steps.metadata.outputs.dependency-names == 'react-docgen' || + steps.metadata.outputs.dependency-names == 'wp-types' + }}" + + run: | + gh pr edit --add-label 'dependencies-auto-merged' "$PR_URL" + gh pr review --approve "$PR_URL" + gh pr merge --auto --squash "$PR_URL" + env: + PR_URL: ${{github.event.pull_request.html_url}} + GITHUB_TOKEN: ${{secrets.GITHUB_TOKEN}} diff --git a/plugins/woocommerce-blocks/.github/workflows/automate-team-review-assignment-config.yml b/plugins/woocommerce-blocks/.github/workflows/automate-team-review-assignment-config.yml new file mode 100644 index 00000000000..9415e015318 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/automate-team-review-assignment-config.yml @@ -0,0 +1,15 @@ +name: 'Automate assigning team for review.' +on: + pull_request: + types: [opened, ready_for_review] + +jobs: + add-reviews: + if: github.event.pull_request.draft == false && github.actor != 'dependabot[bot]' + runs-on: ubuntu-latest + steps: + - name: Check config and assign reviews + uses: acq688/Request-Reviewer-For-Team-Action@v1.1 + with: + config: '.github/automate-team-review-assignment-config.yml' + GITHUB_TOKEN: ${{ secrets.FINE_GRAINED_TOKEN_ACTIONS }} diff --git a/plugins/woocommerce-blocks/.github/workflows/bundle-size.yml b/plugins/woocommerce-blocks/.github/workflows/bundle-size.yml new file mode 100644 index 00000000000..2b0ac877bce --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/bundle-size.yml @@ -0,0 +1,19 @@ +name: Bundle Size + +on: [pull_request] + +jobs: + build-and-size: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + with: + fetch-depth: 1 + - uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + - uses: preactjs/compressed-size-action@8a15fc9a36a94c8c3f7835af11a4924da7e95c7c + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + pattern: '{build/**/*.js,build/**/*.css}' diff --git a/plugins/woocommerce-blocks/.github/workflows/check-doc-links-config.json b/plugins/woocommerce-blocks/.github/workflows/check-doc-links-config.json new file mode 100644 index 00000000000..fef225697d5 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/check-doc-links-config.json @@ -0,0 +1,24 @@ +{ + "httpHeaders": [ + { + "urls": [ + "https://github.com/", + "https://guides.github.com/", + "https://help.github.com/", + "https://docs.github.com/" + ], + "headers": { + "Accept-Encoding": "zstd, br, gzip, deflate" + } + } + ], + "ignorePatterns": [ + { + "pattern": "^http://localhost" + }, + { + "pattern": "https://www.php.net/manual/en/install.php" + } + ], + "retryOn429": true +} diff --git a/plugins/woocommerce-blocks/.github/workflows/check-doc-links.yml b/plugins/woocommerce-blocks/.github/workflows/check-doc-links.yml new file mode 100644 index 00000000000..8a4be5a935a --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/check-doc-links.yml @@ -0,0 +1,33 @@ +name: Check Markdown links + +on: + workflow_dispatch: + pull_request: + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: {} + +jobs: + markdown_link_check: + runs-on: ubuntu-latest + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Install Node.js + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install markdown-link-check + run: npm install -g markdown-link-check@3.11.2 + + - name: Run markdown-link-check + run: | + find ./docs -path ./docs/internal-developers/testing/releases -prune -o -name "*.md" -print0 | xargs -0 -n1 markdown-link-check -c .github/workflows/check-doc-links-config.json + diff --git a/plugins/woocommerce-blocks/.github/workflows/check-modified-assets.yml b/plugins/woocommerce-blocks/.github/workflows/check-modified-assets.yml new file mode 100644 index 00000000000..723f7dd7def --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/check-modified-assets.yml @@ -0,0 +1,91 @@ +name: Check Modified Assets + +on: + pull_request: + +jobs: + build-trunk: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + ref: trunk + + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-build-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: Setup node version and npm cache + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install Node dependencies + if: steps.cache-node-modules.outputs.cache-hit != 'true' + run: npm install --no-optional --no-audit + + - name: Build Assets + run: npm run build:check-assets + + - name: Upload Artifact + uses: actions/upload-artifact@v3.1.2 + with: + name: assets-list + path: ./build/assets.json + + compare-assets-with-trunk: + needs: [ build-trunk ] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-build-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-build-${{ env.cache-name }}- + ${{ runner.os }}-build- + ${{ runner.os }}- + + - name: Setup node version and npm cache + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Build Assets + run: npm run build:check-assets + + - name: Download assets (trunk) + uses: actions/download-artifact@v3 + with: + name: assets-list + path: assets-list + - name: Compare Assets + uses: ./.github/compare-assets + id: compare-assets + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + compare: assets-list/assets.json + create-comment: false + - name: Append report + uses: ./.github/comments-aggregator + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + section-id: compare-assets-with-trunk + content: ${{steps.compare-assets.outputs.comment}} diff --git a/plugins/woocommerce-blocks/.github/workflows/close-stale-issues.yml b/plugins/woocommerce-blocks/.github/workflows/close-stale-issues.yml new file mode 100644 index 00000000000..5894297538c --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/close-stale-issues.yml @@ -0,0 +1,24 @@ +name: 'Close stale issues' + +on: + schedule: + # Runs daily at 9am UTC + - cron: '0 9 * * *' + +jobs: + stale: + runs-on: ubuntu-latest + steps: + - uses: actions/stale@v8 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + days-before-stale: 60 + days-before-pr-stale: 7 + days-before-close: -1 + remove-stale-when-updated: true + exempt-issue-labels: 'priority: critical,priority: high,Epic,type: technical debt,category: refactor,type: documentation,plugin incompatibility' + exempt-pr-labels: 'priority: critical,priority: high,Epic,type: technical debt,category: refactor,type: documentation,plugin incompatibility' + stale-issue-message: "This issue has been marked as `stale` because it has not seen any activity within the past 60 days. Our team uses this tool to help surface issues for review. If you are the author of the issue there's no need to comment as it will be looked at." + stale-pr-message: "This PR has been marked as `stale` because it has not seen any activity within the past 7 days. Our team uses this tool to help surface pull requests that have slipped through review. \n\n###### If deemed still relevant, the pr can be kept active by ensuring it's up to date with the main branch and removing the stale label." + stale-issue-label: 'status: stale' + stale-pr-label: 'status: stale' diff --git a/plugins/woocommerce-blocks/.github/workflows/codeql-analysis.yml b/plugins/woocommerce-blocks/.github/workflows/codeql-analysis.yml new file mode 100644 index 00000000000..8c26e53c65e --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/codeql-analysis.yml @@ -0,0 +1,66 @@ +# For most projects, this workflow file will not need changing; you simply need +# to commit it to your repository. +# +# You may wish to alter this file to override the set of languages analyzed, +# or to provide custom queries or build logic. +name: 'CodeQL' + +on: + push: + branches: [trunk] + pull_request: + # The branches below must be a subset of the branches above + branches: [trunk] + schedule: + - cron: '0 16 * * 4' + +jobs: + analyze: + name: Analyze + runs-on: ubuntu-latest + + strategy: + fail-fast: false + matrix: + # Override automatic language detection by changing the below list + # Supported options are ['csharp', 'cpp', 'go', 'java', 'javascript', 'python'] + language: ['javascript'] + # Learn more... + # https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#overriding-automatic-language-detection + + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + # We must fetch at least the immediate parents so that if this is + # a pull request then we can checkout the head. + fetch-depth: 2 + + # Initializes the CodeQL tools for scanning. + - name: Initialize CodeQL + uses: github/codeql-action/init@v2 + with: + languages: ${{ matrix.language }} + # If you wish to specify custom queries, you can do so here or in a config file. + # By default, queries listed here will override any specified in a config file. + # Prefix the list here with "+" to use these queries and those in the config file. + # queries: ./path/to/local/query, your-org/your-repo/queries@main + + # Autobuild attempts to build any compiled languages (C/C++, C#, or Java). + # If this step fails, then you should remove it and run the build manually (see below) + - name: Autobuild + uses: github/codeql-action/autobuild@v2 + + # ℹ️ Command-line programs to run using the OS shell. + # 📚 https://git.io/JvXDl + + # ✏️ If the Autobuild fails above, remove it and uncomment the following three lines + # and modify them (or add more) to build your code if your project + # uses a compiled language + + #- run: | + # make bootstrap + # make release + + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v2 diff --git a/plugins/woocommerce-blocks/.github/workflows/community-contributor.yml b/plugins/woocommerce-blocks/.github/workflows/community-contributor.yml new file mode 100644 index 00000000000..efa9221d8fb --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/community-contributor.yml @@ -0,0 +1,36 @@ +name: Add Community Label + +on: + pull_request_target: + types: [opened] + issues: + types: [opened] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +permissions: {} + +jobs: + verify: + name: Verify and add label + runs-on: ubuntu-20.04 + permissions: + contents: read + pull-requests: write + issues: write + steps: + - uses: actions/checkout@v3 + + - name: Setup Node.js + uses: actions/setup-node@8f152de45cc393bb48ce5d89d36b731f54556e65 + + - name: npm install + run: npm install -D + + - name: Check if user is a community contributor + id: check + run: node .github/workflows/scripts/is-community-contributor.js + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/plugins/woocommerce-blocks/.github/workflows/flaky-tests.yml b/plugins/woocommerce-blocks/.github/workflows/flaky-tests.yml new file mode 100644 index 00000000000..3235c0348b1 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/flaky-tests.yml @@ -0,0 +1,38 @@ +name: Report Flaky Tests + +on: + workflow_run: + workflows: ['E2E tests'] + types: + - completed + +jobs: + report-to-issues: + name: Report to GitHub issues + runs-on: ubuntu-latest + if: ${{ github.event.workflow_run.conclusion == 'success' }} + steps: + # Checkout defaults to using the branch which triggered the event, which + # isn't necessarily `trunk` (e.g. in the case of a merge). + - uses: actions/checkout@v3 + with: + repository: WordPress/gutenberg + ref: trunk + + - name: Use desired version of NodeJS + uses: actions/setup-node@8f152de45cc393bb48ce5d89d36b731f54556e65 # v4.0.0 + with: + node-version-file: '.nvmrc' + cache: npm + + - name: Npm install and build + # TODO: We don't have to build the entire project, just the action itself. + run: | + npm ci + npm run build:packages + - name: Report flaky tests + uses: ./packages/report-flaky-tests + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + label: 'type: flaky test' + artifact-name-prefix: flaky-tests-report diff --git a/plugins/woocommerce-blocks/.github/workflows/generate-zip.yml b/plugins/woocommerce-blocks/.github/workflows/generate-zip.yml new file mode 100644 index 00000000000..586ff01b39e --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/generate-zip.yml @@ -0,0 +1,64 @@ +name: Generate ZIP file + +on: [pull_request] + +jobs: + generate-zip-file: + if: ${{ !contains(github.event.pull_request.labels.*.name, 'skip-zip') }} + runs-on: ubuntu-latest + steps: + - name: Checkout + uses: actions/checkout@v3 + + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + + - name: Setup node version and npm cache + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install Node dependencies + if: steps.cache-node-modules.outputs.cache-hit != 'true' + run: npm ci --no-optional + + - name: Generate ZIP file + run: npm run package-plugin:deploy + + - name: Create temp folder + run: mkdir wc-blocks-pr-release__temp + + - name: Rename and move ZIP file + run: mv woocommerce-gutenberg-products-block.zip wc-blocks-pr-release__temp/woocommerce-gutenberg-products-block-${{ github.event.pull_request.number }}.zip + + - name: Transfer ZIP file via SFTP + uses: AbleLincoln/push-to-sftp@v2.1 + with: + host: ${{ secrets.FTP_HOST }} + port: 22 + username: ${{ secrets.FTP_USER }} + password: ${{ secrets.FTP_PASS }} + sourceDir: ./wc-blocks-pr-release__temp/ + targetDir: ${{ secrets.FTP_DIR }} + + - name: Add release ZIP URL as comment to the PR + uses: ./.github/comments-aggregator + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + section-id: release-zip-url + order: 1 + content: | + The release ZIP for this PR is accessible via: + ``` + https://wcblocks.wpcomstaging.com/wp-content/uploads/woocommerce-gutenberg-products-block-${{ github.event.pull_request.number }}.zip + ``` + + - name: Delete ZIP file + run: rm -rf wc-blocks-pr-release__temp diff --git a/plugins/woocommerce-blocks/.github/workflows/js-css-md-linting.yml b/plugins/woocommerce-blocks/.github/workflows/js-css-md-linting.yml new file mode 100644 index 00000000000..75ca3655a89 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/js-css-md-linting.yml @@ -0,0 +1,116 @@ +name: JavaScript, CSS and Markdown Linting + +on: + pull_request: + push: + branches: [trunk] +permissions: + actions: write + checks: write + pull-requests: read + +jobs: + # cache node and modules + Setup: + name: Setup + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + + - name: Setup node version and npm cache + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install Node Dependencies + if: steps.cache-node-modules.outputs.cache-hit != 'true' + run: npm ci --no-optional + + JSLintingCheck: + name: Lint JavaScript + needs: Setup + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + + - name: Setup node version + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + + - name: Save code linting report JSON + run: npm run lint:js:report + # Continue to the next step even if this fails + continue-on-error: true + - name: Upload ESLint report + uses: actions/upload-artifact@v3.1.2 + with: + name: eslint_report.json + path: eslint_report.json + - name: Annotate code linting results + uses: ataylorme/eslint-annotate-action@v2 + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + report-json: 'eslint_report.json' + + CSSLintingCheck: + name: Lint CSS + needs: Setup + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + + - name: Setup node version + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + + - name: Lint CSS + run: npm run lint:css + + MDLintingCheck: + name: Lint MD + needs: Setup + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v3 + - name: Setup node version and npm cache + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + - name: Install Node dependencies + run: npm ci --no-optional + - name: Lint MD + run: npm run lint:md:docs diff --git a/plugins/woocommerce-blocks/.github/workflows/merged-with-labels.yml b/plugins/woocommerce-blocks/.github/workflows/merged-with-labels.yml new file mode 100644 index 00000000000..92a6dc79586 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/merged-with-labels.yml @@ -0,0 +1,16 @@ +on: + pull_request: + types: [ closed ] + +name: Merged Pull Requests + +jobs: + remove_labels: + name: Remove labels + runs-on: ubuntu-latest + steps: + - uses: mondeja/remove-labels-gh-action@v1 + with: + token: ${{ secrets.GITHUB_TOKEN }} + labels: | + status: ready to merge diff --git a/plugins/woocommerce-blocks/.github/workflows/monorepo-merge-notices.yml b/plugins/woocommerce-blocks/.github/workflows/monorepo-merge-notices.yml new file mode 100644 index 00000000000..89bbf67c939 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/monorepo-merge-notices.yml @@ -0,0 +1,33 @@ +name: 'Monorepo Merge Notices' +on: + pull_request_target: + types: [ 'opened' ] + issues: + types: [ 'opened' ] +jobs: + issue_block: + name: 'Block Issues & Pull Requests' + runs-on: 'ubuntu-latest' + steps: + - name: 'Add Merge Notice' + uses: 'actions/github-script@v7' + with: + script: | + github.rest.issues.createComment( { + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: 'Thank you for your interest in contributing to WooCommerce!\n\n\ + WooCommerce Blocks [has been merged into the WooCommerce Monorepo](https://developer.woo.com/2023/12/01/woocommerce-blocks-merging-into-the-woocommerce-monorepo/).\n\n\ + From now on, please open any issues or pull requests in the [woocommerce/woocommerce](https://github.com/woocommerce/woocommerce) repository.' + } ); + - name: 'Close' + uses: 'actions/github-script@v7' + with: + script: | + github.rest.issues.update({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + state: 'closed' + }); diff --git a/plugins/woocommerce-blocks/.github/workflows/nightly-builds.yml b/plugins/woocommerce-blocks/.github/workflows/nightly-builds.yml new file mode 100644 index 00000000000..5570efaa8da --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/nightly-builds.yml @@ -0,0 +1,71 @@ +name: Nightly builds + +on: + schedule: + - cron: '1 0 * * *' # Run at 12:01 AM UTC. + workflow_dispatch: + +env: + NODE_OPTIONS: --max-old-space-size=4096 # development build takes a lot of memory + +jobs: + build: + name: Nightly builds + strategy: + fail-fast: false + matrix: + build: [trunk] + runs-on: ubuntu-20.04 + steps: + - name: Checkout Code + uses: actions/checkout@v3 + with: + ref: ${{ matrix.build }} + + - name: Install Node + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + + - name: Install Node Dependencies + run: npm ci --no-optional + + - name: Build zip + run: bash bin/build-plugin-zip.sh -d + + - name: Deploy nightly build + uses: WebFreak001/deploy-nightly@v2.0.0 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + # 80943895 is the release ID of this nightly release https://github.com/woocommerce/woocommerce-blocks/releases/tag/nightly + upload_url: https://uploads.github.com/repos/${{ github.repository }}/releases/80943895/assets{?name,label} + release_id: 80943895 + asset_path: woocommerce-gutenberg-products-block.zip + asset_name: woocommerce-blocks-${{ matrix.build }}-nightly.zip + asset_content_type: application/zip + max_releases: 1 + - name: Get Date + id: date + uses: lee-dohm/calculate-dates-and-times@v1.0.2 + with: + format: 'YYYY-MM-DD' + subtract: '1 day' + - name: Update release notes + uses: irongut/EditRelease@v1.2.0 + with: + token: ${{ secrets.GITHUB_TOKEN }} + id: 80943895 + body: "Nightly release auto generated everyday at 12:01 AM UTC. \n\n[PRs merged since last nightly build](https://github.com/woocommerce/woocommerce-blocks/pulls?q=is%3Apr+closed%3A>%3D${{ steps.date.outputs.date }}+is%3Amerged)" + spacing: 0 + replacebody: true + update: + name: Update nightly tag commit ref + runs-on: ubuntu-20.04 + steps: + - name: Update nightly tag + uses: richardsimko/github-tag-action@v1.0.11 + with: + tag_name: nightly + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} diff --git a/plugins/woocommerce-blocks/.github/workflows/php-coding-standards.yml b/plugins/woocommerce-blocks/.github/workflows/php-coding-standards.yml new file mode 100644 index 00000000000..082d1747725 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/php-coding-standards.yml @@ -0,0 +1,65 @@ +name: PHP Coding Standards + +on: + push: + branches: + - trunk + pull_request: + +jobs: + # Runs PHP coding standards checks. + # Note: Inspired by https://github.com/WordPress/wordpress-develop/blob/master/.github/workflows/coding-standards.yml + # + # Violations are reported inline with annotations. + # + # Performs the following steps: + # - Checks out the repository. + # - Configures caching for Composer. + # - Sets up PHP. + # - Logs debug information. + # - Installs Composer dependencies (from cache if possible). + # - Logs PHP_CodeSniffer debug information. + # - Runs PHPCS on the full codebase with warnings suppressed. + # - todo: Configure Slack notifications for failing scans. + phpcs: + name: PHP coding standards + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + + - name: Get Composer cache directory + id: composer-cache + run: echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT + + + - name: Set up Composer caching + uses: actions/cache@v3 + env: + cache-name: cache-composer-dependencies + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-composer- + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.0' + coverage: none + tools: composer, cs2pr + + - name: Log debug information + run: | + php --version + composer --version + - name: Install Composer dependencies + run: | + composer install --prefer-dist --no-suggest --no-progress --no-ansi --no-interaction + echo "${PWD}/vendor/bin" >> $GITHUB_PATH + - name: Log PHPCS debug information + run: phpcs -i + + - name: Run PHPCS on all changed files + run: | + phpcs ./src -q --report=checkstyle | cs2pr diff --git a/plugins/woocommerce-blocks/.github/workflows/php-js-e2e-tests.yml b/plugins/woocommerce-blocks/.github/workflows/php-js-e2e-tests.yml new file mode 100644 index 00000000000..572e222482b --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/php-js-e2e-tests.yml @@ -0,0 +1,174 @@ +name: E2E tests + +on: + push: + branches: [trunk] + pull_request: + +jobs: + JSE2EWithGutenberg: + if: ${{ false }} # disable until we've fixed failing tests. + strategy: + fail-fast: false + matrix: + part: [1, 2, 3, 4, 5] + name: JavaScript E2E Tests (WP latest with Gutenberg plugin) + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + + - name: Setup node version and npm cache + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install Node Dependencies + if: steps.cache-node-modules.outputs.cache-hit != 'true' + run: npm ci --no-optional + + - name: Build Assets + run: FORCE_REDUCED_MOTION=true npm run build + + - name: blocks.ini setup + run: | + echo -e 'woocommerce_blocks_phase = 3\nwoocommerce_blocks_env = tests' > blocks.ini + - name: Get Composer Cache Directory + id: composer-cache + run: | + echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT + + - uses: actions/cache@v3 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-composer- + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.0' + coverage: none + tools: composer + + - name: Composer install + run: | + composer install + - name: E2E Tests (WP latest with Gutenberg plugin) + env: + WOOCOMMERCE_BLOCKS_PHASE: 3 + run: | + node ./bin/wp-env-with-gutenberg.js + npm run wp-env start + npm run wp-env:config && npx cross-env NODE_CONFIG_DIR=tests/e2e-jest/config wp-scripts test-e2e --config tests/e2e-jest/config/jest.config.js --listTests > ~/.jest-e2e-tests + npx cross-env JEST_PUPPETEER_CONFIG=tests/e2e-jest/config/jest-puppeteer.config.js cross-env NODE_CONFIG_DIR=tests/e2e-jest/config wp-scripts test-e2e --config tests/e2e-jest/config/jest.config.js --runInBand --runTestsByPath $( awk 'NR % 5 == ${{ matrix.part }} - 1' < ~/.jest-e2e-tests ) + + - name: Upload artifacts on failure + if: ${{ failure() }} + uses: actions/upload-artifact@v3.1.2 + with: + name: e2e-with-gutenberg-test-report-${{matrix.part}} + path: reports/e2e + + - name: Archive flaky tests report + uses: actions/upload-artifact@v3.1.2 + if: always() + with: + name: flaky-tests-report-${{ matrix.part }} + path: flaky-tests + if-no-files-found: ignore + + JSE2ETests: + name: JavaScript E2E Tests (latest) + strategy: + fail-fast: false + matrix: + part: [1, 2, 3, 4, 5] + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-modified-build-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-modified-build-${{ env.cache-name }}- + ${{ runner.os }}-modified-build- + ${{ runner.os }}-modified- + + - name: Setup node version and npm cache + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install Node dependencies + if: steps.cache-node-modules.outputs.cache-hit != 'true' + run: npm install --no-optional --no-audit + + - name: Build Assets + run: FORCE_REDUCED_MOTION=true npm run build + + - name: blocks.ini setup + run: | + echo -e 'woocommerce_blocks_phase = 3\nwoocommerce_blocks_env = tests' > blocks.ini + - name: Get Composer Cache Directory + id: composer-cache + run: | + echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT + - uses: actions/cache@v3 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-composer- + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.0' + coverage: none + tools: composer + + - name: Composer install + run: | + composer install + + - name: E2E Tests (WP latest) + env: + WOOCOMMERCE_BLOCKS_PHASE: 3 + run: | + node ./bin/wp-env-with-wp-641.js + npm run wp-env start + npm run wp-env:config && npx cross-env NODE_CONFIG_DIR=tests/e2e-jest/config wp-scripts test-e2e --config tests/e2e-jest/config/jest.config.js --listTests > ~/.jest-e2e-tests + npx cross-env JEST_PUPPETEER_CONFIG=tests/e2e-jest/config/jest-puppeteer.config.js cross-env NODE_CONFIG_DIR=tests/e2e-jest/config wp-scripts test-e2e --config tests/e2e-jest/config/jest.config.js --runInBand --runTestsByPath $( awk 'NR % 5 == ${{ matrix.part }} - 1' < ~/.jest-e2e-tests ) --listTests + npx cross-env JEST_PUPPETEER_CONFIG=tests/e2e-jest/config/jest-puppeteer.config.js cross-env NODE_CONFIG_DIR=tests/e2e-jest/config wp-scripts test-e2e --config tests/e2e-jest/config/jest.config.js --runInBand --runTestsByPath $( awk 'NR % 5 == ${{ matrix.part }} - 1' < ~/.jest-e2e-tests ) + + - name: Upload artifacts on failure + if: ${{ failure() }} + uses: actions/upload-artifact@v3.1.2 + with: + name: e2e-test-report-${{matrix.part}} + path: reports/e2e + + - name: Archive flaky tests report + uses: actions/upload-artifact@v3.1.2 # v2.2.2 + if: always() + with: + name: flaky-tests-report-${{ matrix.part }} + path: flaky-tests + if-no-files-found: ignore diff --git a/plugins/woocommerce-blocks/.github/workflows/playwright.yml b/plugins/woocommerce-blocks/.github/workflows/playwright.yml new file mode 100644 index 00000000000..90202ccab89 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/playwright.yml @@ -0,0 +1,90 @@ +name: Playwright Tests +on: + push: + branches: [ trunk ] + pull_request: + +jobs: + PlaywrightE2ETests: + + name: Playwright E2E tests - ${{ matrix.config.name }} + timeout-minutes: 60 + runs-on: ubuntu-latest + strategy: + matrix: + config: [ + { name: Normal, file: playwright.config.ts, resultPath: test-results }, + { name: Classic, file: playwright.classic-theme.config.ts, resultPath: test-results-classic-theme }, + { name: SideEffects, file: playwright.side-effects.config.ts, resultPath: test-results-side-effects }, + ] + steps: + + - uses: actions/checkout@v3 + + - name: Cache node_modules + id: cache-node-modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + path: node_modules + key: ${{ runner.os }}-modified-build-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.os }}-modified-build-${{ env.cache-name }}- + ${{ runner.os }}-modified-build- + ${{ runner.os }}-modified- + + - name: Setup node version and npm cache + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Install Node dependencies + if: steps.cache-node-modules.outputs.cache-hit != 'true' + run: npm ci + + - name: Build Assets + run: FORCE_REDUCED_MOTION=true npm run build + + - name: blocks.ini setup + run: | + echo -e 'woocommerce_blocks_phase = 3\nwoocommerce_blocks_env = tests' > blocks.ini + - name: Get Composer Cache Directory + id: composer-cache + run: | + echo "dir=$(composer config cache-files-dir)" >> $GITHUB_OUTPUT + - uses: actions/cache@v3 + with: + path: ${{ steps.composer-cache.outputs.dir }} + key: ${{ runner.os }}-composer-${{ hashFiles('**/composer.lock') }} + restore-keys: | + ${{ runner.os }}-composer- + + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '8.0' + coverage: none + tools: composer + + - name: Composer install + run: composer install + + - name: Install Playwright + run: npx playwright install --with-deps + + - name: Load wp-env + run: npm run env:start + + - name: Run Playwright tests + run: npm run test:e2e -- --config=tests/e2e/${{ matrix.config.file }} + + - uses: actions/upload-artifact@v3 + if: ${{ failure() }} + + with: + name: playwright-report-${{ matrix.config.name }} + path: artifacts/${{ matrix.config.resultPath }} + if-no-files-found: error # 'warn' or 'ignore' are also available, defaults to `warn` + diff --git a/plugins/woocommerce-blocks/.github/workflows/pr-label-validation.yml b/plugins/woocommerce-blocks/.github/workflows/pr-label-validation.yml new file mode 100644 index 00000000000..bed1eb4b442 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/pr-label-validation.yml @@ -0,0 +1,24 @@ +name: Pull Request Label Validation + +on: + pull_request: + branches: + - trunk + types: + - labeled + - unlabeled + - opened + - reopened + - synchronize + - edited + +env: + LABELS: ${{ join( github.event.pull_request.labels.*.name, ' ' ) }} + +jobs: + check-type-label: + name: Check [Type] Label + runs-on: ubuntu-latest + steps: + - if: contains( env.LABELS, 'type' ) == false && contains( env.LABELS, 'skip-changelog' ) == false + run: exit 1 diff --git a/plugins/woocommerce-blocks/.github/workflows/project-management-automations.yml b/plugins/woocommerce-blocks/.github/workflows/project-management-automations.yml new file mode 100644 index 00000000000..b76c2a96a3a --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/project-management-automations.yml @@ -0,0 +1,21 @@ +on: + pull_request: + types: [opened, synchronize, closed] + push: + issues: + types: [edited] +name: Project management automations +permissions: + pull-requests: write + actions: write +jobs: + project-management-automation: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + ref: trunk + - uses: woocommerce/automations@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + automations: todos diff --git a/plugins/woocommerce-blocks/.github/workflows/release-pull-request.yml b/plugins/woocommerce-blocks/.github/workflows/release-pull-request.yml new file mode 100644 index 00000000000..7d728a28377 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/release-pull-request.yml @@ -0,0 +1,35 @@ +name: Release Pull Request Automation + +# Controls when the action will run. Triggers the workflow on create branch or tag +# events but only acts on branch create. +on: + create: +jobs: + release-pull-request-automation: + if: ${{ github.event.ref_type == 'branch' && contains( github.ref, 'release/' ) }} + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + runs-on: ubuntu-latest + steps: + - uses: act10ns/slack@v2 + with: + status: starting + if: ${{ always() }} + - name: Checkout code + uses: actions/checkout@v3 + - name: Create changeset for pull request + run: | + git config user.name github-actions + git config user.email github-actions@github.com + git commit -m 'Empty commit for release pull request' --allow-empty + git push + - name: Create Release Pull Request + uses: woocommerce/automations@v1 + with: + github_token: ${{ secrets.GITHUB_TOKEN }} + automations: release + - uses: act10ns/slack@v2 + with: + status: ${{ job.status }} + steps: ${{ toJson(steps) }} + if: ${{ always() }} diff --git a/plugins/woocommerce-blocks/.github/workflows/scripts/is-community-contributor.js b/plugins/woocommerce-blocks/.github/workflows/scripts/is-community-contributor.js new file mode 100644 index 00000000000..4ac92674981 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/scripts/is-community-contributor.js @@ -0,0 +1,67 @@ +// Note you'll need to install these dependencies as part of your workflow. +const { Octokit } = require( '@octokit/action' ); +const core = require( '@actions/core' ); + +// Note that this script assumes you set GITHUB_TOKEN in env, if you don't +// this won't work. +const octokit = new Octokit(); + +const ignoredUsernames = [ 'dependabot[bot]' ]; +const checkIfIgnoredUsername = ( username ) => + ignoredUsernames.includes( username ); + +const getIssueAuthor = ( payload ) => { + return ( + payload?.issue?.user?.login || + payload?.pull_request?.user?.login || + null + ); +}; + +const isCommunityContributor = async ( owner, repo, username ) => { + if ( username && ! checkIfIgnoredUsername( username ) ) { + const { + data: { permission }, + } = await octokit.rest.repos.getCollaboratorPermissionLevel( { + owner, + repo, + username, + } ); + + return permission === 'read' || permission === 'none'; + } + + console.log( 'Not a community contributor!' ); + return false; +}; + +const addLabel = async ( label, owner, repo, issueNumber ) => { + await octokit.rest.issues.addLabels( { + owner, + repo, + issue_number: issueNumber, + labels: [ label ], + } ); +}; + +const applyLabelToCommunityContributor = async () => { + const eventPayload = require( process.env.GITHUB_EVENT_PATH ); + const username = getIssueAuthor( eventPayload ); + const [ owner, repo ] = process.env.GITHUB_REPOSITORY.split( '/' ); + const { number } = eventPayload?.issue || eventPayload?.pull_request; + + const isCommunityUser = await isCommunityContributor( + owner, + repo, + username + ); + + core.setOutput( 'is-community', isCommunityUser ? 'yes' : 'no' ); + + if ( isCommunityUser ) { + console.log( 'Adding community contributor label' ); + await addLabel( 'type: community contribution', owner, repo, number ); + } +}; + +applyLabelToCommunityContributor(); diff --git a/plugins/woocommerce-blocks/.github/workflows/typescript-monitoring.yml b/plugins/woocommerce-blocks/.github/workflows/typescript-monitoring.yml new file mode 100644 index 00000000000..7a997fd4f56 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/typescript-monitoring.yml @@ -0,0 +1,68 @@ +name: Monitor TypeScript errors +on: + push: + branches: [trunk] + pull_request: + +jobs: + check-typescript-errors-with-trunk: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + with: + ref: 'trunk' + + - name: Cache node modules + uses: actions/cache@v3 + env: + cache-name: cache-node-modules + with: + # npm cache files are stored in `~/.npm` on Linux/macOS + path: ~/.npm + key: ${{ runner.OS }}-build-${{ secrets.CACHE_VERSION }}-${{ env.cache-name }}-${{ hashFiles('**/package-lock.json') }} + restore-keys: | + ${{ runner.OS }}-build-${{ secrets.CACHE_VERSION }}-${{ env.cache-name }}- + ${{ runner.OS }}-build-${{ secrets.CACHE_VERSION }}- + + - name: Use Node.js + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: 'npm' + + - name: Generate checkstyle for trunk + run: | + npm ci + npm run ts:log-errors + mv checkstyle.xml $HOME/checkstyle-trunk.xml + + - uses: actions/checkout@v3 + + - name: Generate checkstyle for current PR + run: | + npm ci + npm run ts:log-errors + mv $HOME/checkstyle-trunk.xml checkstyle-trunk.xml + + - name: Get branch name + id: branch-name + uses: tj-actions/branch-names@v7 + + - name: Monitor TypeScript errors + uses: ./.github/monitor-typescript-errors + id: monitor-typescript-errors + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + checkstyle: checkstyle.xml + checkstyle-trunk: checkstyle-trunk.xml + create-comment: false + env: + AIRTABLE_API_KEY: ${{ secrets.AIRTABLE_API_KEY }} + CURRENT_BRANCH: ${{ steps.branch-name.outputs.current_branch }} + - name: Append report + uses: ./.github/comments-aggregator + with: + repo-token: '${{ secrets.GITHUB_TOKEN }}' + section-id: monitor-typescript-errors + content: ${{steps.monitor-typescript-errors.outputs.comment}} + order: 20 diff --git a/plugins/woocommerce-blocks/.github/workflows/unit-tests.yml b/plugins/woocommerce-blocks/.github/workflows/unit-tests.yml new file mode 100644 index 00000000000..33ac82d7abf --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/unit-tests.yml @@ -0,0 +1,128 @@ +name: Unit Tests + +# Since Unit Tests are required to pass for each PR, +# we cannot disable them for documentation-only changes. +on: + pull_request: + push: + branches: [trunk] + # Allow manually triggering the workflow. + workflow_dispatch: + +# Cancels all previous workflow runs for pull requests that have not completed. +concurrency: + # The concurrency group contains the workflow name and the branch name for pull requests + # or the commit hash for any other events. + group: ${{ github.workflow }}-${{ github.event_name == 'pull_request' && github.head_ref || github.sha }} + cancel-in-progress: true + +jobs: + JSUnitTests: + name: JS Unit Tests + runs-on: ubuntu-latest + if: ${{ github.repository == 'WooCommerce/WooCommerce-Blocks' || github.event_name == 'pull_request' }} + + strategy: + fail-fast: false + + steps: + - uses: actions/checkout@v3 + + - name: Use desired version of NodeJS + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: npm + + - name: Npm install and build + run: | + npm ci --no-optional + FORCE_REDUCED_MOTION=true npm run build + + - name: blocks.ini setup + run: echo -e 'woocommerce_blocks_phase = 3\nwoocommerce_blocks_env = test' > blocks.ini + + - name: Run JavaScript Unit tests + run: npm run test + + PHPUnitTests: + name: PHP ${{ matrix.php }} + runs-on: ubuntu-latest + timeout-minutes: 20 + if: ${{ github.repository == 'WooCommerce/WooCommerce-Blocks' || github.event_name == 'pull_request' }} + strategy: + fail-fast: true + matrix: + php: + - '7.4' + - '8.0' + - '8.1' + - '8.2' + + env: + WP_ENV_PHP_VERSION: ${{ matrix.php }} + + steps: + - uses: actions/checkout@v3 + + - name: Set up Node.js + uses: actions/setup-node@v4 + with: + node-version-file: '.nvmrc' + cache: npm + + ## + # This allows Composer dependencies to be installed using a single step. + # + # Since the tests are currently run within the Docker containers where the PHP version varies, + # the same PHP version needs to be configured for the action runner machine so that the correct + # dependency versions are installed and cached. + ## + - name: Set up PHP + uses: shivammathur/setup-php@v2 + with: + php-version: '${{ matrix.php }}' + ini-file: development + coverage: none + + # Ensure that Composer installs the correct versions of packages. + - name: Override PHP version in composer.json + run: | + composer config platform.php ${{ matrix.php }} + composer update + + - name: Install npm dependencies + run: | + npm ci + npm run build + + - name: Docker debug information + run: | + docker -v + docker-compose -v + + - name: General debug information + run: | + npm --version + node --version + curl --version + git --version + svn --version + locale -a + + - name: Start Docker environment + run: npm run wp-env start --update + + - name: Log running Docker containers + run: docker ps -a + + - name: Docker container debug information + run: | + npm run wp-env run tests-mysql mysql -- --version + npm run wp-env run tests-wordpress php -- --version + npm run wp-env run tests-wordpress php -- -m + npm run wp-env run tests-wordpress php -- -i + npm run wp-env run tests-wordpress locale -- -a + + - name: Run PHPUnit tests + run: npm run test:php diff --git a/plugins/woocommerce-blocks/.github/workflows/wordpress-deploy.yml b/plugins/woocommerce-blocks/.github/workflows/wordpress-deploy.yml new file mode 100644 index 00000000000..e07c3b08960 --- /dev/null +++ b/plugins/woocommerce-blocks/.github/workflows/wordpress-deploy.yml @@ -0,0 +1,40 @@ +name: Deploy to WordPress.org +on: + release: + types: [released] +jobs: + tag: + name: New Release + runs-on: ubuntu-latest + env: + SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} + steps: + - uses: act10ns/slack@v2 + with: + status: starting + if: ${{ always() }} + - name: Checkout code + uses: actions/checkout@v3 + - name: WordPress Plugin Deploy + id: deploy + uses: 10up/action-wordpress-plugin-deploy@stable + with: + generate-zip: true + env: + SVN_USERNAME: ${{ secrets.SVN_USERNAME }} + SVN_PASSWORD: ${{ secrets.SVN_PASSWORD }} + SLUG: woo-gutenberg-products-block + - name: Upload release asset + uses: actions/upload-release-asset@v1 + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + with: + upload_url: ${{ github.event.release.upload_url }} + asset_path: ${{github.workspace}}/woo-gutenberg-products-block.zip + asset_name: woo-gutenberg-products-block.zip + asset_content_type: application/zip + - uses: act10ns/slack@v2 + with: + status: ${{ job.status }} + steps: ${{ toJson(steps) }} + if: ${{ always() }} diff --git a/plugins/woocommerce-blocks/.gitignore b/plugins/woocommerce-blocks/.gitignore new file mode 100644 index 00000000000..6b905dd43dd --- /dev/null +++ b/plugins/woocommerce-blocks/.gitignore @@ -0,0 +1,69 @@ +# Editors +project.xml +project.properties +/nbproject/private/ +.buildpath +.project +.settings* +.idea +.vscode +!.vscode/extensions.json +!.vscode/storybook.code-snippets +*.sublime-project +*.sublime-workspace +.sublimelinterrc + +# Grunt +/node_modules/ +none + +# Sass +.sass-cache/ + +# OS X metadata +.DS_Store + +# Windows junk +Thumbs.db + +# ApiGen +/wc-apidocs/ + +# Behat/CLI Tests +tests/cli/installer +tests/cli/composer.phar +tests/cli/composer.lock +tests/cli/composer.json +tests/cli/vendor + +# Unit tests +/tmp +/tests/bin/tmp +/reports + +# E2E tests +/tests/e2e-tests/config/local-*.json +**/e2e/test-results/ +**/e2e/artifacts/ +/artifacts/ +/playwright-report/ +**/e2e/.auth + +# Logs +/logs + +# Composer +/vendor/ + +# Built files +/build/ +bin/languages +bin/eslint-plugin-woocommerce/node_modules/ +woocommerce-gutenberg-products-block.zip +storybook-static/ +blocks.ini +/wp-content/ +/.wp-env.override.json +/eslint_report.json +/storybook/dist +.phpunit.result.cache diff --git a/plugins/woocommerce-blocks/.husky/pre-commit b/plugins/woocommerce-blocks/.husky/pre-commit new file mode 100755 index 00000000000..d4a43dd13e8 --- /dev/null +++ b/plugins/woocommerce-blocks/.husky/pre-commit @@ -0,0 +1,4 @@ +#!/usr/bin/env sh +. "$(dirname -- "$0")/_/husky.sh" + +npm run pre-commit diff --git a/plugins/woocommerce-blocks/.markdownlint.json b/plugins/woocommerce-blocks/.markdownlint.json new file mode 100644 index 00000000000..46f253c2e8f --- /dev/null +++ b/plugins/woocommerce-blocks/.markdownlint.json @@ -0,0 +1,13 @@ +{ + "default": true, + "MD003": { "style": "atx" }, + "MD007": { "indent": 4 }, + "MD013": { "line_length": 9999 }, + "MD024": false, + "MD025": false, + "MD029": false, + "MD033": false, + "MD046": { "style": "fenced" }, + "no-hard-tabs": false, + "whitespace": false +} diff --git a/plugins/woocommerce-blocks/.markdownlintignore b/plugins/woocommerce-blocks/.markdownlintignore new file mode 100644 index 00000000000..bdbff91bedd --- /dev/null +++ b/plugins/woocommerce-blocks/.markdownlintignore @@ -0,0 +1,4 @@ +**/node_modules/** +**/vendor/** +**/extensibility/**/actions.md +**/extensibility/**/filters.md diff --git a/plugins/woocommerce-blocks/.nvmrc b/plugins/woocommerce-blocks/.nvmrc new file mode 100644 index 00000000000..99cdd8009c3 --- /dev/null +++ b/plugins/woocommerce-blocks/.nvmrc @@ -0,0 +1 @@ +16.15.0 diff --git a/plugins/woocommerce-blocks/.prettierignore b/plugins/woocommerce-blocks/.prettierignore new file mode 100644 index 00000000000..7e155376458 --- /dev/null +++ b/plugins/woocommerce-blocks/.prettierignore @@ -0,0 +1,3 @@ +*.json +*.scss +*.yml diff --git a/plugins/woocommerce-blocks/.prettierrc.js b/plugins/woocommerce-blocks/.prettierrc.js new file mode 100644 index 00000000000..51b8aeb4150 --- /dev/null +++ b/plugins/woocommerce-blocks/.prettierrc.js @@ -0,0 +1,3 @@ +// Import the default config file and expose it in the project root. +// Useful for editor integrations. +module.exports = require( '@wordpress/prettier-config' ); diff --git a/plugins/woocommerce-blocks/.sources/block-previews.sketch b/plugins/woocommerce-blocks/.sources/block-previews.sketch new file mode 100644 index 00000000000..a378fc76f11 Binary files /dev/null and b/plugins/woocommerce-blocks/.sources/block-previews.sketch differ diff --git a/plugins/woocommerce-blocks/.sources/handles.sketch b/plugins/woocommerce-blocks/.sources/handles.sketch new file mode 100644 index 00000000000..6a7e82ebf2d Binary files /dev/null and b/plugins/woocommerce-blocks/.sources/handles.sketch differ diff --git a/plugins/woocommerce-blocks/.stylelintrc.json b/plugins/woocommerce-blocks/.stylelintrc.json new file mode 100644 index 00000000000..baee43fc2a8 --- /dev/null +++ b/plugins/woocommerce-blocks/.stylelintrc.json @@ -0,0 +1,15 @@ +{ + "extends": "@wordpress/stylelint-config/scss", + "rules": { + "at-rule-empty-line-before": null, + "at-rule-no-unknown": null, + "comment-empty-line-before": null, + "font-weight-notation": null, + "max-line-length": null, + "no-descending-specificity": null, + "no-duplicate-selectors": null, + "rule-empty-line-before": null, + "selector-class-pattern": null, + "value-keyword-case": null + } +} diff --git a/plugins/woocommerce-blocks/.vscode/extensions.json b/plugins/woocommerce-blocks/.vscode/extensions.json new file mode 100644 index 00000000000..536e5a17f59 --- /dev/null +++ b/plugins/woocommerce-blocks/.vscode/extensions.json @@ -0,0 +1,16 @@ +{ + "recommendations": [ + "dbaeumer.vscode-eslint", + "esbenp.prettier-vscode", + "wordpresstoolbox.wordpress-toolbox", + "claudiosanches.woocommerce", + "andys8.jest-snippets", + "eamodio.gitlens", + "bmewburn.vscode-intelephense-client", + "neilbrayfield.php-docblocker", + "valeryanm.vscode-phpsab", + "editorconfig.editorconfig", + "stylelint.vscode-stylelint", + "DavidAnson.vscode-markdownlint" + ] +} diff --git a/plugins/woocommerce-blocks/.vscode/storybook.code-snippets b/plugins/woocommerce-blocks/.vscode/storybook.code-snippets new file mode 100644 index 00000000000..1050fda3b4e --- /dev/null +++ b/plugins/woocommerce-blocks/.vscode/storybook.code-snippets @@ -0,0 +1,40 @@ +{ + "Storybook Story": { + "prefix": [ "storybook", "sbs" ], + "body": [ + "/**", + " * External dependencies", + " */", + "import type { Story, Meta } from '@storybook/react';", + "", + "/**", + " * Internal dependencies", + " */", + "import ${1:${TM_DIRECTORY/.*\\/(.*)\\/.*$/${1:/pascalcase}/}}, { ${2:${TM_DIRECTORY/.*\\/(.*)\\/.*$/${1:/pascalcase}/}Props} } from '..';", + "", + "export default {", + "\ttitle: 'WooCommerce Blocks/${3|@base-components,editor-components,woocommerce,Checkout Blocks|}/${1}',", + "\tcomponent: ${1},", + "} as Meta< ${2} >;", + "", + "const Template: Story< ${2} > = ( args ) => (", + "\t<${1} { ...args } />", + ");", + "", + "export const Default = Template.bind( {} );", + "Default.args = {};", + "" + ], + "description": "Scaffolds a Storybook story", + "scope": "typescript, typescriptreact" + }, + "Storybook Story from Template": { + "prefix": [ "sbt" ], + "body": [ + "export const ${1:MyStory} = Template.bind( {} );", + "$1.args = {", + "\t$2", + "};" + ] + } +} diff --git a/plugins/woocommerce-blocks/.wordpress-org/banner-1544x500.png b/plugins/woocommerce-blocks/.wordpress-org/banner-1544x500.png new file mode 100644 index 00000000000..3a83246f164 Binary files /dev/null and b/plugins/woocommerce-blocks/.wordpress-org/banner-1544x500.png differ diff --git a/plugins/woocommerce-blocks/.wordpress-org/banner-772x250.png b/plugins/woocommerce-blocks/.wordpress-org/banner-772x250.png new file mode 100644 index 00000000000..b932f21dd77 Binary files /dev/null and b/plugins/woocommerce-blocks/.wordpress-org/banner-772x250.png differ diff --git a/plugins/woocommerce-blocks/.wordpress-org/icon-128x128.png b/plugins/woocommerce-blocks/.wordpress-org/icon-128x128.png new file mode 100644 index 00000000000..6d5a0f50715 Binary files /dev/null and b/plugins/woocommerce-blocks/.wordpress-org/icon-128x128.png differ diff --git a/plugins/woocommerce-blocks/.wordpress-org/icon-256x256.png b/plugins/woocommerce-blocks/.wordpress-org/icon-256x256.png new file mode 100644 index 00000000000..1ff4a1d6106 Binary files /dev/null and b/plugins/woocommerce-blocks/.wordpress-org/icon-256x256.png differ diff --git a/plugins/woocommerce-blocks/.wp-env.json b/plugins/woocommerce-blocks/.wp-env.json new file mode 100644 index 00000000000..f9f80b3bc3b --- /dev/null +++ b/plugins/woocommerce-blocks/.wp-env.json @@ -0,0 +1,39 @@ +{ + "core": null, + "plugins": [ + "https://downloads.wordpress.org/plugin/woocommerce.latest-stable.zip", + "https://github.com/WP-API/Basic-Auth/archive/master.zip", + "https://downloads.wordpress.org/plugin/wordpress-importer.0.8.zip", + "./tests/mocks/woo-test-helper", + "." + ], + "env": { + "tests": { + "mappings": { + "wp-content/mu-plugins": "./node_modules/@wordpress/e2e-tests/mu-plugins", + "wp-content/plugins/gutenberg-test-plugins": "./node_modules/@wordpress/e2e-tests/plugins", + "wp-content/plugins/woocommerce-blocks": ".", + "wp-content/plugins/woocommerce-gutenberg-products-block": ".", + "wp-cli.yml": "./wp-cli.yml", + "custom-plugins" : "./tests/e2e/mocks/custom-plugins" + } + } + }, + "themes": [ + "https://downloads.wordpress.org/theme/storefront.latest-stable.zip", + "https://downloads.wordpress.org/theme/twentytwentyone.latest-stable.zip", + "https://downloads.wordpress.org/theme/twentytwentyfour.latest-stable.zip", + "./tests/mocks/emptytheme", + "./tests/mocks/theme-with-woo-templates" + ], + "config": { + "JETPACK_AUTOLOAD_DEV": true, + "SCRIPT_DEBUG": false, + "WP_TESTS_DOMAIN": "http://localhost:8889", + "WP_TESTS_EMAIL": "admin@example.org", + "WP_TESTS_TITLE": "Test Blog", + "WP_PHP_BINARY": "php", + "WP_TESTS_DIR": "./tests/php", + "WP_PHPUNIT__TESTS_CONFIG": "./vendor/wp-phpunit/wp-phpunit/wp-tests-config.php" + } +} diff --git a/plugins/woocommerce-blocks/LICENSE b/plugins/woocommerce-blocks/LICENSE new file mode 100644 index 00000000000..f288702d2fa --- /dev/null +++ b/plugins/woocommerce-blocks/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/plugins/woocommerce-blocks/README.md b/plugins/woocommerce-blocks/README.md new file mode 100644 index 00000000000..78aba52ee6b --- /dev/null +++ b/plugins/woocommerce-blocks/README.md @@ -0,0 +1,81 @@ +# WooCommerce Blocks + +[![Latest Tag](https://img.shields.io/github/tag/woocommerce/woocommerce-gutenberg-products-block.svg?style=flat&label=Latest%20Tag)](https://github.com/woocommerce/woocommerce-gutenberg-products-block/releases) +[![View](https://img.shields.io/badge/Project%20Components-brightgreen.svg?style=flat)](https://woocommerce.github.io/woocommerce-blocks/) +![JavaScript and CSS Linting](https://github.com/woocommerce/woocommerce-gutenberg-products-block/workflows/JavaScript%20and%20CSS%20Linting/badge.svg?branch=trunk) +![PHP Coding Standards](https://github.com/woocommerce/woocommerce-gutenberg-products-block/workflows/PHP%20Coding%20Standards/badge.svg?branch=trunk) +![Unit Tests](https://github.com/woocommerce/woocommerce-blocks/workflows/E2E%20tests/badge.svg?branch=trunk) +![E2E Tests](https://github.com/woocommerce/woocommerce-blocks/workflows/Unit%20Tests/badge.svg?branch=trunk) + +This is the feature plugin for WooCommerce + the Gutenberg. This plugin serves as a space to iterate and explore new Blocks and updates to existing blocks for WooCommerce, and how WooCommerce might work with the block editor. + +Use this plugin if you want access to the bleeding edge of available blocks for WooCommerce. However, stable blocks are bundled into WooCommerce, and can be added from the "WooCommerce" section in the block inserter. + +- [WCCOM product page](https://woocommerce.com/products/woocommerce-gutenberg-products-block/) +- [User documentation](https://docs.woocommerce.com/document/woocommerce-blocks/) + +## Table of Contents + +- [Documentation](#documentation) + - [Code Documentation](#code-documentation) +- [Installing the plugin version](#installing-the-plugin-version) +- [Installing the development version](#installing-the-development-version) +- [Getting started with block development](#getting-started-with-block-development) +- [Long-term vision](#long-term-vision) + +## Documentation + +To find out more about the blocks and how to use them, [check out the documentation on WooCommerce.com](https://docs.woocommerce.com/document/woocommerce-blocks/). + +If you want to see what we're working on for future versions, or want to help out, read on. + +### Code Documentation + +- [Blocks](./assets/js/blocks) - Documentation for specific Blocks. +- [Editor Components](assets/js/editor-components) - Shared components used in WooCommerce blocks for the editor (Gutenberg) UI. +- [WooCommerce Blocks Handbook](./docs) - Documentation for designers and developers on how to extend or contribute to blocks, and how internal developers should handle new releases. +- [WooCommerce Blocks Storybook](https://woocommerce.github.io/woocommerce-blocks/) - Contains a list and demo of components used in the plugin. + +## Installing the plugin version + +We release a new version of WooCommerce Blocks onto WordPress.org every few weeks, which can be used as an easier way to preview the features. + +> Note: The plugin follows a policy of supporting the "L0" strategy for version support. What this means is that the plugin will require the most recent version of WordPress. It will also require the most recent version of WooCommerce core at the time of a release. You can read more about [this policy here](https://developer.woocommerce.com/?p=9998). + +1.Ensure you have the latest available versions of WordPress and WooCommerce installed on your site. +2. The plugin version is available on WordPress.org. [Download the plugin version here.](https://wordpress.org/plugins/woo-gutenberg-products-block/) +3. Activate the plugin. + +## Installing the development version + +1. Ensure you have the latest versions of WordPress and WooCommerce installed on your site. +2. Get a copy of this plugin using the green "Clone or download" button on the right. +3. Make sure you're using Node.js v16.15. If you use a Node version management tool such as `nvm` or `n`, you can do so by running `nvm use` or `n auto`, respectively. +4. `npm install` to install the dependencies. +5. `composer install` to install core dependencies. +6. To compile the code, run any of the following commands + 1. `npm run build` (production build). + 2. `npm run dev` (development build). + 3. `npm start` (development build + watching for changes). +7. Activate the plugin. + +The source code is in the `assets/` folder, and the compiled code is stored into `build/`. + +## Getting started with block development + +Run through the ["Writing Your First Block Type" tutorial](https://developer.wordpress.org/block-editor/how-to-guides/block-tutorial/writing-your-first-block-type/) for a quick course in block-building. + +For deeper dive, try looking at the [core blocks code,](https://github.com/WordPress/gutenberg/tree/master/packages/block-library/src) or see what [components are available.](https://github.com/WordPress/gutenberg/tree/master/packages/components/src) + +To begin contributing to the WooCommerce Blocks plugin, see our [getting started guide](./docs/contributors/getting-started.md) and [developer handbook](./docs/README.md). + +Other useful docs to explore: + +- [`InnerBlocks`](https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/inner-blocks/README.md) +- [`apiFetch`](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-api-fetch/) +- [`@wordpress/editor`](https://github.com/WordPress/gutenberg/blob/master/packages/editor/README.md) +- [`@wordpress/create-block`](https://developer.wordpress.org/block-editor/reference-guides/packages/packages-create-block/) + +## Long-term vision + +WooCommerce Blocks are the easiest, most flexible way to build your store's user interface and showcase your products. diff --git a/plugins/woocommerce-blocks/assets/css/abstracts/_breakpoints.scss b/plugins/woocommerce-blocks/assets/css/abstracts/_breakpoints.scss new file mode 100644 index 00000000000..2e091794169 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/css/abstracts/_breakpoints.scss @@ -0,0 +1,62 @@ +/* stylelint-disable block-closing-brace-newline-after */ + +// Breakpoints +// Forked from https://github.com/Automattic/wp-calypso/blob/46ae24d8800fb85da6acf057a640e60dac988a38/assets/stylesheets/shared/mixins/_breakpoints.scss + +// Think very carefully before adding a new breakpoint. +// The list below is based on wp-admin's main breakpoints +// See https://github.com/WordPress/gutenberg/tree/master/packages/viewport#usage +$breakpoints: 480px, 600px, 782px, 960px, 1280px, 1440px; + +// @todo refactor breakpoints so they use the mixins from Gutenberg +// https://github.com/WordPress/gutenberg/blob/master/packages/base-styles/_mixins.scss +@mixin breakpoint($sizes...) { + @each $size in $sizes { + @if type-of($size) == string { + $approved-value: 0; + @each $breakpoint in $breakpoints { + $and-larger: ">" + $breakpoint; + $and-smaller: "<" + $breakpoint; + + @if $size == $and-smaller { + $approved-value: 1; + @media (max-width: $breakpoint) { + @content; + } + } @else { + @if $size == $and-larger { + $approved-value: 2; + @media (min-width: $breakpoint + 1) { + @content; + } + } @else { + @each $breakpoint-end in $breakpoints { + $range: $breakpoint + "-" + $breakpoint-end; + @if $size == $range { + $approved-value: 3; + @media (min-width: $breakpoint + 1) and (max-width: $breakpoint-end) { + @content; + } + } + } + } + } + } + @if $approved-value == 0 { + $sizes: ""; + @each $breakpoint in $breakpoints { + $sizes: $sizes + " " + $breakpoint; + } + @warn "ERROR in breakpoint(#{ $size }) : You can only use these sizes[ #{$sizes} ] using the following syntax [ <#{ nth($breakpoints, 1) } >#{ nth($breakpoints, 1) } #{ nth($breakpoints, 1) }-#{ nth($breakpoints, 2) } ]"; + } + } @else { + $sizes: ""; + @each $breakpoint in $breakpoints { + $sizes: $sizes + " " + $breakpoint; + } + @error "ERROR in breakpoint(#{ $size }) : Please wrap the breakpoint $size in parenthesis. You can use these sizes[ #{$sizes} ] using the following syntax [ <#{ nth($breakpoints, 1) } >#{ nth($breakpoints, 1) } #{ nth($breakpoints, 1) }-#{ nth($breakpoints, 2) } ]"; + } + } +} + +/* stylelint-enable */ diff --git a/plugins/woocommerce-blocks/assets/css/abstracts/_colors.scss b/plugins/woocommerce-blocks/assets/css/abstracts/_colors.scss new file mode 100644 index 00000000000..c11538ed376 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/css/abstracts/_colors.scss @@ -0,0 +1,24 @@ +@import "node_modules/@wordpress/base-styles/colors"; +@import "node_modules/@automattic/color-studio/dist/color-variables"; + +// Bright colors +$discount-color: $alert-green; + +$input-border-gray: #50575e; +$input-border-dark: rgba(255, 255, 255, 0.4); +$controls-border-dark: rgba(255, 255, 255, 0.6); +$input-text-active: #2b2d2f; +$input-placeholder-dark: rgba(255, 255, 255, 0.6); +$input-text-dark: #fff; +$input-background-dark: rgba(0, 0, 0, 0.1); +$select-dropdown-dark: #1e1e1e; +$select-dropdown-light: #fff; +$select-item-dark: rgba(0, 0, 0, 0.4); +$image-placeholder-border-color: #f2f2f2; + +// Universal colors for use on the frontend, currently being applied to checkout blocks. +$universal-border-light: rgba(17, 17, 17, 0.11); // #e7e7e7 on white. Used for low contrast decorative elements such as section borders. +$universal-border-medium: rgba(25, 23, 17, 0.48); // Used for radio and checkbox resting state. +$universal-border-strong: rgba(17, 17, 17, 0.8); // #1e1e1e on white. Used for low contrast decorative elements such as input borders. +$universal-body-low-emphasis: rgba(17, 17, 17, 0.5); // Used for low emphasis text such as input labels. +$universal-background: rgba(17, 17, 17, 0.02); // Used for low contrast decorative elements background color. diff --git a/plugins/woocommerce-blocks/assets/css/abstracts/_mixins.scss b/plugins/woocommerce-blocks/assets/css/abstracts/_mixins.scss new file mode 100644 index 00000000000..7fef7d98f7c --- /dev/null +++ b/plugins/woocommerce-blocks/assets/css/abstracts/_mixins.scss @@ -0,0 +1,311 @@ +$fontSizes: ( + "smaller": 0.75, + "small": 0.875, + "regular": 1, + "large": 1.25, + "larger": 2, +); + +// Maps a named font-size to its predefined size. Units default to em, but can +// be changed using the multiplier parameter. +@mixin font-size($sizeName, $multiplier: 1em) { + font-size: map.get($fontSizes, $sizeName) * $multiplier; +} + +@keyframes spinner__animation { + 0% { + animation-timing-function: cubic-bezier(0.5856, 0.0703, 0.4143, 0.9297); + transform: rotate(0deg); + } + 100% { + transform: rotate(360deg); + } +} + +@keyframes loading__animation { + 100% { + transform: translateX(100%); + } +} + +// Adds animation to placeholder section +@mixin placeholder($include-border-radius: true) { + outline: 0 !important; + border: 0 !important; + background-color: currentColor !important; + color: currentColor !important; + width: 100%; + @if $include-border-radius == true { + border-radius: 0.25rem; + } + display: block; + line-height: 1; + position: relative !important; + overflow: hidden !important; + max-width: 100% !important; + pointer-events: none; + box-shadow: none; + z-index: 1; /* Necessary for overflow: hidden to work correctly in Safari */ + opacity: 0.15; + + // Forces direct descendants to keep layout but lose visibility. + > * { + visibility: hidden; + } + + &::after { + content: " "; + display: block; + position: absolute; + left: 0; + right: 0; + top: 0; + height: 100%; + background-repeat: no-repeat; + background-image: linear-gradient(90deg, currentColor, #f5f5f54d, currentColor); + transform: translateX(-100%); + animation: loading__animation 1.5s ease-in-out infinite; + } + + @media screen and (prefers-reduced-motion: reduce) { + animation: none; + } +} + +@mixin force-content() { + &::before { + content: "\00a0"; + } +} + +// Hide an element from sighted users, but available to screen reader users. +@mixin visually-hidden() { + border: 0; + clip: rect(1px, 1px, 1px, 1px); + clip-path: inset(50%); + height: 1px; + width: 1px; + margin: -1px; + overflow: hidden; + /* Many screen reader and browser combinations announce broken words as they would appear visually. */ + overflow-wrap: normal !important; + word-wrap: normal !important; + padding: 0; + position: absolute !important; +} + +@mixin visually-hidden-focus-reveal() { + background-color: #fff; + border-radius: 3px; + box-shadow: 0 0 2px 2px rgba(0, 0, 0, 0.6); + clip: auto !important; + clip-path: none; + color: $input-text-active; + display: block; + font-size: 0.875rem; + font-weight: 700; + height: auto; + left: 5px; + line-height: normal; + padding: 15px 23px 14px; + text-decoration: none; + top: 5px; + width: auto; + z-index: 100000; +} + +@mixin reset-box() { + border: 0; + border-radius: 0; + margin: 0; + padding: 0; + vertical-align: baseline; +} + +@mixin reset-color() { + color: inherit; +} + +@mixin reset-typography() { + font-family: inherit; + font-size: inherit; + font-style: inherit; + font-weight: inherit; + letter-spacing: inherit; + line-height: inherit; + text-decoration: inherit; + text-transform: inherit; +} + +// Reset

,

, etc. styles as if they were text. Useful for elements that must be headings for a11y but don't need those styles. +@mixin text-heading() { + @include reset-box(); + @include reset-color(); + @include reset-typography(); + box-shadow: none; + display: inline; + + background: transparent; +} + +// Reset + + + + + ); +}; + +export default Edit; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/editor.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/editor.scss new file mode 100644 index 00000000000..230940d5c24 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/editor.scss @@ -0,0 +1,6 @@ +.wc-block-editor-add-to-cart-form-container { + cursor: help; + gap: 10px; + display: flex; + flex-direction: column; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/index.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/index.tsx new file mode 100644 index 00000000000..d2002f337e1 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/index.tsx @@ -0,0 +1,36 @@ +/** + * External dependencies + */ +import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils'; +import { Icon, button } from '@wordpress/icons'; + +/** + * Internal dependencies + */ +import metadata from './block.json'; +import edit from './edit'; +import './style.scss'; +import './editor.scss'; + +const blockSettings = { + edit, + icon: { + src: ( + + ), + }, + ancestor: [ 'woocommerce/single-product' ], + save() { + return null; + }, +}; + +registerBlockSingleProductTemplate( { + blockName: metadata.name, + blockMetadata: metadata, + blockSettings, + isAvailableOnPostEditor: true, +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/style.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/style.scss new file mode 100644 index 00000000000..30284751237 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart-form/style.scss @@ -0,0 +1,25 @@ +.wc-block-add-to-cart-form { + width: unset; + /** + * This is a base style for the input text element in WooCommerce that prevents inputs from appearing too small. + * + * @link https://github.com/woocommerce/woocommerce/blob/95ca53675f2817753d484583c96ca9ab9f725172/plugins/woocommerce/client/legacy/css/woocommerce-blocktheme.scss#L203-L206 + */ + .input-text { + font-size: var(--wp--preset--font-size--small); + padding: 0.9rem 1.1rem; + } + + .quantity { + display: inline-block; + float: none; + margin-right: 4px; + vertical-align: middle; + + .qty { + margin-right: 0.5rem; + width: 3.631em; + text-align: center; + } + } +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/attributes.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/attributes.ts new file mode 100644 index 00000000000..993ebcc8ec6 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/attributes.ts @@ -0,0 +1,12 @@ +export const blockAttributes = { + showFormElements: { + type: 'boolean', + default: false, + }, + productId: { + type: 'number', + default: 0, + }, +}; + +export default blockAttributes; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/block.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/block.tsx new file mode 100644 index 00000000000..19dd85dde07 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/block.tsx @@ -0,0 +1,87 @@ +/** + * External dependencies + */ +import classnames from 'classnames'; +import { + AddToCartFormContextProvider, + useAddToCartFormContext, +} from '@woocommerce/base-context'; +import { useProductDataContext } from '@woocommerce/shared-context'; +import { isEmpty } from '@woocommerce/types'; +import { withProductDataContext } from '@woocommerce/shared-hocs'; + +/** + * Internal dependencies + */ +import './style.scss'; +import { AddToCartButton } from './shared'; +import { + SimpleProductForm, + VariableProductForm, + ExternalProductForm, + GroupedProductForm, +} from './product-types'; + +interface Props { + /** + * CSS Class name for the component. + */ + className?: string; + /** + * Whether or not to show form elements. + */ + showFormElements?: boolean; +} + +/** + * Renders the add to cart form using useAddToCartFormContext. + */ +const AddToCartForm = () => { + const { showFormElements, productType } = useAddToCartFormContext(); + + if ( showFormElements ) { + if ( productType === 'variable' ) { + return ; + } + if ( productType === 'grouped' ) { + return ; + } + if ( productType === 'external' ) { + return ; + } + if ( productType === 'simple' || productType === 'variation' ) { + return ; + } + return null; + } + + return ; +}; + +/** + * Product Add to Form Block Component. + */ +const Block = ( { className, showFormElements }: Props ) => { + const { product } = useProductDataContext(); + const componentClass = classnames( + className, + 'wc-block-components-product-add-to-cart', + { + 'wc-block-components-product-add-to-cart--placeholder': + isEmpty( product ), + } + ); + + return ( + +
+ +
+
+ ); +}; + +export default withProductDataContext( Block ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/constants.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/constants.tsx new file mode 100644 index 00000000000..d37c26dc389 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/constants.tsx @@ -0,0 +1,15 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import { cart } from '@woocommerce/icons'; +import { Icon } from '@wordpress/icons'; + +export const BLOCK_TITLE = __( 'Add to Cart', 'woo-gutenberg-products-block' ); +export const BLOCK_ICON = ( + +); +export const BLOCK_DESCRIPTION = __( + 'Displays an add to cart button. Optionally displays other add to cart form elements.', + 'woo-gutenberg-products-block' +); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/edit.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/edit.tsx new file mode 100644 index 00000000000..fc9e1c98748 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/edit.tsx @@ -0,0 +1,94 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import EditProductLink from '@woocommerce/editor-components/edit-product-link'; +import { useProductDataContext } from '@woocommerce/shared-context'; +import classnames from 'classnames'; +import { + Disabled, + PanelBody, + ToggleControl, + Notice, +} from '@wordpress/components'; +import { InspectorControls } from '@wordpress/block-editor'; +import { productSupportsAddToCartForm } from '@woocommerce/base-utils'; + +/** + * Internal dependencies + */ +import './style.scss'; +import Block from './block'; +import withProductSelector from '../shared/with-product-selector'; +import { BLOCK_TITLE, BLOCK_ICON } from './constants'; + +interface EditProps { + attributes: { + className: string; + showFormElements: boolean; + }; + setAttributes: ( attributes: { showFormElements: boolean } ) => void; +} + +const Edit = ( { attributes, setAttributes }: EditProps ) => { + const { product } = useProductDataContext(); + const { className, showFormElements } = attributes; + + return ( +
+ + + + { productSupportsAddToCartForm( product ) ? ( + + setAttributes( { + showFormElements: ! showFormElements, + } ) + } + /> + ) : ( + + { __( + 'This product does not support the block based add to cart form. A link to the product page will be shown instead.', + 'woo-gutenberg-products-block' + ) } + + ) } + + + + + +
+ ); +}; + +export default withProductSelector( { + icon: BLOCK_ICON, + label: BLOCK_TITLE, + description: __( + 'Choose a product to display its add to cart form.', + 'woo-gutenberg-products-block' + ), +} )( Edit ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/frontend.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/frontend.ts new file mode 100644 index 00000000000..b6c773996b2 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/frontend.ts @@ -0,0 +1,12 @@ +/** + * External dependencies + */ +import { withFilteredAttributes } from '@woocommerce/shared-hocs'; + +/** + * Internal dependencies + */ +import Block from './block'; +import attributes from './attributes'; + +export default withFilteredAttributes( attributes )( Block ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/index.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/index.ts new file mode 100644 index 00000000000..beb3e451bcf --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/index.ts @@ -0,0 +1,29 @@ +/** + * External dependencies + */ +import { registerExperimentalBlockType } from '@woocommerce/block-settings'; + +/** + * Internal dependencies + */ +import sharedConfig from '../shared/config'; +import edit from './edit'; +import attributes from './attributes'; +import { + BLOCK_TITLE as title, + BLOCK_ICON as icon, + BLOCK_DESCRIPTION as description, +} from './constants'; + +const blockConfig = { + title, + description, + icon: { src: icon }, + edit, + attributes, +}; + +registerExperimentalBlockType( 'woocommerce/product-add-to-cart', { + ...sharedConfig, + ...blockConfig, +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/external.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/external.tsx new file mode 100644 index 00000000000..fa2455ecb2a --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/external.tsx @@ -0,0 +1,13 @@ +/** + * Internal dependencies + */ +import AddToCartButton from '../shared/add-to-cart-button'; + +/** + * External Product Add To Cart Form + */ +const External = () => { + return ; +}; + +export default External; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/grouped.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/grouped.tsx new file mode 100644 index 00000000000..1c5dae4c56e --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/grouped.tsx @@ -0,0 +1,8 @@ +/** + * Grouped Product Add To Cart Form + */ +const Grouped = () => ( +

This is a placeholder for the grouped products form element.

+); + +export default Grouped; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/index.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/index.ts new file mode 100644 index 00000000000..9c307daebc3 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/index.ts @@ -0,0 +1,4 @@ +export { default as SimpleProductForm } from './simple'; +export { default as VariableProductForm } from './variable/index'; +export { default as ExternalProductForm } from './external'; +export { default as GroupedProductForm } from './grouped'; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/simple.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/simple.tsx new file mode 100644 index 00000000000..8dc707ef27d --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/simple.tsx @@ -0,0 +1,57 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import { useAddToCartFormContext } from '@woocommerce/base-context'; + +/** + * Internal dependencies + */ +import { AddToCartButton, QuantityInput, ProductUnavailable } from '../shared'; + +/** + * Simple Product Add To Cart Form + */ +const Simple = () => { + // @todo Add types for `useAddToCartFormContext` + const { + product, + quantity, + minQuantity, + maxQuantity, + multipleOf, + dispatchActions, + isDisabled, + } = useAddToCartFormContext(); + + if ( product.id && ! product.is_purchasable ) { + return ; + } + + if ( product.id && ! product.is_in_stock ) { + return ( + + ); + } + + return ( + <> + + + + ); +}; + +export default Simple; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/index.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/index.tsx new file mode 100644 index 00000000000..8aeb00f67ac --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/index.tsx @@ -0,0 +1,66 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import { useAddToCartFormContext } from '@woocommerce/base-context'; + +/** + * Internal dependencies + */ +import { + AddToCartButton, + QuantityInput, + ProductUnavailable, +} from '../../shared'; +import VariationAttributes from './variation-attributes'; + +/** + * Variable Product Add To Cart Form + */ +const Variable = () => { + // @todo Add types for `useAddToCartFormContext` + const { + product, + quantity, + minQuantity, + maxQuantity, + multipleOf, + dispatchActions, + isDisabled, + } = useAddToCartFormContext(); + + if ( product.id && ! product.is_purchasable ) { + return ; + } + + if ( product.id && ! product.is_in_stock ) { + return ( + + ); + } + + return ( + <> + + + + + ); +}; + +export default Variable; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/types.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/types.ts new file mode 100644 index 00000000000..0704b3ca06d --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/types.ts @@ -0,0 +1,17 @@ +/** + * External dependencies + */ +import { Dictionary } from '@woocommerce/types'; + +export type AttributesMap = Record< + string, + { id: number; attributes: Dictionary } +>; + +export interface VariationParam { + id: number; + variation: { + attribute: string; + value: string; + }[]; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/attribute-picker.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/attribute-picker.tsx new file mode 100644 index 00000000000..0a0a48a629e --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/attribute-picker.tsx @@ -0,0 +1,128 @@ +/** + * External dependencies + */ +import { useState, useEffect, useMemo } from '@wordpress/element'; +import { useShallowEqual } from '@woocommerce/base-hooks'; +import type { SelectControl } from '@wordpress/components'; +import { Dictionary, ProductResponseAttributeItem } from '@woocommerce/types'; + +/** + * Internal dependencies + */ +import AttributeSelectControl from './attribute-select-control'; +import { + getVariationMatchingSelectedAttributes, + getActiveSelectControlOptions, + getDefaultAttributes, +} from './utils'; +import { AttributesMap, VariationParam } from '../types'; + +interface Props { + attributes: Record< string, ProductResponseAttributeItem >; + setRequestParams: ( param: VariationParam ) => void; + variationAttributes: AttributesMap; +} + +/** + * AttributePicker component. + */ +const AttributePicker = ( { + attributes, + variationAttributes, + setRequestParams, +}: Props ) => { + const currentAttributes = useShallowEqual( attributes ); + const currentVariationAttributes = useShallowEqual( variationAttributes ); + const [ variationId, setVariationId ] = useState( 0 ); + const [ selectedAttributes, setSelectedAttributes ] = + useState< Dictionary >( {} ); + const [ hasSetDefaults, setHasSetDefaults ] = useState( false ); + + // Get options for each attribute picker. + const filteredAttributeOptions = useMemo( () => { + return getActiveSelectControlOptions( + currentAttributes, + currentVariationAttributes, + selectedAttributes + ); + }, [ selectedAttributes, currentAttributes, currentVariationAttributes ] ); + + // Set default attributes as selected. + useEffect( () => { + if ( ! hasSetDefaults ) { + const defaultAttributes = getDefaultAttributes( attributes ); + if ( defaultAttributes ) { + setSelectedAttributes( { + ...defaultAttributes, + } ); + } + setHasSetDefaults( true ); + } + }, [ selectedAttributes, attributes, hasSetDefaults ] ); + + // Select variations when selections are change. + useEffect( () => { + const hasSelectedAllAttributes = + Object.values( selectedAttributes ).filter( + ( selected ) => selected !== '' + ).length === Object.keys( currentAttributes ).length; + + if ( hasSelectedAllAttributes ) { + setVariationId( + getVariationMatchingSelectedAttributes( + currentAttributes, + currentVariationAttributes, + selectedAttributes + ) + ); + } else if ( variationId > 0 ) { + // Unset variation when form is incomplete. + setVariationId( 0 ); + } + }, [ + selectedAttributes, + variationId, + currentAttributes, + currentVariationAttributes, + ] ); + + // Set requests params as variation ID and data changes. + useEffect( () => { + setRequestParams( { + id: variationId, + variation: Object.keys( selectedAttributes ).map( + ( attributeName ) => { + return { + attribute: attributeName, + value: selectedAttributes[ attributeName ], + }; + } + ), + } ); + }, [ setRequestParams, variationId, selectedAttributes ] ); + + return ( +
+ { Object.keys( currentAttributes ).map( ( attributeName ) => ( + { + setSelectedAttributes( { + ...selectedAttributes, + [ attributeName ]: selected, + } ); + } } + /> + ) ) } +
+ ); +}; + +export default AttributePicker; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/attribute-select-control.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/attribute-select-control.tsx new file mode 100644 index 00000000000..e562ca4bb8a --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/attribute-select-control.tsx @@ -0,0 +1,98 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import { decodeEntities } from '@wordpress/html-entities'; +import { SelectControl } from 'wordpress-components'; +import type { SelectControl as SelectControlType } from '@wordpress/components'; +import { useEffect } from '@wordpress/element'; +import classnames from 'classnames'; +import { ValidationInputError } from '@woocommerce/blocks-components'; +import { VALIDATION_STORE_KEY } from '@woocommerce/block-data'; +import { useDispatch, useSelect } from '@wordpress/data'; + +interface Props extends SelectControlType.Props< string > { + attributeName: string; + errorMessage?: string; +} + +// Default option for select boxes. +const selectAnOption = { + value: '', + label: __( 'Select an option', 'woo-gutenberg-products-block' ), +}; + +/** + * VariationAttributeSelect component. + */ +const AttributeSelectControl = ( { + attributeName, + options = [], + value = '', + onChange = () => void 0, + errorMessage = __( + 'Please select a value.', + 'woo-gutenberg-products-block' + ), +}: Props ) => { + const errorId = attributeName; + + const { setValidationErrors, clearValidationError } = + useDispatch( VALIDATION_STORE_KEY ); + + const { error } = useSelect( ( select ) => { + const store = select( VALIDATION_STORE_KEY ); + return { + error: store.getValidationError( errorId ) || {}, + }; + } ); + + useEffect( () => { + if ( value ) { + clearValidationError( errorId ); + } else { + setValidationErrors( { + [ errorId ]: { + message: errorMessage, + hidden: true, + }, + } ); + } + }, [ + value, + errorId, + errorMessage, + clearValidationError, + setValidationErrors, + ] ); + + // Remove validation errors when unmounted. + useEffect( + () => () => void clearValidationError( errorId ), + [ errorId, clearValidationError ] + ); + + return ( +
+ + +
+ ); +}; + +export default AttributeSelectControl; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/index.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/index.tsx new file mode 100644 index 00000000000..a83497dacc2 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/index.tsx @@ -0,0 +1,40 @@ +/** + * External dependencies + */ +import { ProductResponseItem } from '@woocommerce/types'; + +/** + * Internal dependencies + */ +import './style.scss'; +import AttributePicker from './attribute-picker'; +import { getAttributes, getVariationAttributes } from './utils'; + +interface Props { + dispatchers: { setRequestParams: () => void }; + product: ProductResponseItem; +} + +/** + * VariationAttributes component. + */ +const VariationAttributes = ( { dispatchers, product }: Props ) => { + const attributes = getAttributes( product.attributes ); + const variationAttributes = getVariationAttributes( product.variations ); + if ( + Object.keys( attributes ).length === 0 || + Object.keys( variationAttributes ).length === 0 + ) { + return null; + } + + return ( + + ); +}; + +export default VariationAttributes; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/style.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/style.scss new file mode 100644 index 00000000000..5f58b06699c --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/style.scss @@ -0,0 +1,33 @@ +.wc-block-components-product-add-to-cart-attribute-picker { + margin: 0; + flex-basis: 100%; + + label { + display: block; + @include font-size(regular); + } + + .wc-block-components-product-add-to-cart-attribute-picker__container { + position: relative; + } + + .wc-block-components-product-add-to-cart-attribute-picker__select { + margin: 0 0 em($gap-small) 0; + + select { + min-width: 60%; + min-height: 1.75em; + } + + &.has-error { + margin-bottom: $gap-large; + + select { + border-color: $alert-red; + &:focus { + outline-color: $alert-red; + } + } + } + } +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/test/index.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/test/index.ts new file mode 100644 index 00000000000..d859338da97 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/test/index.ts @@ -0,0 +1,487 @@ +/** + * External dependencies + */ +import { ProductResponseAttributeItem } from '@woocommerce/types'; + +/** + * Internal dependencies + */ +import { + getAttributes, + getVariationAttributes, + getVariationsMatchingSelectedAttributes, + getVariationMatchingSelectedAttributes, + getActiveSelectControlOptions, + getDefaultAttributes, +} from '../utils'; + +const rawAttributeData: ProductResponseAttributeItem[] = [ + { + id: 1, + name: 'Color', + taxonomy: 'pa_color', + has_variations: true, + terms: [ + { + id: 22, + name: 'Blue', + slug: 'blue', + default: true, + }, + { + id: 23, + name: 'Green', + slug: 'green', + default: false, + }, + { + id: 24, + name: 'Red', + slug: 'red', + default: false, + }, + ], + }, + { + id: 0, + name: 'Logo', + taxonomy: 'pa_logo', + has_variations: true, + terms: [ + { + id: 0, + name: 'Yes', + slug: 'Yes', + default: true, + }, + { + id: 0, + name: 'No', + slug: 'No', + default: false, + }, + ], + }, + { + id: 0, + name: 'Non-variable attribute', + taxonomy: 'pa_non-variable-attribute', + has_variations: false, + terms: [ + { + id: 0, + name: 'Test', + slug: 'Test', + default: false, + }, + { + id: 0, + name: 'Test 2', + slug: 'Test 2', + default: false, + }, + ], + }, +]; + +const rawVariations = [ + { + id: 35, + attributes: [ + { + name: 'Color', + value: 'blue', + }, + { + name: 'Logo', + value: 'Yes', + }, + ], + }, + { + id: 28, + attributes: [ + { + name: 'Color', + value: 'red', + }, + { + name: 'Logo', + value: 'No', + }, + ], + }, + { + id: 29, + attributes: [ + { + name: 'Color', + value: 'green', + }, + { + name: 'Logo', + value: 'No', + }, + ], + }, + { + id: 30, + attributes: [ + { + name: 'Color', + value: 'blue', + }, + { + name: 'Logo', + value: 'No', + }, + ], + }, +]; + +const formattedAttributes = { + Color: { + id: 1, + name: 'Color', + taxonomy: 'pa_color', + has_variations: true, + terms: [ + { + id: 22, + name: 'Blue', + slug: 'blue', + default: true, + }, + { + id: 23, + name: 'Green', + slug: 'green', + default: false, + }, + { + id: 24, + name: 'Red', + slug: 'red', + default: false, + }, + ], + }, + Size: { + id: 2, + name: 'Size', + taxonomy: 'pa_size', + has_variations: true, + terms: [ + { + id: 25, + name: 'Large', + slug: 'large', + default: false, + }, + { + id: 26, + name: 'Medium', + slug: 'medium', + default: true, + }, + { + id: 27, + name: 'Small', + slug: 'small', + default: false, + }, + ], + }, +}; + +describe( 'Testing utils', () => { + describe( 'Testing getAttributes()', () => { + it( 'returns empty object if there are no attributes', () => { + const attributes = getAttributes( null ); + expect( attributes ).toStrictEqual( {} ); + } ); + it( 'returns list of attributes when given valid data', () => { + const attributes = getAttributes( rawAttributeData ); + expect( attributes ).toStrictEqual( { + Color: { + id: 1, + name: 'Color', + taxonomy: 'pa_color', + has_variations: true, + terms: [ + { + id: 22, + name: 'Blue', + slug: 'blue', + default: true, + }, + { + id: 23, + name: 'Green', + slug: 'green', + default: false, + }, + { + id: 24, + name: 'Red', + slug: 'red', + default: false, + }, + ], + }, + Logo: { + id: 0, + name: 'Logo', + taxonomy: 'pa_logo', + has_variations: true, + terms: [ + { + id: 0, + name: 'Yes', + slug: 'Yes', + default: true, + }, + { + id: 0, + name: 'No', + slug: 'No', + default: false, + }, + ], + }, + } ); + } ); + } ); + describe( 'Testing getVariationAttributes()', () => { + it( 'returns empty object if there are no variations', () => { + const variationAttributes = getVariationAttributes( null ); + expect( variationAttributes ).toStrictEqual( {} ); + } ); + it( 'returns list of attribute names and value pairs when given valid data', () => { + const variationAttributes = getVariationAttributes( rawVariations ); + expect( variationAttributes ).toStrictEqual( { + 'id:35': { + id: 35, + attributes: { + Color: 'blue', + Logo: 'Yes', + }, + }, + 'id:28': { + id: 28, + attributes: { + Color: 'red', + Logo: 'No', + }, + }, + 'id:29': { + id: 29, + attributes: { + Color: 'green', + Logo: 'No', + }, + }, + 'id:30': { + id: 30, + attributes: { + Color: 'blue', + Logo: 'No', + }, + }, + } ); + } ); + } ); + describe( 'Testing getVariationsMatchingSelectedAttributes()', () => { + const attributes = getAttributes( rawAttributeData ); + const variationAttributes = getVariationAttributes( rawVariations ); + + it( 'returns all variations, in the correct order, if no selections have been made yet', () => { + const selectedAttributes = {}; + const matches = getVariationsMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + expect( matches ).toStrictEqual( [ 35, 28, 29, 30 ] ); + } ); + + it( 'returns correct subset of variations after a selection', () => { + const selectedAttributes = { + Color: 'blue', + }; + const matches = getVariationsMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + expect( matches ).toStrictEqual( [ 35, 30 ] ); + } ); + + it( 'returns correct subset of variations after all selections', () => { + const selectedAttributes = { + Color: 'blue', + Logo: 'No', + }; + const matches = getVariationsMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + expect( matches ).toStrictEqual( [ 30 ] ); + } ); + + it( 'returns no results if selection does not match or is invalid', () => { + const selectedAttributes = { + Color: 'brown', + }; + const matches = getVariationsMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + expect( matches ).toStrictEqual( [] ); + } ); + } ); + describe( 'Testing getVariationMatchingSelectedAttributes()', () => { + const attributes = getAttributes( rawAttributeData ); + const variationAttributes = getVariationAttributes( rawVariations ); + + it( 'returns first match if no selections have been made yet', () => { + const selectedAttributes = {}; + const matches = getVariationMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + expect( matches ).toStrictEqual( 35 ); + } ); + + it( 'returns first match after single selection', () => { + const selectedAttributes = { + Color: 'blue', + }; + const matches = getVariationMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + expect( matches ).toStrictEqual( 35 ); + } ); + + it( 'returns correct match after all selections', () => { + const selectedAttributes = { + Color: 'blue', + Logo: 'No', + }; + const matches = getVariationMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + expect( matches ).toStrictEqual( 30 ); + } ); + + it( 'returns no match if invalid', () => { + const selectedAttributes = { + Color: 'brown', + }; + const matches = getVariationMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + expect( matches ).toStrictEqual( 0 ); + } ); + } ); + describe( 'Testing getActiveSelectControlOptions()', () => { + const attributes = getAttributes( rawAttributeData ); + const variationAttributes = getVariationAttributes( rawVariations ); + + it( 'returns all possible options if no selections have been made yet', () => { + const selectedAttributes = {}; + const controlOptions = getActiveSelectControlOptions( + attributes, + variationAttributes, + selectedAttributes + ); + expect( controlOptions ).toStrictEqual( { + Color: [ + { + value: 'blue', + label: 'Blue', + }, + { + value: 'green', + label: 'Green', + }, + { + value: 'red', + label: 'Red', + }, + ], + Logo: [ + { + value: 'Yes', + label: 'Yes', + }, + { + value: 'No', + label: 'No', + }, + ], + } ); + } ); + + it( 'returns only valid options if color is selected', () => { + const selectedAttributes = { + Color: 'green', + }; + const controlOptions = getActiveSelectControlOptions( + attributes, + variationAttributes, + selectedAttributes + ); + expect( controlOptions ).toStrictEqual( { + Color: [ + { + value: 'blue', + label: 'Blue', + }, + { + value: 'green', + label: 'Green', + }, + { + value: 'red', + label: 'Red', + }, + ], + Logo: [ + { + value: 'No', + label: 'No', + }, + ], + } ); + } ); + } ); + describe( 'Testing getDefaultAttributes()', () => { + const defaultAttributes = getDefaultAttributes( formattedAttributes ); + + it( 'should return default attributes in the format that is ready for setting state', () => { + expect( defaultAttributes ).toStrictEqual( { + Color: 'blue', + Size: 'medium', + } ); + } ); + + it( 'should return an empty object if given unexpected values', () => { + // @ts-expect-error Expected TS Error as we are checking how the function does with *unexpected values*. + expect( getDefaultAttributes( [] ) ).toStrictEqual( {} ); + // @ts-expect-error Ditto above. + expect( getDefaultAttributes( null ) ).toStrictEqual( {} ); + // @ts-expect-error Ditto above. + expect( getDefaultAttributes( undefined ) ).toStrictEqual( {} ); + } ); + } ); +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/utils.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/utils.ts new file mode 100644 index 00000000000..edb77eabb73 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/product-types/variable/variation-attributes/utils.ts @@ -0,0 +1,295 @@ +/** + * External dependencies + */ +import { decodeEntities } from '@wordpress/html-entities'; +import { + Dictionary, + isObject, + ProductResponseAttributeItem, + ProductResponseTermItem, + ProductResponseVariationsItem, +} from '@woocommerce/types'; +import { keyBy } from '@woocommerce/base-utils'; + +/** + * Internal dependencies + */ +import { AttributesMap } from '../types'; + +/** + * Key an array of attributes by name, + */ +export const getAttributes = ( + attributes?: ProductResponseAttributeItem[] | null +) => { + return attributes + ? keyBy( + Object.values( attributes ).filter( + ( { has_variations: hasVariations } ) => hasVariations + ), + 'name' + ) + : {}; +}; + +/** + * Format variations from the API into a map of just the attribute names and values. + * + * Note, each item is keyed by the variation ID with an id: prefix. This is to prevent the object + * being reordered when iterated. + */ +export const getVariationAttributes = ( + /** + * List of Variation objects and attributes keyed by variation ID. + */ + variations?: ProductResponseVariationsItem[] | null +) => { + if ( ! variations ) { + return {}; + } + + const attributesMap: AttributesMap = {}; + + variations.forEach( ( { id, attributes } ) => { + attributesMap[ `id:${ id }` ] = { + id, + attributes: attributes.reduce( ( acc, { name, value } ) => { + acc[ name ] = value; + return acc; + }, {} as Dictionary ), + }; + } ); + + return attributesMap; +}; + +/** + * Given a list of variations and a list of attribute values, return variations which match. + * + * Allows an attribute to be excluded by name. This is used to filter displayed options for + * individual attribute selects. + * + * @return List of matching variation IDs. + */ +export const getVariationsMatchingSelectedAttributes = ( + /** + * List of attribute names and terms. + * + * As returned from {@link getAttributes()}. + */ + attributes: Record< string, ProductResponseAttributeItem >, + /** + * Attributes for each variation keyed by variation ID. + * + * As returned from {@link getVariationAttributes()}. + */ + variationAttributes: AttributesMap, + /** + * Attribute Name Value pairs of current selections by the user. + */ + selectedAttributes: Record< string, string | null > +) => { + const variationIds = Object.values( variationAttributes ).map( + ( { id } ) => id + ); + + // If nothing is selected yet, just return all variations. + if ( + Object.values( selectedAttributes ).every( ( value ) => value === '' ) + ) { + return variationIds; + } + + const attributeNames = Object.keys( attributes ); + + return variationIds.filter( ( variationId ) => + attributeNames.every( ( attributeName ) => { + const selectedAttribute = selectedAttributes[ attributeName ] || ''; + const variationAttribute = + variationAttributes[ 'id:' + variationId ].attributes[ + attributeName + ]; + + // If there is no selected attribute, consider this a match. + if ( selectedAttribute === '' ) { + return true; + } + // If the variation attributes for this attribute are set to null, it matches all values. + if ( variationAttribute === null ) { + return true; + } + // Otherwise, only match if the selected values are the same. + return variationAttribute === selectedAttribute; + } ) + ); +}; + +/** + * Given a list of variations and a list of attribute values, returns the first matched variation ID. + * + * @return Variation ID. + */ +export const getVariationMatchingSelectedAttributes = ( + /** + * List of attribute names and terms. + * + * As returned from {@link getAttributes()}. + */ + attributes: Record< string, ProductResponseAttributeItem >, + /** + * Attributes for each variation keyed by variation ID. + * + * As returned from {@link getVariationAttributes()}. + */ + variationAttributes: AttributesMap, + /** + * Attribute Name Value pairs of current selections by the user. + */ + selectedAttributes: Dictionary +) => { + const matchingVariationIds = getVariationsMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributes + ); + return matchingVariationIds[ 0 ] || 0; +}; + +/** + * Given a list of terms, filter them and return valid options for the select boxes. + * + * @see getActiveSelectControlOptions + * + * @return Value/Label pairs of select box options. + */ +const getValidSelectControlOptions = ( + /** + * List of attribute term objects. + */ + attributeTerms: ProductResponseTermItem[], + /** + * Valid values if selections have been made already. + */ + validAttributeTerms: Array< string | null > | null = null +) => { + return Object.values( attributeTerms ) + .map( ( { name, slug } ) => { + if ( + validAttributeTerms === null || + validAttributeTerms.includes( null ) || + validAttributeTerms.includes( slug ) + ) { + return { + value: slug, + label: decodeEntities( name ), + }; + } + return null; + } ) + .filter( Boolean ); +}; + +/** + * Given a list of terms, filter them and return active options for the select boxes. This factors in + * which options should be hidden due to current selections. + * + * @return Select box options. + */ +export const getActiveSelectControlOptions = ( + /** + * List of attribute names and terms. + * + * As returned from {@link getAttributes()}. + */ + attributes: Record< string, ProductResponseAttributeItem >, + /** + * Attributes for each variation keyed by variation ID. + * + * As returned from {@link getVariationAttributes()}. + */ + variationAttributes: AttributesMap, + /** + * Attribute Name Value pairs of current selections by the user. + */ + selectedAttributes: Dictionary +) => { + const options: Record< + string, + Array< { label: string; value: string } | null > + > = {}; + const attributeNames = Object.keys( attributes ); + const hasSelectedAttributes = + Object.values( selectedAttributes ).filter( Boolean ).length > 0; + + attributeNames.forEach( ( attributeName ) => { + const currentAttribute = attributes[ attributeName ]; + const selectedAttributesExcludingCurrentAttribute = { + ...selectedAttributes, + [ attributeName ]: null, + }; + // This finds matching variations for selected attributes apart from this one. This will be + // used to get valid attribute terms of the current attribute narrowed down by those matching + // variation IDs. For example, if I had Large Blue Shirts and Medium Red Shirts, I want to only + // show Red shirts if Medium is selected. + const matchingVariationIds = hasSelectedAttributes + ? getVariationsMatchingSelectedAttributes( + attributes, + variationAttributes, + selectedAttributesExcludingCurrentAttribute + ) + : null; + // Uses the above matching variation IDs to get the attributes from just those variations. + const validAttributeTerms = + matchingVariationIds !== null + ? matchingVariationIds.map( + ( varId ) => + variationAttributes[ 'id:' + varId ].attributes[ + attributeName + ] + ) + : null; + // Intersects attributes with valid attributes. + options[ attributeName ] = getValidSelectControlOptions( + currentAttribute.terms, + validAttributeTerms + ); + } ); + + return options; +}; + +/** + * Return the default values of the given attributes in a format ready to be set in state. + * + * @return Default attributes. + */ +export const getDefaultAttributes = ( + /** + * List of attribute names and terms. + * + * As returned from {@link getAttributes()}. + */ + attributes: Record< string, ProductResponseAttributeItem > +) => { + if ( ! isObject( attributes ) ) { + return {}; + } + + const attributeNames = Object.keys( attributes ); + + if ( attributeNames.length === 0 ) { + return {}; + } + + const attributesEntries = Object.values( attributes ); + + return attributesEntries.reduce( ( acc, curr ) => { + const defaultValues = curr.terms.filter( ( term ) => term.default ); + + if ( defaultValues.length > 0 ) { + acc[ curr.name ] = defaultValues[ 0 ]?.slug; + } + + return acc; + }, {} as Dictionary ); +}; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/add-to-cart-button.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/add-to-cart-button.tsx new file mode 100644 index 00000000000..d36e7da5f2d --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/add-to-cart-button.tsx @@ -0,0 +1,181 @@ +/** + * External dependencies + */ +import { __, _n, sprintf } from '@wordpress/i18n'; +import Button, { ButtonProps } from '@woocommerce/base-components/button'; +import { Icon, check } from '@wordpress/icons'; +import { useState, useEffect } from '@wordpress/element'; +import { useAddToCartFormContext } from '@woocommerce/base-context'; +import { + useStoreEvents, + useStoreAddToCart, +} from '@woocommerce/base-context/hooks'; +import { useInnerBlockLayoutContext } from '@woocommerce/shared-context'; + +type LinkProps = Pick< ButtonProps, 'className' | 'href' | 'onClick' | 'text' >; + +interface ButtonComponentProps + extends Pick< ButtonProps, 'className' | 'onClick' > { + /** + * Whether the button is disabled or not. + */ + isDisabled: boolean; + /** + * Whether processing is done. + */ + isDone: boolean; + /** + * Whether processing action is occurring. + */ + isProcessing: ButtonProps[ 'showSpinner' ]; + /** + * Quantity of said item currently in the cart. + */ + quantityInCart: number; +} + +/** + * Button component for non-purchasable products. + */ +const LinkComponent = ( { className, href, text, onClick }: LinkProps ) => { + return ( + + ); +}; + +/** + * Button for purchasable products. + */ +const ButtonComponent = ( { + className, + quantityInCart, + isProcessing, + isDisabled, + isDone, + onClick, +}: ButtonComponentProps ) => { + return ( + + ); +}; + +/** + * Add to Cart Form Button Component. + */ +const AddToCartButton = () => { + // @todo Add types for `useAddToCartFormContext` + const { + showFormElements, + productIsPurchasable, + productHasOptions, + product, + productType, + isDisabled, + isProcessing, + eventRegistration, + hasError, + dispatchActions, + } = useAddToCartFormContext(); + const { parentName } = useInnerBlockLayoutContext(); + const { dispatchStoreEvent } = useStoreEvents(); + const { cartQuantity } = useStoreAddToCart( product.id || 0 ); + const [ addedToCart, setAddedToCart ] = useState( false ); + const addToCartButtonData = product.add_to_cart || { + url: '', + text: '', + }; + + // Subscribe to emitter for after processing. + useEffect( () => { + const onSuccess = () => { + if ( ! hasError ) { + setAddedToCart( true ); + } + return true; + }; + const unsubscribeProcessing = + eventRegistration.onAddToCartAfterProcessingWithSuccess( + onSuccess, + 0 + ); + return () => { + unsubscribeProcessing(); + }; + }, [ eventRegistration, hasError ] ); + + /** + * We can show a real button if we are: + * + * a) Showing a full add to cart form. + * b) The product doesn't have options and can therefore be added directly to the cart. + * c) The product is purchasable. + * + * Otherwise we show a link instead. + */ + const showButton = + ( showFormElements || + ( ! productHasOptions && productType === 'simple' ) ) && + productIsPurchasable; + + return showButton ? ( + { + dispatchActions.submitForm( + `woocommerce/single-product/${ product?.id || 0 }` + ); + dispatchStoreEvent( 'cart-add-item', { + product, + listName: parentName, + } ); + } } + /> + ) : ( + { + dispatchStoreEvent( 'product-view-link', { + product, + listName: parentName, + } ); + } } + /> + ); +}; + +export default AddToCartButton; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/index.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/index.ts new file mode 100644 index 00000000000..9fe6eed8226 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/index.ts @@ -0,0 +1,3 @@ +export { default as AddToCartButton } from './add-to-cart-button'; +export { default as QuantityInput } from './quantity-input'; +export { default as ProductUnavailable } from './product-unavailable'; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/product-unavailable.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/product-unavailable.tsx new file mode 100644 index 00000000000..77644f5bcf6 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/product-unavailable.tsx @@ -0,0 +1,19 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; + +const ProductUnavailable = ( { + reason = __( + 'Sorry, this product cannot be purchased.', + 'woo-gutenberg-products-block' + ), +} ) => { + return ( +
+ { reason } +
+ ); +}; + +export default ProductUnavailable; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/quantity-input.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/quantity-input.tsx new file mode 100644 index 00000000000..a9c1e257ec4 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/shared/quantity-input.tsx @@ -0,0 +1,85 @@ +/** + * External dependencies + */ +import { useDebouncedCallback } from 'use-debounce'; + +type JSXInputProps = JSX.IntrinsicElements[ 'input' ]; + +interface QuantityInputProps extends Omit< JSXInputProps, 'onChange' > { + max: number; + min: number; + onChange: ( val: number | string ) => void; + step: number; +} + +/** + * Quantity Input Component. + */ +const QuantityInput = ( { + disabled, + min, + max, + step = 1, + value, + onChange, +}: QuantityInputProps ) => { + const hasMaximum = typeof max !== 'undefined'; + + /** + * The goal of this function is to normalize what was inserted, + * but after the customer has stopped typing. + * + * It's important to wait before normalizing or we end up with + * a frustrating experience, for example, if the minimum is 2 and + * the customer is trying to type "10", premature normalizing would + * always kick in at "1" and turn that into 2. + * + * Copied from + */ + const normalizeQuantity = useDebouncedCallback< ( val: number ) => void >( + ( initialValue ) => { + // We copy the starting value. + let newValue = initialValue; + + // We check if we have a maximum value, and select the lowest between what was inserted and the maximum. + if ( hasMaximum ) { + newValue = Math.min( + newValue, + // the maximum possible value in step increments. + Math.floor( max / step ) * step + ); + } + + // Select the biggest between what's inserted, the the minimum value in steps. + newValue = Math.max( newValue, Math.ceil( min / step ) * step ); + + // We round off the value to our steps. + newValue = Math.floor( newValue / step ) * step; + + // Only commit if the value has changed + if ( newValue !== initialValue ) { + onChange?.( newValue ); + } + }, + 300 + ); + + return ( + { + onChange?.( e.target.value ); + normalizeQuantity( Number( e.target.value ) ); + } } + /> + ); +}; + +export default QuantityInput; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/style.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/style.scss new file mode 100644 index 00000000000..686d216aff6 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/add-to-cart/style.scss @@ -0,0 +1,49 @@ +.wc-block-components-product-add-to-cart { + margin: 0; + display: flex; + flex-wrap: wrap; + + .wc-block-components-product-add-to-cart-button { + margin: 0 0 em($gap-small) 0; + + .wc-block-components-button__text { + display: block; + + > svg { + fill: currentColor; + vertical-align: top; + width: 1.5em; + height: 1.5em; + margin: -0.25em 0 -0.25em 0.5em; + } + } + } + + .wc-block-components-product-add-to-cart-quantity { + margin: 0 1em em($gap-small) 0; + flex-basis: 5em; + padding: 0.618em; + background: $white; + border: 1px solid #ccc; + border-radius: $universal-border-radius; + color: #43454b; + box-shadow: inset 0 1px 1px rgba(0, 0, 0, 0.125); + text-align: center; + } +} + +.is-loading .wc-block-components-product-add-to-cart, +.wc-block-components-product-add-to-cart--placeholder { + .wc-block-components-product-add-to-cart-quantity, + .wc-block-components-product-add-to-cart-button { + @include placeholder(); + } +} + +.wc-block-grid .wc-block-components-product-add-to-cart { + justify-content: center; +} + +.wc-block-components-product-add-to-cart-notice { + margin: 0; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/block.json b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/block.json new file mode 100644 index 00000000000..7572d5dfd93 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/block.json @@ -0,0 +1,17 @@ +{ + "name": "woocommerce/product-average-rating", + "version": "1.0.0", + "title": "Product Average Rating (Beta)", + "description": "Display the average rating of a product", + "attributes": { + "textAlign": { + "type": "string" + } + }, + "category": "woocommerce", + "keywords": [ "WooCommerce" ], + "ancestor": [ "woocommerce/single-product" ], + "textdomain": "woo-gutenberg-products-block", + "apiVersion": 2, + "$schema": "https://schemas.wp.org/trunk/block.json" +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/block.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/block.tsx new file mode 100644 index 00000000000..796b55f7d2a --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/block.tsx @@ -0,0 +1,37 @@ +/** + * External dependencies + */ +import classnames from 'classnames'; +import { useProductDataContext } from '@woocommerce/shared-context'; +import { useStyleProps } from '@woocommerce/base-hooks'; +import { __ } from '@wordpress/i18n'; +import { withProductDataContext } from '@woocommerce/shared-hocs'; + +type ProductAverageRatingProps = { + className?: string; + textAlign?: string; +}; + +export const Block = ( props: ProductAverageRatingProps ): JSX.Element => { + const { textAlign } = props; + const styleProps = useStyleProps( props ); + const { product } = useProductDataContext(); + + const className = classnames( + styleProps.className, + 'wc-block-components-product-average-rating', + { + [ `has-text-align-${ textAlign }` ]: textAlign, + } + ); + + return ( +
+ { Number( product.average_rating ) > 0 + ? product.average_rating + : __( 'No ratings', 'woo-gutenberg-products-block' ) } +
+ ); +}; + +export default withProductDataContext( Block ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/edit.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/edit.tsx new file mode 100644 index 00000000000..c5a311e0887 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/edit.tsx @@ -0,0 +1,43 @@ +/** + * External dependencies + */ +import { + AlignmentToolbar, + BlockControls, + useBlockProps, +} from '@wordpress/block-editor'; +import type { BlockEditProps } from '@wordpress/blocks'; + +/** + * Internal dependencies + */ +import Block from './block'; + +export interface BlockAttributes { + textAlign: string; +} + +const Edit = ( props: BlockEditProps< BlockAttributes > ): JSX.Element => { + const { attributes, setAttributes } = props; + const blockProps = useBlockProps( { + className: 'wp-block-woocommerce-product-average-rating', + } ); + + return ( + <> + + { + setAttributes( { textAlign: newAlign || '' } ); + } } + /> + +
+ +
+ + ); +}; + +export default Edit; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/index.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/index.tsx new file mode 100644 index 00000000000..6933405fd81 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/index.tsx @@ -0,0 +1,25 @@ +/** + * External dependencies + */ +import { registerBlockType } from '@wordpress/blocks'; +import { Icon, starHalf } from '@wordpress/icons'; + +/** + * Internal dependencies + */ +import metadata from './block.json'; +import edit from './edit'; +import { supports } from './support'; + +registerBlockType( metadata, { + icon: { + src: ( + + ), + }, + supports, + edit, +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/support.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/support.ts new file mode 100644 index 00000000000..d8724d99bac --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/average-rating/support.ts @@ -0,0 +1,26 @@ +/* eslint-disable @wordpress/no-unsafe-wp-apis */ +/** + * External dependencies + */ +import { isFeaturePluginBuild } from '@woocommerce/block-settings'; + +export const supports = { + ...( isFeaturePluginBuild() && { + color: { + text: true, + background: true, + __experimentalSkipSerialization: true, + }, + spacing: { + margin: true, + padding: true, + __experimentalSkipSerialization: true, + }, + typography: { + fontSize: true, + __experimentalFontWeight: true, + __experimentalSkipSerialization: true, + }, + __experimentalSelector: '.wc-block-components-product-average-rating', + } ), +}; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/block.json b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/block.json new file mode 100644 index 00000000000..c69913bdee2 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/block.json @@ -0,0 +1,66 @@ +{ + "name": "woocommerce/product-button", + "version": "1.0.0", + "title": "Add to Cart Button", + "description": "Display a call to action button which either adds the product to the cart, or links to the product page.", + "category": "woocommerce", + "keywords": [ "WooCommerce" ], + "usesContext": [ "query", "queryId", "postId" ], + "textdomain": "woo-gutenberg-products-block", + "attributes": { + "productId": { + "type": "number", + "default": 0 + }, + "textAlign": { + "type": "string", + "default": "" + }, + "width": { + "type": "number" + }, + "isDescendentOfSingleProductBlock": { + "type": "boolean", + "default": false + }, + "isDescendentOfQueryLoop": { + "type": "boolean", + "default": false + } + }, + "supports": { + "align": [ "wide", "full" ], + "color": { + "background": false, + "link": true + }, + "interactivity": true, + "html": false, + "typography": { + "fontSize": true, + "lineHeight": true + } + }, + "ancestor": [ + "woocommerce/all-products", + "woocommerce/single-product", + "core/post-template", + "woocommerce/product-template" + ], + "styles": [ + { + "name": "fill", + "label": "Fill", + "isDefault": true + }, + { + "name": "outline", + "label": "Outline" + } + ], + "viewScript": [ + "wc-product-button-interactivity-frontend" + ], + "apiVersion": 2, + "$schema": "https://schemas.wp.org/trunk/block.json" +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/block.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/block.tsx new file mode 100644 index 00000000000..2199c1e3613 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/block.tsx @@ -0,0 +1,172 @@ +/** + * External dependencies + */ +import classnames from 'classnames'; +import { __, _n, sprintf } from '@wordpress/i18n'; +import { + useStoreEvents, + useStoreAddToCart, +} from '@woocommerce/base-context/hooks'; +import { useStyleProps } from '@woocommerce/base-hooks'; +import { decodeEntities } from '@wordpress/html-entities'; +import { CART_URL } from '@woocommerce/block-settings'; +import { getSetting } from '@woocommerce/settings'; +import { + useInnerBlockLayoutContext, + useProductDataContext, +} from '@woocommerce/shared-context'; +import { withProductDataContext } from '@woocommerce/shared-hocs'; + +/** + * Internal dependencies + */ +import './style.scss'; +import type { + BlockAttributes, + AddToCartButtonAttributes, + AddToCartButtonPlaceholderAttributes, +} from './types'; + +const AddToCartButton = ( { + product, + className, + style, +}: AddToCartButtonAttributes ): JSX.Element => { + const { + id, + permalink, + add_to_cart: productCartDetails, + has_options: hasOptions, + is_purchasable: isPurchasable, + is_in_stock: isInStock, + } = product; + const { dispatchStoreEvent } = useStoreEvents(); + const { cartQuantity, addingToCart, addToCart } = useStoreAddToCart( id ); + + const addedToCart = Number.isFinite( cartQuantity ) && cartQuantity > 0; + const allowAddToCart = ! hasOptions && isPurchasable && isInStock; + const buttonAriaLabel = decodeEntities( + productCartDetails?.description || '' + ); + const buttonText = addedToCart + ? sprintf( + /* translators: %s number of products in cart. */ + _n( + '%d in cart', + '%d in cart', + cartQuantity, + 'woo-gutenberg-products-block' + ), + cartQuantity + ) + : decodeEntities( + productCartDetails?.text || + __( 'Add to cart', 'woo-gutenberg-products-block' ) + ); + + const ButtonTag = allowAddToCart ? 'button' : 'a'; + const buttonProps = {} as HTMLAnchorElement & { onClick: () => void }; + + if ( ! allowAddToCart ) { + buttonProps.href = permalink; + buttonProps.rel = 'nofollow'; + buttonProps.onClick = () => { + dispatchStoreEvent( 'product-view-link', { + product, + } ); + }; + } else { + buttonProps.onClick = async () => { + await addToCart(); + dispatchStoreEvent( 'cart-add-item', { + product, + } ); + // redirect to cart if the setting to redirect to the cart page + // on cart add item is enabled + const { cartRedirectAfterAdd }: { cartRedirectAfterAdd: boolean } = + getSetting( 'productsSettings' ); + if ( cartRedirectAfterAdd ) { + window.location.href = CART_URL; + } + }; + } + + return ( + + { buttonText } + + ); +}; + +const AddToCartButtonPlaceholder = ( { + className, + style, +}: AddToCartButtonPlaceholderAttributes ): JSX.Element => { + return ( + + ); + } ) } + + + ); +} + +const Edit = ( { + attributes, + setAttributes, + context, +}: BlockEditProps< BlockAttributes > & { + context?: Context | undefined; +} ): JSX.Element => { + const blockProps = useBlockProps(); + const isDescendentOfQueryLoop = Number.isFinite( context?.queryId ); + const { width } = attributes; + + useEffect( + () => setAttributes( { isDescendentOfQueryLoop } ), + [ setAttributes, isDescendentOfQueryLoop ] + ); + return ( + <> + + { isDescendentOfQueryLoop && ( + { + setAttributes( { textAlign: newAlign || '' } ); + } } + /> + ) } + + + + +
+ + + +
+ + ); +}; + +export default Edit; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/frontend.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/frontend.tsx new file mode 100644 index 00000000000..3086aee599e --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/frontend.tsx @@ -0,0 +1,241 @@ +/** + * External dependencies + */ +import { store, getContext as getContextFn } from '@woocommerce/interactivity'; +import { select, subscribe, dispatch } from '@wordpress/data'; +import { CART_STORE_KEY as storeKey } from '@woocommerce/block-data'; +import { Cart } from '@woocommerce/type-defs/cart'; +import { createRoot } from '@wordpress/element'; +import NoticeBanner from '@woocommerce/base-components/notice-banner'; + +interface Context { + isLoading: boolean; + addToCartText: string; + productId: number; + displayViewCart: boolean; + quantityToAdd: number; + temporaryNumberOfItems: number; + animationStatus: AnimationStatus; +} + +enum AnimationStatus { + IDLE = 'IDLE', + SLIDE_OUT = 'SLIDE-OUT', + SLIDE_IN = 'SLIDE-IN', +} + +interface Store { + state: { + cart?: Cart; + inTheCartText?: string; + numberOfItemsInTheCart: number; + hasCartLoaded: boolean; + slideInAnimation: boolean; + slideOutAnimation: boolean; + addToCartText: string; + displayViewCart: boolean; + }; + actions: { + addToCart: () => void; + handleAnimationEnd: ( event: AnimationEvent ) => void; + }; + callbacks: { + startAnimation: () => void; + syncTemporaryNumberOfItemsOnLoad: () => void; + }; +} + +const storeNoticeClass = '.wc-block-store-notices'; + +const createNoticeContainer = () => { + const noticeContainer = document.createElement( 'div' ); + noticeContainer.classList.add( storeNoticeClass.replace( '.', '' ) ); + return noticeContainer; +}; + +const injectNotice = ( domNode: Element, errorMessage: string ) => { + const root = createRoot( domNode ); + + root.render( + root.unmount() }> + { errorMessage } + + ); + + domNode?.scrollIntoView( { + behavior: 'smooth', + inline: 'nearest', + } ); +}; + +const getProductById = ( cartState: Cart | undefined, productId: number ) => { + return cartState?.items.find( ( item ) => item.id === productId ); +}; + +const getButtonText = ( + addToCart: string, + inTheCart: string, + numberOfItems: number +): string => { + if ( numberOfItems === 0 ) return addToCart; + return inTheCart.replace( '###', numberOfItems.toString() ); +}; + +// The `getContextFn` function is wrapped just to avoid prettier issues. +const getContext = ( ns?: string ) => getContextFn< Context >( ns ); + +const { state } = store< Store >( 'woocommerce/product-button', { + state: { + get slideInAnimation() { + const { animationStatus } = getContext(); + return animationStatus === AnimationStatus.SLIDE_IN; + }, + get slideOutAnimation() { + const { animationStatus } = getContext(); + return animationStatus === AnimationStatus.SLIDE_OUT; + }, + get numberOfItemsInTheCart() { + const { productId } = getContext(); + const product = getProductById( state.cart, productId ); + return product?.quantity || 0; + }, + get hasCartLoaded(): boolean { + return !! state.cart; + }, + get addToCartText(): string { + const context = getContext(); + // We use the temporary number of items when there's no animation, or the + // second part of the animation hasn't started. + if ( + context.animationStatus === AnimationStatus.IDLE || + context.animationStatus === AnimationStatus.SLIDE_OUT + ) { + return getButtonText( + context.addToCartText, + state.inTheCartText!, + context.temporaryNumberOfItems + ); + } + return getButtonText( + context.addToCartText, + state.inTheCartText!, + state.numberOfItemsInTheCart + ); + }, + get displayViewCart(): boolean { + const { displayViewCart, temporaryNumberOfItems } = getContext(); + if ( ! displayViewCart ) return false; + if ( ! state.hasCartLoaded ) { + return temporaryNumberOfItems > 0; + } + return state.numberOfItemsInTheCart > 0; + }, + }, + actions: { + *addToCart() { + const context = getContext(); + const { productId, quantityToAdd } = context; + + context.isLoading = true; + + try { + yield dispatch( storeKey ).addItemToCart( + productId, + quantityToAdd + ); + + // After the cart is updated, sync the temporary number of items again. + context.temporaryNumberOfItems = state.numberOfItemsInTheCart; + } catch ( error ) { + const storeNoticeBlock = + document.querySelector( storeNoticeClass ); + + if ( ! storeNoticeBlock ) { + document + .querySelector( '.entry-content' ) + ?.prepend( createNoticeContainer() ); + } + + const domNode = + storeNoticeBlock ?? + document.querySelector( storeNoticeClass ); + + if ( domNode ) { + injectNotice( domNode, ( error as Error ).message ); + } + + // We don't care about errors blocking execution, but will + // console.error for troubleshooting. + // eslint-disable-next-line no-console + console.error( error ); + } finally { + context.displayViewCart = true; + context.isLoading = false; + } + }, + handleAnimationEnd: ( event: AnimationEvent ) => { + const context = getContext(); + if ( event.animationName === 'slideOut' ) { + // When the first part of the animation (slide-out) ends, we move + // to the second part (slide-in). + context.animationStatus = AnimationStatus.SLIDE_IN; + } else if ( event.animationName === 'slideIn' ) { + // When the second part of the animation ends, we update the + // temporary number of items to sync it with the cart and reset the + // animation status so it can be triggered again. + context.temporaryNumberOfItems = state.numberOfItemsInTheCart; + context.animationStatus = AnimationStatus.IDLE; + } + }, + }, + callbacks: { + syncTemporaryNumberOfItemsOnLoad: () => { + const context = getContext(); + // If the cart has loaded when we instantiate this element, we sync + // the temporary number of items with the number of items in the cart + // to avoid triggering the animation. We do this only once, but we + // use useLayoutEffect to avoid the useEffect flickering. + if ( state.hasCartLoaded ) { + context.temporaryNumberOfItems = state.numberOfItemsInTheCart; + } + }, + startAnimation: () => { + const context = getContext(); + // We start the animation if the cart has loaded, the temporary number + // of items is out of sync with the number of items in the cart, the + // button is not loading (because that means the user started the + // interaction) and the animation hasn't started yet. + if ( + state.hasCartLoaded && + context.temporaryNumberOfItems !== + state.numberOfItemsInTheCart && + ! context.isLoading && + context.animationStatus === AnimationStatus.IDLE + ) { + context.animationStatus = AnimationStatus.SLIDE_OUT; + } + }, + }, +} ); + +// Subscribe to changes in Cart data. +subscribe( () => { + const cartData = select( storeKey ).getCartData(); + const isResolutionFinished = + select( storeKey ).hasFinishedResolution( 'getCartData' ); + if ( isResolutionFinished ) { + state.cart = cartData; + } +}, storeKey ); + +// RequestIdleCallback is not available in Safari, so we use setTimeout as an alternative. +const callIdleCallback = + window.requestIdleCallback || ( ( cb ) => setTimeout( cb, 100 ) ); + +// This selector triggers a fetch of the Cart data. It is done in a +// `requestIdleCallback` to avoid potential performance issues. +callIdleCallback( () => { + if ( ! state.hasCartLoaded ) { + select( storeKey ).getCartData(); + } +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/index.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/index.tsx new file mode 100644 index 00000000000..60121d4f64f --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/index.tsx @@ -0,0 +1,76 @@ +/** + * External dependencies + */ +import { Icon, button } from '@wordpress/icons'; +import { registerBlockType } from '@wordpress/blocks'; +import { isFeaturePluginBuild } from '@woocommerce/block-settings'; +import { __experimentalGetSpacingClassesAndStyles } from '@wordpress/block-editor'; +/** + * Internal dependencies + */ +import edit from './edit'; +import save from './save'; +import metadata from './block.json'; + +const featurePluginSupport = { + ...metadata.supports, + ...( isFeaturePluginBuild() && { + color: { + text: true, + background: true, + link: false, + __experimentalSkipSerialization: true, + }, + __experimentalBorder: { + radius: true, + __experimentalSkipSerialization: true, + }, + ...( typeof __experimentalGetSpacingClassesAndStyles === 'function' && { + spacing: { + margin: true, + padding: true, + __experimentalSkipSerialization: true, + }, + } ), + typography: { + fontSize: true, + lineHeight: true, + __experimentalFontWeight: true, + __experimentalFontFamily: true, + __experimentalFontStyle: true, + __experimentalTextTransform: true, + __experimentalTextDecoration: true, + __experimentalLetterSpacing: true, + __experimentalDefaultControls: { + fontSize: true, + }, + }, + __experimentalSelector: + '.wp-block-button.wc-block-components-product-button .wc-block-components-product-button__button', + } ), + ...( typeof __experimentalGetSpacingClassesAndStyles === 'function' && + ! isFeaturePluginBuild() && { + spacing: { + margin: true, + }, + } ), +}; +// @ts-expect-error: `metadata` currently does not have a type definition in WordPress core +registerBlockType( metadata, { + icon: { + src: ( + + ), + }, + attributes: { + ...metadata.attributes, + }, + supports: { + ...featurePluginSupport, + }, + edit, + save, +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/save.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/save.tsx new file mode 100644 index 00000000000..267b49937e5 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/save.tsx @@ -0,0 +1,36 @@ +/** + * External dependencies + */ +import { useBlockProps } from '@wordpress/block-editor'; +import classnames from 'classnames'; + +/** + * Internal dependencies + */ +import { BlockAttributes } from './types'; + +type Props = { + attributes: BlockAttributes; +}; + +const Save = ( { attributes }: Props ): JSX.Element | null => { + if ( + attributes.isDescendentOfQueryLoop || + attributes.isDescendentOfSingleProductBlock + ) { + return null; + } + + return ( +
+ ); +}; + +export default Save; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/style.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/style.scss new file mode 100644 index 00000000000..d9d636056e5 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/style.scss @@ -0,0 +1,145 @@ +.wp-block-button.wc-block-components-product-button { + word-break: break-word; + white-space: normal; + display: flex; + justify-content: center; + flex-direction: column; + align-items: center; + gap: $gap-small; + + .wp-block-button__link { + word-break: break-word; + white-space: normal; + display: inline-flex; + justify-content: center; + text-align: center; + // Set button font size so it inherits from parent. + font-size: 1em; + + &.loading { + opacity: 0.25; + } + + &.loading::after { + font-family: WooCommerce; /* stylelint-disable-line */ + content: "\e031"; + animation: spin 2s linear infinite; + margin-right: 0; + margin-left: 0.5em; + display: inline-block; + width: auto; + height: auto; + } + } + + a[hidden] { + display: none; + } + + @keyframes slideOut { + from { + transform: translateY(0); + } + to { + transform: translateY(-100%); + } + } + + @keyframes slideIn { + from { + transform: translateY(90%); + opacity: 0; + } + to { + transform: translate(0); + opacity: 1; + } + } + + &.align-left { + align-items: flex-start; + } + + &.align-right { + align-items: flex-end; + } + + .wc-block-components-product-button__button { + border-style: none; + display: inline-flex; + justify-content: center; + white-space: normal; + word-break: break-word; + overflow: hidden; + align-items: center; + line-height: inherit; + + span { + + &.wc-block-slide-out { + animation: slideOut 0.1s linear 1 normal forwards; + } + &.wc-block-slide-in { + animation: slideIn 0.1s linear 1 normal; + } + } + } + + .wc-block-components-product-button__button--placeholder { + @include placeholder(); + min-width: 8em; + min-height: 3em; + } + + .wc-block-all-products & { + margin-bottom: $gap-small; + } +} + +.is-loading .wc-block-components-product-button > .wc-block-components-product-button__button { + @include placeholder(); + min-width: 8em; + min-height: 3em; +} + +.theme-twentytwentyone { + // Prevent buttons appearing disabled in the editor. + .editor-styles-wrapper .wc-block-components-product-button .wp-block-button__link { + background-color: var(--button--color-background); + color: var(--button--color-text); + border-color: var(--button--color-background); + } +} + +// Style: Fill & Outline +.wp-block-button.is-style-outline { + .wp-block-button__link { + border: 2px solid currentColor; + + &:not(.has-text-color) { + color: currentColor; + } + + &:not(.has-background) { + background-color: transparent; + background-image: none; + } + } +} + +// Width setting +.wp-block-button { + &.has-custom-width { + .wp-block-button__link { + box-sizing: border-box; + } + } + + @for $i from 1 through 4 { + &.wp-block-button__width-#{$i * 25} { + .wp-block-button__link { + width: $i * 25%; // 25%, 50%, 75%, 100% + } + } + } +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/types.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/types.ts new file mode 100644 index 00000000000..6f429e53cce --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/button/types.ts @@ -0,0 +1,37 @@ +interface WithClass { + className: string; +} + +interface WithStyle { + style: Record< string, unknown >; +} + +export interface BlockAttributes { + className?: string | undefined; + textAlign?: string | undefined; + isDescendentOfQueryLoop?: boolean | undefined; + isDescendentOfSingleProductBlock?: boolean | undefined; + width?: number | undefined; +} + +export interface AddToCartButtonPlaceholderAttributes { + className: string; + style: React.CSSProperties; +} + +export interface AddToCartButtonAttributes + extends AddToCartButtonPlaceholderAttributes { + product: { + id: number; + permalink: string; + add_to_cart: { + url: string; + description: string; + text: string; + }; + has_options: boolean; + is_purchasable: boolean; + is_in_stock: boolean; + }; + textAlign?: ( WithClass & WithStyle ) | undefined; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/attributes.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/attributes.ts new file mode 100644 index 00000000000..2405642245e --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/attributes.ts @@ -0,0 +1,55 @@ +/** + * External dependencies + */ +import type { BlockAttributes } from '@wordpress/blocks'; + +/** + * Internal dependencies + */ +import { ImageSizing } from './types'; + +export const blockAttributes: BlockAttributes = { + showProductLink: { + type: 'boolean', + default: true, + }, + showSaleBadge: { + type: 'boolean', + default: true, + }, + saleBadgeAlign: { + type: 'string', + default: 'right', + }, + imageSizing: { + type: 'string', + default: ImageSizing.SINGLE, + }, + productId: { + type: 'number', + default: 0, + }, + isDescendentOfQueryLoop: { + type: 'boolean', + default: false, + }, + isDescendentOfSingleProductBlock: { + type: 'boolean', + default: false, + }, + width: { + type: 'string', + }, + height: { + type: 'string', + }, + scale: { + type: 'string', + default: 'cover', + }, + aspectRatio: { + type: 'string', + }, +}; + +export default blockAttributes; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/block.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/block.tsx new file mode 100644 index 00000000000..5d05c9b9176 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/block.tsx @@ -0,0 +1,188 @@ +/** + * External dependencies + */ +import { Fragment } from '@wordpress/element'; +import { __, sprintf } from '@wordpress/i18n'; +import classnames from 'classnames'; +import { PLACEHOLDER_IMG_SRC } from '@woocommerce/settings'; +import { + useInnerBlockLayoutContext, + useProductDataContext, +} from '@woocommerce/shared-context'; +import { useStyleProps } from '@woocommerce/base-hooks'; +import { withProductDataContext } from '@woocommerce/shared-hocs'; +import { useStoreEvents } from '@woocommerce/base-context/hooks'; +import type { HTMLAttributes } from 'react'; + +/** + * Internal dependencies + */ +import ProductSaleBadge from '../sale-badge/block'; +import './style.scss'; +import { BlockAttributes, ImageSizing } from './types'; + +const ImagePlaceholder = ( props ): JSX.Element => { + return ( + + ); +}; + +interface ImageProps { + image?: null | { + alt?: string | undefined; + id: number; + name: string; + sizes?: string | undefined; + src?: string | undefined; + srcset?: string | undefined; + thumbnail?: string | undefined; + }; + loaded: boolean; + showFullSize: boolean; + fallbackAlt: string; + scale: string; + width?: string | undefined; + height?: string | undefined; + aspectRatio: string | undefined; +} + +const Image = ( { + image, + loaded, + showFullSize, + fallbackAlt, + width, + scale, + height, + aspectRatio, +}: ImageProps ): JSX.Element => { + const { thumbnail, src, srcset, sizes, alt } = image || {}; + const imageProps = { + alt: alt || fallbackAlt, + hidden: ! loaded, + src: thumbnail, + ...( showFullSize && { src, srcSet: srcset, sizes } ), + }; + + const imageStyles: Record< string, string | undefined > = { + height, + width, + objectFit: scale, + aspectRatio, + }; + + return ( + <> + { imageProps.src && ( + /* eslint-disable-next-line jsx-a11y/alt-text */ + + ) } + { ! image && } + + ); +}; + +type Props = BlockAttributes & HTMLAttributes< HTMLDivElement >; + +export const Block = ( props: Props ): JSX.Element | null => { + const { + className, + imageSizing = ImageSizing.SINGLE, + showProductLink = true, + showSaleBadge, + saleBadgeAlign = 'right', + height, + width, + scale, + aspectRatio, + ...restProps + } = props; + const styleProps = useStyleProps( props ); + const { parentClassName } = useInnerBlockLayoutContext(); + const { product, isLoading } = useProductDataContext(); + const { dispatchStoreEvent } = useStoreEvents(); + + if ( ! product.id ) { + return ( +
+ +
+ ); + } + const hasProductImages = !! product.images.length; + const image = hasProductImages ? product.images[ 0 ] : null; + const ParentComponent = showProductLink ? 'a' : Fragment; + const anchorLabel = sprintf( + /* translators: %s is referring to the product name */ + __( 'Link to %s', 'woo-gutenberg-products-block' ), + product.name + ); + const anchorProps = { + href: product.permalink, + ...( ! hasProductImages && { 'aria-label': anchorLabel } ), + onClick: () => { + dispatchStoreEvent( 'product-view-link', { + product, + } ); + }, + }; + + // Remove parent block custom styles from sale badge. + delete restProps.style; + + return ( +
+ + { !! showSaleBadge && ( + + ) } + + +
+ ); +}; + +export default withProductDataContext( Block ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/constants.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/constants.tsx new file mode 100644 index 00000000000..5ccf1075463 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/constants.tsx @@ -0,0 +1,17 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import { image, Icon } from '@wordpress/icons'; + +export const BLOCK_TITLE: string = __( + 'Product Image', + 'woo-gutenberg-products-block' +); +export const BLOCK_ICON: JSX.Element = ( + +); +export const BLOCK_DESCRIPTION: string = __( + 'Display the main product image.', + 'woo-gutenberg-products-block' +); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/edit.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/edit.tsx new file mode 100644 index 00000000000..b90ee88dd05 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/edit.tsx @@ -0,0 +1,199 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import { InspectorControls, useBlockProps } from '@wordpress/block-editor'; +import { createInterpolateElement, useEffect } from '@wordpress/element'; +import { getAdminLink, getSettingWithCoercion } from '@woocommerce/settings'; +import { isBoolean } from '@woocommerce/types'; +import type { BlockEditProps } from '@wordpress/blocks'; +import { ProductQueryContext as Context } from '@woocommerce/blocks/product-query/types'; +import { + Disabled, + PanelBody, + ToggleControl, + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore - Ignoring because `__experimentalToggleGroupControl` is not yet in the type definitions. + // eslint-disable-next-line @wordpress/no-unsafe-wp-apis + __experimentalToggleGroupControl as ToggleGroupControl, + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore - Ignoring because `__experimentalToggleGroupControl` is not yet in the type definitions. + // eslint-disable-next-line @wordpress/no-unsafe-wp-apis + __experimentalToggleGroupControlOption as ToggleGroupControlOption, +} from '@wordpress/components'; + +/** + * Internal dependencies + */ +import Block from './block'; +import withProductSelector from '../shared/with-product-selector'; +import { + BLOCK_TITLE as label, + BLOCK_ICON as icon, + BLOCK_DESCRIPTION as description, +} from './constants'; +import { BlockAttributes, ImageSizing } from './types'; +import { ImageSizeSettings } from './image-size-settings'; + +type SaleBadgeAlignProps = 'left' | 'center' | 'right'; + +const Edit = ( { + attributes, + setAttributes, + context, +}: BlockEditProps< BlockAttributes > & { context: Context } ): JSX.Element => { + const { + showProductLink, + imageSizing, + showSaleBadge, + saleBadgeAlign, + width, + height, + scale, + } = attributes; + const blockProps = useBlockProps( { style: { width, height } } ); + const isDescendentOfQueryLoop = Number.isFinite( context.queryId ); + const isBlockThemeEnabled = getSettingWithCoercion( + 'isBlockThemeEnabled', + false, + isBoolean + ); + + useEffect( + () => setAttributes( { isDescendentOfQueryLoop } ), + [ setAttributes, isDescendentOfQueryLoop ] + ); + + return ( +
+ + + + + setAttributes( { + showProductLink: ! showProductLink, + } ) + } + /> + + setAttributes( { + showSaleBadge: ! showSaleBadge, + } ) + } + /> + { showSaleBadge && ( + + setAttributes( { saleBadgeAlign: value } ) + } + > + + + + + ) } + { ! isBlockThemeEnabled && ( + Customizer.', + 'woo-gutenberg-products-block' + ), + { + a: ( + // eslint-disable-next-line jsx-a11y/anchor-has-content + + ), + } + ) } + value={ imageSizing } + onChange={ ( value: ImageSizing ) => + setAttributes( { imageSizing: value } ) + } + > + + + + ) } + + + + + +
+ ); +}; + +export default withProductSelector( { icon, label, description } )( Edit ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/frontend.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/frontend.ts new file mode 100644 index 00000000000..b6c773996b2 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/frontend.ts @@ -0,0 +1,12 @@ +/** + * External dependencies + */ +import { withFilteredAttributes } from '@woocommerce/shared-hocs'; + +/** + * Internal dependencies + */ +import Block from './block'; +import attributes from './attributes'; + +export default withFilteredAttributes( attributes )( Block ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/image-size-settings.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/image-size-settings.tsx new file mode 100644 index 00000000000..22ade62c503 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/image-size-settings.tsx @@ -0,0 +1,127 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import { BlockAttributes } from '@wordpress/blocks'; +import { + // @ts-expect-error Using experimental features + // eslint-disable-next-line @wordpress/no-unsafe-wp-apis + __experimentalToggleGroupControl as ToggleGroupControl, + // @ts-expect-error Using experimental features + // eslint-disable-next-line @wordpress/no-unsafe-wp-apis + __experimentalToggleGroupControlOption as ToggleGroupControlOption, + // @ts-expect-error Using experimental features + // eslint-disable-next-line @wordpress/no-unsafe-wp-apis + __experimentalToolsPanel as ToolsPanel, + // @ts-expect-error Using experimental features + // eslint-disable-next-line @wordpress/no-unsafe-wp-apis + __experimentalToolsPanelItem as ToolsPanelItem, + // @ts-expect-error Using experimental features + // eslint-disable-next-line @wordpress/no-unsafe-wp-apis + __experimentalUnitControl as UnitControl, +} from '@wordpress/components'; + +interface ImageSizeSettingProps { + scale: string; + width: string | undefined; + height: string | undefined; + setAttributes: ( attrs: BlockAttributes ) => void; +} + +const scaleHelp: Record< string, string > = { + cover: __( + 'Image is scaled and cropped to fill the entire space without being distorted.', + 'woo-gutenberg-products-block' + ), + contain: __( + 'Image is scaled to fill the space without clipping nor distorting.', + 'woo-gutenberg-products-block' + ), + fill: __( + 'Image will be stretched and distorted to completely fill the space.', + 'woo-gutenberg-products-block' + ), +}; + +export const ImageSizeSettings = ( { + scale, + width, + height, + setAttributes, +}: ImageSizeSettingProps ) => { + return ( + + { + setAttributes( { height: value } ); + } } + value={ height } + units={ [ + { + value: 'px', + label: 'px', + }, + ] } + /> + { + setAttributes( { width: value } ); + } } + value={ width } + units={ [ + { + value: 'px', + label: 'px', + }, + ] } + /> + { height && ( + true } + label={ __( 'Scale', 'woo-gutenberg-products-block' ) } + > + + setAttributes( { + scale: value, + } ) + } + isBlock + > + <> + + + + + + + ) } + + ); +}; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/index.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/index.ts new file mode 100644 index 00000000000..f2edff84430 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/index.ts @@ -0,0 +1,42 @@ +/** + * External dependencies + */ +import { registerBlockType } from '@wordpress/blocks'; +import type { BlockConfiguration } from '@wordpress/blocks'; + +/** + * Internal dependencies + */ +import edit from './edit'; + +import { supports } from './supports'; +import attributes from './attributes'; +import sharedConfig from '../shared/config'; +import { + BLOCK_TITLE as title, + BLOCK_ICON as icon, + BLOCK_DESCRIPTION as description, +} from './constants'; + +const blockConfig: BlockConfiguration = { + ...sharedConfig, + apiVersion: 2, + name: 'woocommerce/product-image', + title, + icon: { src: icon }, + keywords: [ 'WooCommerce' ], + description, + usesContext: [ 'query', 'queryId', 'postId' ], + ancestor: [ + 'woocommerce/all-products', + 'woocommerce/single-product', + 'core/post-template', + 'woocommerce/product-template', + ], + textdomain: 'woo-gutenberg-products-block', + attributes, + supports, + edit, +}; + +registerBlockType( 'woocommerce/product-image', { ...blockConfig } ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/style.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/style.scss new file mode 100644 index 00000000000..7c08d449ee6 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/style.scss @@ -0,0 +1,67 @@ +.editor-styles-wrapper .wc-block-grid__products .wc-block-grid__product .wc-block-components-product-image, +.wc-block-components-product-image { + text-decoration: none; + display: block; + position: relative; + + a { + border-radius: inherit; + text-decoration: none; + border: 0; + outline: 0; + box-shadow: none; + } + + img { + border-radius: inherit; + vertical-align: middle; + width: 100%; + height: auto; + + &[hidden] { + display: none; + } + } + + img[alt=""] { + border: 1px solid $image-placeholder-border-color; + } + + .wc-block-components-product-sale-badge { + &--align-left { + position: absolute; + left: $gap-smaller * 0.5; + top: $gap-smaller * 0.5; + right: auto; + margin: 0; + } + &--align-center { + position: absolute; + top: $gap-smaller * 0.5; + left: 50%; + right: auto; + transform: translateX(-50%); + margin: 0; + } + &--align-right { + position: absolute; + right: $gap-smaller * 0.5; + top: $gap-smaller * 0.5; + left: auto; + margin: 0; + } + } +} + +.is-loading .wc-block-components-product-image { + @include placeholder($include-border-radius: false); + width: auto; +} + +.wc-block-components-product-image { + margin: 0 0 $gap-small; +} + +.wc-block-product-image__tools-panel .components-input-control { + margin-bottom: 8px; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/supports.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/supports.ts new file mode 100644 index 00000000000..27110fe30ef --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/supports.ts @@ -0,0 +1,31 @@ +/* eslint-disable @wordpress/no-unsafe-wp-apis */ +/** + * External dependencies + */ +import { isFeaturePluginBuild } from '@woocommerce/block-settings'; +import { __experimentalGetSpacingClassesAndStyles as getSpacingClassesAndStyles } from '@wordpress/block-editor'; + +/** + * Internal dependencies + */ + +export const supports = { + html: false, + ...( isFeaturePluginBuild() && { + __experimentalBorder: { + radius: true, + __experimentalSkipSerialization: true, + }, + typography: { + fontSize: true, + __experimentalSkipSerialization: true, + }, + ...( typeof getSpacingClassesAndStyles === 'function' && { + spacing: { + margin: true, + padding: true, + }, + } ), + __experimentalSelector: '.wc-block-components-product-image', + } ), +}; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/test/block.test.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/test/block.test.tsx new file mode 100644 index 00000000000..7f47f6e8e27 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/test/block.test.tsx @@ -0,0 +1,289 @@ +/** + * External dependencies + */ +import { render, fireEvent } from '@testing-library/react'; +import { ProductDataContextProvider } from '@woocommerce/shared-context'; +import { ProductResponseItem } from '@woocommerce/types'; + +/** + * Internal dependencies + */ +import { Block } from '../block'; +import { ImageSizing } from '../types'; + +jest.mock( '@woocommerce/base-hooks', () => ( { + __esModule: true, + useStyleProps: jest.fn( () => ( { + className: '', + style: {}, + } ) ), +} ) ); + +const productWithoutImages: ProductResponseItem = { + name: 'Test product', + id: 1, + permalink: 'http://test.com/product/test-product/', + images: [], + parent: 0, + type: '', + variation: '', + sku: '', + short_description: '', + description: '', + on_sale: false, + prices: { + currency_code: 'USD', + currency_symbol: '', + currency_minor_unit: 0, + currency_decimal_separator: '', + currency_thousand_separator: '', + currency_prefix: '', + currency_suffix: '', + price: '', + regular_price: '', + sale_price: '', + price_range: null, + }, + price_html: '', + average_rating: '', + review_count: 0, + categories: [], + tags: [], + attributes: [], + variations: [], + has_options: false, + is_purchasable: false, + is_in_stock: false, + is_on_backorder: false, + low_stock_remaining: null, + sold_individually: false, + add_to_cart: { + text: '', + description: '', + url: '', + minimum: 0, + maximum: 0, + multiple_of: 0, + }, +}; + +const productWithImages: ProductResponseItem = { + name: 'Test product', + id: 1, + permalink: 'http://test.com/product/test-product/', + images: [ + { + id: 56, + src: 'logo-1.jpg', + thumbnail: 'logo-1-324x324.jpg', + srcset: 'logo-1.jpg 800w, logo-1-300x300.jpg 300w, logo-1-150x150.jpg 150w, logo-1-768x767.jpg 768w, logo-1-324x324.jpg 324w, logo-1-416x415.jpg 416w, logo-1-100x100.jpg 100w', + sizes: '(max-width: 800px) 100vw, 800px', + name: 'logo-1.jpg', + alt: '', + }, + { + id: 55, + src: 'beanie-with-logo-1.jpg', + thumbnail: 'beanie-with-logo-1-324x324.jpg', + srcset: 'beanie-with-logo-1.jpg 800w, beanie-with-logo-1-300x300.jpg 300w, beanie-with-logo-1-150x150.jpg 150w, beanie-with-logo-1-768x768.jpg 768w, beanie-with-logo-1-324x324.jpg 324w, beanie-with-logo-1-416x416.jpg 416w, beanie-with-logo-1-100x100.jpg 100w', + sizes: '(max-width: 800px) 100vw, 800px', + name: 'beanie-with-logo-1.jpg', + alt: '', + }, + ], + parent: 0, + type: '', + variation: '', + sku: '', + short_description: '', + description: '', + on_sale: false, + prices: { + currency_code: 'USD', + currency_symbol: '', + currency_minor_unit: 0, + currency_decimal_separator: '', + currency_thousand_separator: '', + currency_prefix: '', + currency_suffix: '', + price: '', + regular_price: '', + sale_price: '', + price_range: null, + }, + price_html: '', + average_rating: '', + review_count: 0, + categories: [], + tags: [], + attributes: [], + variations: [], + has_options: false, + is_purchasable: false, + is_in_stock: false, + is_on_backorder: false, + low_stock_remaining: null, + sold_individually: false, + add_to_cart: { + text: '', + description: '', + url: '', + minimum: 0, + maximum: 0, + multiple_of: 0, + }, +}; + +describe( 'Product Image Block', () => { + describe( 'with product link', () => { + test( 'should render an anchor with the product image', () => { + const component = render( + + + + ); + + // use testId as alt is added after image is loaded + const image = component.getByTestId( 'product-image' ); + fireEvent.load( image ); + + const productImage = component.getByAltText( + productWithImages.name + ); + expect( productImage.getAttribute( 'src' ) ).toBe( + productWithImages.images[ 0 ].src + ); + + const anchor = productImage.closest( 'a' ); + expect( anchor?.getAttribute( 'href' ) ).toBe( + productWithImages.permalink + ); + } ); + + test( 'should render an anchor with the placeholder image', () => { + const component = render( + + + + ); + + const placeholderImage = component.getByAltText( '' ); + expect( placeholderImage.getAttribute( 'src' ) ).toBe( + 'placeholder.jpg' + ); + + const anchor = placeholderImage.closest( 'a' ); + expect( anchor?.getAttribute( 'href' ) ).toBe( + productWithoutImages.permalink + ); + expect( anchor?.getAttribute( 'aria-label' ) ).toBe( + `Link to ${ productWithoutImages.name }` + ); + } ); + } ); + + describe( 'without product link', () => { + test( 'should render the product image without an anchor wrapper', () => { + const component = render( + + + + ); + const image = component.getByTestId( 'product-image' ); + fireEvent.load( image ); + + const productImage = component.getByAltText( + productWithImages.name + ); + expect( productImage.getAttribute( 'src' ) ).toBe( + productWithImages.images[ 0 ].src + ); + + const anchor = productImage.closest( 'a' ); + expect( anchor ).toBe( null ); + } ); + + test( 'should render the placeholder image without an anchor wrapper', () => { + const component = render( + + + + ); + + const placeholderImage = component.getByAltText( '' ); + expect( placeholderImage.getAttribute( 'src' ) ).toBe( + 'placeholder.jpg' + ); + + const anchor = placeholderImage.closest( 'a' ); + expect( anchor ).toBe( null ); + } ); + } ); + + describe( 'without image', () => { + test( 'should render the placeholder with no inline width or height attributes', () => { + const component = render( + + + + ); + + const placeholderImage = component.getByAltText( '' ); + expect( placeholderImage.getAttribute( 'src' ) ).toBe( + 'placeholder.jpg' + ); + expect( placeholderImage.getAttribute( 'width' ) ).toBe( null ); + expect( placeholderImage.getAttribute( 'height' ) ).toBe( null ); + } ); + } ); +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/types.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/types.ts new file mode 100644 index 00000000000..ccd88e86f43 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/image/types.ts @@ -0,0 +1,29 @@ +export enum ImageSizing { + SINGLE = 'single', + THUMBNAIL = 'thumbnail', +} + +export interface BlockAttributes { + // The product ID. + productId: number; + // CSS Class name for the component. + className?: string | undefined; + // Whether or not to display a link to the product page. + showProductLink: boolean; + // Whether or not to display the on sale badge. + showSaleBadge: boolean; + // How should the sale badge be aligned if displayed. + saleBadgeAlign: 'left' | 'center' | 'right'; + // Size of image to use. + imageSizing: ImageSizing; + // Whether or not be a children of Query Loop Block. + isDescendentOfQueryLoop: boolean; + // Height of the image. + height?: string; + // Width of the image. + width?: string; + // Image scaling method. + scale: 'cover' | 'contain' | 'fill'; + // Aspect ratio of the image. + aspectRatio: string; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/attributes.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/attributes.ts new file mode 100644 index 00000000000..0acba812f16 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/attributes.ts @@ -0,0 +1,29 @@ +/** + * External dependencies + */ +import { BlockAttributes } from '@wordpress/blocks'; + +export const blockAttributes: BlockAttributes = { + productId: { + type: 'number', + default: 0, + }, + isDescendentOfQueryLoop: { + type: 'boolean', + default: false, + }, + textAlign: { + type: 'string', + default: '', + }, + isDescendentOfSingleProductTemplate: { + type: 'boolean', + default: false, + }, + isDescendentOfSingleProductBlock: { + type: 'boolean', + default: false, + }, +}; + +export default blockAttributes; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/block.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/block.tsx new file mode 100644 index 00000000000..3f66056631b --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/block.tsx @@ -0,0 +1,131 @@ +/** + * External dependencies + */ +import classnames from 'classnames'; +import ProductPrice from '@woocommerce/base-components/product-price'; +import { getCurrencyFromPriceResponse } from '@woocommerce/price-format'; +import { + useInnerBlockLayoutContext, + useProductDataContext, +} from '@woocommerce/shared-context'; +import { useStyleProps } from '@woocommerce/base-hooks'; +import { withProductDataContext } from '@woocommerce/shared-hocs'; +import { CurrencyCode } from '@woocommerce/type-defs/currency'; +import type { HTMLAttributes } from 'react'; + +/** + * Internal dependencies + */ +import type { BlockAttributes } from './types'; + +type Props = BlockAttributes & HTMLAttributes< HTMLDivElement >; + +interface PriceProps { + currency_code: CurrencyCode; + currency_symbol: string; + currency_minor_unit: number; + currency_decimal_separator: string; + currency_thousand_separator: string; + currency_prefix: string; + currency_suffix: string; + price: string; + regular_price: string; + sale_price: string; + price_range: null | { min_amount: string; max_amount: string }; +} + +export const Block = ( props: Props ): JSX.Element | null => { + const { className, textAlign, isDescendentOfSingleProductTemplate } = props; + const styleProps = useStyleProps( props ); + const { parentName, parentClassName } = useInnerBlockLayoutContext(); + const { product } = useProductDataContext(); + + const isDescendentOfAllProductsBlock = + parentName === 'woocommerce/all-products'; + + const wrapperClassName = classnames( + 'wc-block-components-product-price', + className, + styleProps.className, + { + [ `${ parentClassName }__product-price` ]: parentClassName, + } + ); + + if ( ! product.id && ! isDescendentOfSingleProductTemplate ) { + const productPriceComponent = ( + + ); + if ( isDescendentOfAllProductsBlock ) { + return ( +
+ { productPriceComponent } +
+ ); + } + return productPriceComponent; + } + + const prices: PriceProps = product.prices; + const currency = isDescendentOfSingleProductTemplate + ? getCurrencyFromPriceResponse() + : getCurrencyFromPriceResponse( prices ); + + const pricePreview = '5000'; + const isOnSale = prices.price !== prices.regular_price; + const priceClassName = classnames( { + [ `${ parentClassName }__product-price__value` ]: parentClassName, + [ `${ parentClassName }__product-price__value--on-sale` ]: isOnSale, + } ); + + const productPriceComponent = ( + + ); + if ( isDescendentOfAllProductsBlock ) { + return ( +
+ { productPriceComponent } +
+ ); + } + return productPriceComponent; +}; + +export default ( props: Props ) => { + // It is necessary because this block has to support serveral contexts: + // - Inside `All Products Block` -> `withProductDataContext` HOC + // - Inside `Products Block` -> Gutenberg Context + // - Inside `Single Product Template` -> Gutenberg Context + // - Without any parent -> `WithSelector` and `withProductDataContext` HOCs + // For more details, check https://github.com/woocommerce/woocommerce-blocks/pull/8609 + if ( props.isDescendentOfSingleProductTemplate ) { + return ; + } + return withProductDataContext( Block )( props ); +}; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/constants.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/constants.tsx new file mode 100644 index 00000000000..544becb88aa --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/constants.tsx @@ -0,0 +1,20 @@ +/** + * External dependencies + */ +import { __ } from '@wordpress/i18n'; +import { currencyDollar, Icon } from '@wordpress/icons'; + +export const BLOCK_TITLE: string = __( + 'Product Price', + 'woo-gutenberg-products-block' +); +export const BLOCK_ICON: JSX.Element = ( + +); +export const BLOCK_DESCRIPTION: string = __( + 'Display the price of a product.', + 'woo-gutenberg-products-block' +); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx new file mode 100644 index 00000000000..d0cd2d33311 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/edit.tsx @@ -0,0 +1,93 @@ +/** + * External dependencies + */ +import { + AlignmentToolbar, + BlockControls, + useBlockProps, +} from '@wordpress/block-editor'; +import { useEffect } from '@wordpress/element'; +import type { BlockAlignment } from '@wordpress/blocks'; + +/** + * Internal dependencies + */ +import Block from './block'; +import { useIsDescendentOfSingleProductTemplate } from '../shared/use-is-descendent-of-single-product-template'; + +type UnsupportedAligments = 'wide' | 'full'; +type AllowedAlignments = Exclude< BlockAlignment, UnsupportedAligments >; + +interface BlockAttributes { + textAlign?: AllowedAlignments; +} + +interface Attributes { + textAlign: 'left' | 'center' | 'right'; + isDescendentOfSingleProduct: boolean; + isDescendentOfSingleProductBlock: boolean; + productId: number; +} + +interface Context { + queryId: number; +} + +interface Props { + attributes: Attributes; + setAttributes: ( + attributes: Partial< BlockAttributes > & Record< string, unknown > + ) => void; + context: Context; +} + +const PriceEdit = ( { + attributes, + setAttributes, + context, +}: Props ): JSX.Element => { + const blockProps = useBlockProps(); + const blockAttrs = { + ...attributes, + ...context, + }; + const isDescendentOfQueryLoop = Number.isFinite( context.queryId ); + + let { isDescendentOfSingleProductTemplate } = + useIsDescendentOfSingleProductTemplate( { isDescendentOfQueryLoop } ); + + if ( isDescendentOfQueryLoop ) { + isDescendentOfSingleProductTemplate = false; + } + + useEffect( + () => + setAttributes( { + isDescendentOfQueryLoop, + isDescendentOfSingleProductTemplate, + } ), + [ + isDescendentOfQueryLoop, + isDescendentOfSingleProductTemplate, + setAttributes, + ] + ); + + return ( + <> + + { + setAttributes( { textAlign } ); + } } + /> + +
+ +
+ + ); +}; + +export default PriceEdit; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/index.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/index.tsx new file mode 100644 index 00000000000..6447673b9f2 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/index.tsx @@ -0,0 +1,33 @@ +/** + * External dependencies + */ +import { registerBlockType } from '@wordpress/blocks'; + +/** + * Internal dependencies + */ +import sharedConfig from '../shared/config'; +import edit from './edit'; +import attributes from './attributes'; +import { supports } from './supports'; +import { + BLOCK_TITLE as title, + BLOCK_ICON as icon, + BLOCK_DESCRIPTION as description, +} from './constants'; + +const { ancestor, ...configuration } = sharedConfig; + +const blockConfig = { + ...configuration, + apiVersion: 2, + title, + description, + usesContext: [ 'query', 'queryId', 'postId' ], + icon: { src: icon }, + attributes, + supports, + edit, +}; + +registerBlockType( 'woocommerce/product-price', blockConfig ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/supports.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/supports.ts new file mode 100644 index 00000000000..3a1f18fd018 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/supports.ts @@ -0,0 +1,39 @@ +/** + * External dependencies + */ +import { isFeaturePluginBuild } from '@woocommerce/block-settings'; +import { __experimentalGetSpacingClassesAndStyles } from '@wordpress/block-editor'; + +/** + * Internal dependencies + */ +import sharedConfig from '../shared/config'; + +export const supports = { + ...sharedConfig.supports, + ...( isFeaturePluginBuild() && { + color: { + text: true, + background: true, + link: false, + __experimentalSkipSerialization: true, + }, + typography: { + fontSize: true, + lineHeight: true, + __experimentalFontFamily: true, + __experimentalFontWeight: true, + __experimentalFontStyle: true, + __experimentalSkipSerialization: true, + __experimentalLetterSpacing: true, + }, + __experimentalSelector: + '.wp-block-woocommerce-product-price .wc-block-components-product-price', + } ), + ...( typeof __experimentalGetSpacingClassesAndStyles === 'function' && { + spacing: { + margin: true, + padding: true, + }, + } ), +}; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/types.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/types.ts new file mode 100644 index 00000000000..bfbdb99815a --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/price/types.ts @@ -0,0 +1,7 @@ +export interface BlockAttributes { + productId?: number; + className?: string; + textAlign?: 'left' | 'center' | 'right'; + isDescendentOfQueryLoop?: boolean; + isDescendentOfSingleProductTemplate?: boolean; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/block.json b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/block.json new file mode 100644 index 00000000000..a8e95dd56ac --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/block.json @@ -0,0 +1,18 @@ +{ + "name": "woocommerce/product-details", + "version": "1.0.0", + "icon": "info", + "title": "Product Details", + "description": "Display a product's description, attributes, and reviews.", + "category": "woocommerce", + "keywords": [ "WooCommerce" ], + "supports": { + "align": true, + "spacing": { + "margin": true + } + }, + "textdomain": "woo-gutenberg-products-block", + "apiVersion": 2, + "$schema": "https://schemas.wp.org/trunk/block.json" +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/block.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/block.tsx new file mode 100644 index 00000000000..2d2f95bfd03 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/block.tsx @@ -0,0 +1,91 @@ +/** + * External dependencies + */ +import classnames from 'classnames'; +import { __ } from '@wordpress/i18n'; +import { useBlockProps } from '@wordpress/block-editor'; + +interface SingleProductTab { + id: string; + title: string; + active: boolean; + content: string | undefined; +} + +const ProductTabTitle = ( { + id, + title, + active, +}: Pick< SingleProductTab, 'id' | 'title' | 'active' > ) => { + return ( +
  • + { title } +
  • + ); +}; + +const ProductTabContent = ( { + id, + content, +}: Pick< SingleProductTab, 'id' | 'content' > ) => { + return ( +
    + { content } +
    + ); +}; + +export const SingleProductDetails = () => { + const blockProps = useBlockProps(); + const productTabs = [ + { + id: 'description', + title: 'Description', + active: true, + content: __( + 'This block lists description, attributes and reviews for a single product.', + 'woo-gutenberg-products-block' + ), + }, + { + id: 'additional_information', + title: 'Additional Information', + active: false, + }, + { id: 'reviews', title: 'Reviews', active: false }, + ]; + const tabsTitle = productTabs.map( ( { id, title, active } ) => ( + + ) ); + const tabsContent = productTabs.map( ( { id, content } ) => ( + + ) ); + + return ( +
    +
      + { tabsTitle } +
    + { tabsContent } +
    + ); +}; + +export default SingleProductDetails; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/edit.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/edit.tsx new file mode 100644 index 00000000000..6b8e4ab9f9c --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/edit.tsx @@ -0,0 +1,31 @@ +/** + * External dependencies + */ +import { useBlockProps } from '@wordpress/block-editor'; +import { Disabled } from '@wordpress/components'; +import type { BlockEditProps } from '@wordpress/blocks'; + +/** + * Internal dependencies + */ +import Block from './block'; +import { Attributes } from './types'; + +const Edit = ( { attributes }: BlockEditProps< Attributes > ) => { + const { className } = attributes; + const blockProps = useBlockProps( { + className, + } ); + + return ( + <> +
    + + + +
    + + ); +}; + +export default Edit; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/index.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/index.tsx new file mode 100644 index 00000000000..4a71b9963ae --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/index.tsx @@ -0,0 +1,31 @@ +/** + * External dependencies + */ +import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils'; +import { Icon } from '@wordpress/icons'; +import { productDetails } from '@woocommerce/icons'; + +/** + * Internal dependencies + */ +import metadata from './block.json'; +import edit from './edit'; +import './style.scss'; + +registerBlockSingleProductTemplate( { + blockName: metadata.name, + // @ts-expect-error: `metadata` currently does not have a type definition in WordPress core + blockMetadata: metadata, + blockSettings: { + icon: { + src: ( + + ), + }, + edit, + }, + isAvailableOnPostEditor: false, +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/style.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/style.scss new file mode 100644 index 00000000000..6e6405d4392 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/style.scss @@ -0,0 +1,38 @@ +.wp-block-woocommerce-product-details { + ul.wc-tabs { + list-style: none; + padding: 0 0 0 1em; + margin: 0 0 1.618em; + overflow: hidden; + position: relative; + border-bottom: 1px solid $gray-200; + + li { + border: 1px solid $gray-200; + display: inline-block; + position: relative; + z-index: 0; + border-radius: $universal-border-radius $universal-border-radius 0 0; + margin: 0; + padding: 0.5em 1em; + + a { + display: inline-block; + font-weight: 700; + text-decoration: none; + + &:hover { + text-decoration: none; + } + } + + &.active { + z-index: 2; + + a { + text-shadow: inherit; + } + } + } + } +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/types.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/types.ts new file mode 100644 index 00000000000..aa9b37b316a --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-details/types.ts @@ -0,0 +1,3 @@ +export interface Attributes { + className?: string; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/block.json b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/block.json new file mode 100644 index 00000000000..92def860465 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/block.json @@ -0,0 +1,17 @@ +{ + "name": "woocommerce/product-image-gallery", + "version": "1.0.0", + "title": "Product Image Gallery", + "icon": "gallery", + "description": "Display a product's images.", + "category": "woocommerce", + "supports": { + "align": true, + "multiple": false + }, + "keywords": [ "WooCommerce" ], + "usesContext": [ "postId", "postType", "queryId" ], + "textdomain": "woo-gutenberg-products-block", + "apiVersion": 2, + "$schema": "https://schemas.wp.org/trunk/block.json" +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/edit.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/edit.tsx new file mode 100644 index 00000000000..b4f50c9ca6a --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/edit.tsx @@ -0,0 +1,64 @@ +/** + * External dependencies + */ +import { WC_BLOCKS_IMAGE_URL } from '@woocommerce/block-settings'; +import { isEmptyObject } from '@woocommerce/types'; +import { useBlockProps } from '@wordpress/block-editor'; +import { BlockAttributes } from '@wordpress/blocks'; +import { Disabled } from '@wordpress/components'; +import type { BlockEditProps } from '@wordpress/blocks'; + +/** + * Internal dependencies + */ +import './editor.scss'; + +const Placeholder = () => { + return ( +
    + Placeholder +
    + { [ ...Array( 4 ).keys() ].map( ( index ) => { + return ( + Placeholder + ); + } ) } +
    +
    + ); +}; + +type Context = { + postId: string; + postType: string; + queryId: string; +}; + +interface Props extends BlockEditProps< BlockAttributes > { + context: Context; +} + +const Edit = ( { context }: Props ) => { + const blockProps = useBlockProps(); + + if ( isEmptyObject( context ) ) { + return ( +
    + + + +
    + ); + } + // We have work on this case when we will work on the Single Product block. + return <>; +}; + +export default Edit; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/editor.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/editor.scss new file mode 100644 index 00000000000..5b04e305fd0 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/editor.scss @@ -0,0 +1,14 @@ +.wc-block-editor-product-gallery { + img { + max-width: 500px; + width: 100%; + height: auto; + } + .wc-block-editor-product-gallery__other-images { + img { + width: 100px; + height: 100px; + margin: 5px; + } + } +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/index.ts b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/index.ts new file mode 100644 index 00000000000..9b7cb2ab19e --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/index.ts @@ -0,0 +1,24 @@ +/** + * External dependencies + */ +import { gallery as icon } from '@wordpress/icons'; +import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils'; + +/** + * Internal dependencies + */ +import edit from './edit'; +import metadata from './block.json'; +import './style.scss'; + +registerBlockSingleProductTemplate( { + blockName: metadata.name, + // @ts-expect-error: `metadata` currently does not have a type definition in WordPress core + blockMetadata: metadata, + blockSettings: { + icon, + // @ts-expect-error `edit` can be extended to include other attributes + edit, + }, + isAvailableOnPostEditor: false, +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/style.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/style.scss new file mode 100644 index 00000000000..e936b10f555 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-image-gallery/style.scss @@ -0,0 +1,24 @@ +.woocommerce .wp-block-woocommerce-product-image-gallery { + position: relative; + // This is necessary to calculate the correct width of the gallery. https://www.lockedownseo.com/parent-div-100-height-child-floated-elements/#:~:text=Solution%20%232%3A%20Float%20Parent%20Container + clear: both; + max-width: 512px; + + span.onsale { + right: unset; + z-index: 1; + left: -1rem; + } +} + +// This is necessary to calculate the correct width of the gallery. https://www.lockedownseo.com/parent-div-100-height-child-floated-elements/#:~:text=Solution%20%232%3A%20Float%20Parent%20Container +.woocommerce .wp-block-woocommerce-product-image-gallery::after { + clear: both; + content: ""; + display: table; +} + + +.woocommerce .wp-block-woocommerce-product-image-gallery .woocommerce-product-gallery.images { + width: 100%; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/block.json b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/block.json new file mode 100644 index 00000000000..5773190eb1c --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/block.json @@ -0,0 +1,17 @@ +{ + "name": "woocommerce/product-meta", + "version": "1.0.0", + "title": "Product Meta", + "icon": "product", + "description": "Display a product’s SKU, categories, tags, and more.", + "category": "woocommerce", + "supports": { + "align": true, + "reusable": false + }, + "keywords": [ "WooCommerce" ], + "usesContext": [ "postId", "postType", "queryId" ], + "textdomain": "woo-gutenberg-products-block", + "apiVersion": 2, + "$schema": "https://schemas.wp.org/trunk/block.json" +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/edit.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/edit.tsx new file mode 100644 index 00000000000..f6ab5077482 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/edit.tsx @@ -0,0 +1,58 @@ +/** + * External dependencies + */ +import { InnerBlocks, useBlockProps } from '@wordpress/block-editor'; +import { InnerBlockTemplate } from '@wordpress/blocks'; +import { __ } from '@wordpress/i18n'; + +/** + * Internal dependencies + */ +import './editor.scss'; +import { useIsDescendentOfSingleProductTemplate } from '../shared/use-is-descendent-of-single-product-template'; + +const Edit = () => { + const isDescendentOfSingleProductTemplate = + useIsDescendentOfSingleProductTemplate(); + + const TEMPLATE: InnerBlockTemplate[] = [ + [ + 'core/group', + { layout: { type: 'flex', flexWrap: 'nowrap' } }, + [ + [ + 'woocommerce/product-sku', + { + isDescendentOfSingleProductTemplate, + }, + ], + [ + 'core/post-terms', + { + prefix: __( + 'Category: ', + 'woo-gutenberg-products-block' + ), + term: 'product_cat', + }, + ], + [ + 'core/post-terms', + { + prefix: __( 'Tags: ', 'woo-gutenberg-products-block' ), + term: 'product_tag', + }, + ], + ], + ], + ]; + const blockProps = useBlockProps(); + + return ( +
    + +
    + ); +}; + +export default Edit; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/editor.scss b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/editor.scss new file mode 100644 index 00000000000..b3872daea3a --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/editor.scss @@ -0,0 +1,4 @@ +.wc-block-editor-related-products__notice { + margin: 10px auto; + max-width: max-content; +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/index.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/index.tsx new file mode 100644 index 00000000000..f7d5ffff681 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/index.tsx @@ -0,0 +1,33 @@ +/** + * External dependencies + */ +import { registerBlockSingleProductTemplate } from '@woocommerce/atomic-utils'; +import { Icon } from '@wordpress/icons'; +import { productMeta } from '@woocommerce/icons'; + +/** + * Internal dependencies + */ +import edit from './edit'; +import save from './save'; +import metadata from './block.json'; + +registerBlockSingleProductTemplate( { + blockName: metadata.name, + // @ts-expect-error: `metadata` currently does not have a type definition in WordPress core + blockMetadata: metadata, + blockSettings: { + edit, + save, + icon: { + src: ( + + ), + }, + ancestor: [ 'woocommerce/single-product' ], + }, + isAvailableOnPostEditor: true, +} ); diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/save.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/save.tsx new file mode 100644 index 00000000000..0feb6d8f950 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-meta/save.tsx @@ -0,0 +1,17 @@ +/** + * External dependencies + */ +import { InnerBlocks, useBlockProps } from '@wordpress/block-editor'; + +const Save = () => { + const blockProps = useBlockProps.save(); + + return ( +
    + { /* @ts-expect-error: `InnerBlocks.Content` is a component that is typed in WordPress core*/ } + +
    + ); +}; + +export default Save; diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-reviews/block.json b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-reviews/block.json new file mode 100644 index 00000000000..89b26015553 --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-reviews/block.json @@ -0,0 +1,15 @@ +{ + "name": "woocommerce/product-reviews", + "version": "1.0.0", + "icon": "admin-comments", + "title": "Product Reviews", + "description": "A block that shows the reviews for a product.", + "category": "woocommerce", + "keywords": [ "WooCommerce" ], + "supports": {}, + "attributes": {}, + "usesContext": [ "postId" ], + "textdomain": "woo-gutenberg-products-block", + "apiVersion": 2, + "$schema": "https://schemas.wp.org/trunk/block.json" +} diff --git a/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-reviews/block.tsx b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-reviews/block.tsx new file mode 100644 index 00000000000..da8d08aee9a --- /dev/null +++ b/plugins/woocommerce-blocks/assets/js/atomic/blocks/product-elements/product-reviews/block.tsx @@ -0,0 +1,69 @@ +// We are using anchors as mere placeholders to replicate the front-end look. +/* eslint-disable jsx-a11y/anchor-is-valid */ + +/** + * External dependencies + */ +import { WC_BLOCKS_IMAGE_URL } from '@woocommerce/block-settings'; +import { __ } from '@wordpress/i18n'; +import { useBlockProps } from '@wordpress/block-editor'; +import { Notice } from '@wordpress/components'; + +export const ProductReviews = () => { + const blockProps = useBlockProps(); + + return ( +
    + +

    + { __( + 'The products reviews and the form to add a new review will be displayed here according to your theme. The look you see here is not representative of what is going to look like, this is just a placeholder.', + 'woo-gutenberg-products-block' + ) } +

    +
    +

    + { __( + '3 reviews for this product', + 'woo-gutenberg-products-block' + ) } +

    + Placeholder +

    { __( 'Add a review', 'woo-gutenberg-products-block' ) }

    +
    +
    + + { __( + 'Your rating *', + 'woo-gutenberg-products-block' + ) } + +

    +
    +
    + + { __( + 'Your review *', + 'woo-gutenberg-products-block' + ) } + +