Merge remote-tracking branch 'woocommerce/woocommerce-blocks/trunk' into merge/woocommerce-blocks

This commit is contained in:
Christopher Allford 2023-12-08 20:14:58 -08:00
commit 12940ebcd6
3147 changed files with 351566 additions and 0 deletions

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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',
},
},
],
};

View File

@ -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

View File

@ -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/

View File

@ -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).

View File

@ -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.

View File

@ -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"
---
<!--
Thank you for taking the time to leave your feedback on the Cart and Checkout blocks!
We read every single one of these reports and use them as we plan and consider where we focus
future efforts on improving the blocks.
-->
## What do you like about the Cart & Checkout blocks?
## What do you think is missing from the Cart & Checkout blocks?

View File

@ -0,0 +1,9 @@
---
name: '📖 Feedback Documentation'
about: Submit feedback or report an issue about some documentation.
labels: 'type: documentation'
---
<!--
Thank you for taking the time to leave your feedback about the documentation. Please explain your issue or suggestion below.
-->

View File

@ -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.

View File

@ -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

View File

@ -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.

View File

@ -0,0 +1,17 @@
when:
- author:
teamIs:
- rubik
ignore:
nameIs:
assign:
teams:
- rubik
- author:
teamIs:
- woo-fse
ignore:
nameIs:
assign:
teams:
- woo-fse

View File

@ -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
```
```

View File

@ -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'

View File

@ -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();

Binary file not shown.

After

Width:  |  Height:  |  Size: 196 KiB

View File

@ -0,0 +1,89 @@
const identifier = `<!-- comments-aggregator -->`;
const separator = '<!-- separator -->';
const footerText =
'[comments-aggregator](https://github.com/woocommerce/woocommerce-blocks/tree/trunk/.github/comments-aggregator)';
const footer = `\n> <sub>${ footerText }</sub>\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 = `<!-- section-id: ${ sectionId } -->\n\n<!-- section-order: ${ order } -->\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]'
);
};

View File

@ -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'

View File

@ -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();

View File

@ -0,0 +1,3 @@
todo:
blobLines: 10
label: false

View File

@ -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"

View File

@ -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 wont 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 theres 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"
}
]

View File

@ -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'

View File

@ -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` +
'<details> \n' +
filesWithNewErrors.join( '\n\n' ) +
'\n' +
'</details>'
: '🎉 🎉 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();

View File

@ -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 }`,
},
}
);

View File

@ -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,
} );
};

View File

@ -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' ) }
`;
} );
};

View File

@ -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,
[]
);
};

View File

@ -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 well 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`.

View File

@ -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.
---

View File

@ -0,0 +1,61 @@
<!-- Please do not remove any information from this pull request. Instead, add N/A or leave blank if not applicable -->
## What
Fixes #
## Why
<!-- Describe the reason for your changes. This will help the reviewer and future readers get additional context -->
## Testing Instructions
<!-- Write these steps from the perspective of a "user" (merchant) familiar with WooCommerce. No need to spell out the steps for common setup scenarios (eg. "Create a product"), but do be specific about the thing being tested. Include screenshots demonstrating expectations where that will be helpful. -->
_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 <!-- Check this box if this PR can't be tested (ie: it makes changes to tests, coding standards, docblocks, etc.). -->
* [ ] Should be tested by the development team exclusively <!-- Check this box if this PR should be tested by the development team exclusively (ie: it doesn't include user-facing changes or it can't be tested without manually modifying the code). -->
## Screenshots or screencast
<!-- Any screenshots of UI changes will be helpful to include here. Leave blank if not applicable. -->
| Before | After |
| ------ | ----- |
| | |
## WooCommerce Visibility
<!-- Check this documentation link (../docs/blocks/feature-flags-and-experimental-interfaces.md) to see if the change is visible in WooCommerce core, part of the feature plugin, or experimental. -->
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
<!-- Provide a brief, descriptive summary of the changes in this PR. Include potential impacts on different parts of the product. Example: "Updated the checkout process to streamline the experience for users and reduce the number of steps." -->
> Add suggested changelog entry here.

View File

@ -0,0 +1,3 @@
{
"labelsToOmit": [ "skip-changelog", "type: build" ]
}

View File

@ -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: `<config name="minimum_supported_wp_version" value="5.6" />`.
- [ ] 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 well 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.

View File

@ -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.
---

View File

@ -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}}

View File

@ -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 }}

View File

@ -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}'

View File

@ -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
}

View File

@ -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

View File

@ -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}}

View File

@ -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'

View File

@ -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

View File

@ -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 }}

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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

View File

@ -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'
});

View File

@ -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 }}

View File

@ -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

View File

@ -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

View File

@ -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`

View File

@ -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

View File

@ -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

View File

@ -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() }}

View File

@ -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();

View File

@ -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

View File

@ -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

View File

@ -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() }}

69
plugins/woocommerce-blocks/.gitignore vendored Normal file
View File

@ -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

View File

@ -0,0 +1,4 @@
#!/usr/bin/env sh
. "$(dirname -- "$0")/_/husky.sh"
npm run pre-commit

View File

@ -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
}

View File

@ -0,0 +1,4 @@
**/node_modules/**
**/vendor/**
**/extensibility/**/actions.md
**/extensibility/**/filters.md

View File

@ -0,0 +1 @@
16.15.0

View File

@ -0,0 +1,3 @@
*.json
*.scss
*.yml

View File

@ -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' );

Binary file not shown.

View File

@ -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
}
}

View File

@ -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"
]
}

View File

@ -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",
"};"
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 258 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 76 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.8 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.3 KiB

View File

@ -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"
}
}

View File

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
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.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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 <https://www.gnu.org/licenses/>.
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:
<program> Copyright (C) <year> <name of author>
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
<https://www.gnu.org/licenses/>.
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
<https://www.gnu.org/licenses/why-not-lgpl.html>.

View File

@ -0,0 +1,81 @@
# WooCommerce Blocks <!-- omit in toc -->
[![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 <!-- omit in toc -->
- [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.

View File

@ -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 */

View File

@ -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.

View File

@ -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 <h1>, <h2>, 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 <button> style as if it was text. Useful for elements that must be `<button>` for a11y but don't need those styles.
@mixin text-button() {
@include reset-box();
@include reset-color();
@include reset-typography();
background: transparent;
box-shadow: none;
display: inline;
text-shadow: none;
&:hover,
&:focus,
&:active {
background: transparent;
}
}
// Reset <button> style so we can use link style for action buttons.
@mixin link-button() {
@include text-button();
text-decoration: underline;
}
@mixin hover-effect() {
&:hover {
text-decoration: none;
color: inherit;
cursor: pointer;
}
}
// Reset <button> style so we can use link style for action buttons in filter blocks
@mixin filter-link-button() {
@include link-button();
@include hover-effect();
@include font-size(small);
text-decoration: underline;
font-weight: normal;
color: inherit;
}
// Makes sure long words are broken if they overflow the container.
@mixin wrap-break-word() {
// This is the current standard, works in most browsers.
overflow-wrap: anywhere;
// Safari supports word-break.
word-break: break-word;
// IE11 doesn't support overflow-wrap neither word-break: break-word, so we fallback to -ms-work-break: break-all.
-ms-word-break: break-all;
}
// Add support for content alignment classes
@mixin with-alignment() {
// Apply max-width to floated items that have no intrinsic width
&.alignleft,
&.alignright {
max-width: $content-width * 0.5;
width: 100%;
}
// Using flexbox without an assigned height property breaks vertical center alignment in IE11.
// Appending an empty ::after element tricks IE11 into giving the cover image an implicit height, which sidesteps this issue.
&::after {
display: block;
content: "";
font-size: 0;
min-height: inherit;
// IE doesn't support flex so omit that.
@supports (position: sticky) {
content: none;
}
}
// Aligned cover blocks should not use our global alignment rules
&.aligncenter,
&.alignleft,
&.alignright {
display: flex;
}
}
// Shows an semi-transparent overlay
@mixin with-background-dim($opacity: 0.5) {
&.has-background-dim {
.background-dim__overlay::before {
content: "";
position: absolute;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: inherit;
border-radius: inherit;
opacity: $opacity;
z-index: 1;
}
}
@for $i from 1 through 10 {
&.has-background-dim-#{ $i * 10 } .background-dim__overlay::before {
opacity: $i * 0.1;
}
}
}
// Shows a border with the current color and a custom opacity. That can't be achieved
// with normal border because `currentColor` doesn't allow tweaking the opacity, and
// setting the opacity of the entire element would change the children's opacity too.
@mixin with-translucent-border($border-width: 1px, $opacity: 0.3) {
position: relative;
&::after {
border-style: solid;
border-width: $border-width;
bottom: 0;
content: "";
display: block;
left: 0;
opacity: $opacity;
pointer-events: none;
position: absolute;
right: 0;
top: 0;
}
}
// Wraps the content with a media query specially targeting IE11.
@mixin ie11() {
@media screen and (-ms-high-contrast: active), (-ms-high-contrast: none) {
@content;
}
}
// Positions an element absolutely and stretches it over the container
@mixin absolute-stretch() {
margin: 0;
padding: 0;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
width: 100%;
height: 100%;
}
// Converts a px unit to em.
@function em($size, $base: 16px) {
@return math.div($size, $base) * 1em;
}
// Encodes hex colors so they can be used in URL content.
@function encode-color($color) {
@if type-of($color) != "color" or string.index(#{$color}, "#") != 1 {
@return $color;
}
$hex: string.slice(color.ie-hex-str($color), 4);
@return "%23" + unquote("#{$hex}");
}

View File

@ -0,0 +1,14 @@
@import "node_modules/@wordpress/base-styles/variables";
// grid-unit from base-styles is 8px.
$gap-huge: 7 * $grid-unit; // 56px
$gap-largest: 6 * $grid-unit; // 48px
$gap-larger: 4.5 * $grid-unit; // 36px
$gap-large: 3 * $grid-unit; // 24px
$gap: 2 * $grid-unit; // 16px
$gap-small: 1.5 * $grid-unit; // 12px
$gap-smaller: 1 * $grid-unit; // 8px
$gap-smallest: 0.5 * $grid-unit; // 4px
// Standard border radius for forms.
$universal-border-radius: 4px;

View File

@ -0,0 +1,62 @@
// Remove the list styling, which is added back by core GB styles.
.editor-styles-wrapper {
.wc-block-grid {
.wc-block-grid__products {
list-style: none;
margin: 0 (-$gap * 0.5) $gap;
padding: 0;
.wc-block-grid__product {
margin: 0 0 $gap-large 0;
.wc-block-grid__product-onsale {
position: absolute;
}
}
}
&.components-placeholder {
padding: 2em 1em;
}
&.is-loading,
&.is-not-found {
display: block;
}
}
}
// Style inline notices in the inspector.
.components-base-control {
+ .wc-block-base-control-notice {
margin: -$gap 0 $gap;
}
+ .wc-block-base-control-notice:last-child {
margin: -$gap 0 $gap-small;
}
}
svg.wc-block-editor-components-block-icon--sparkles path {
fill: currentColor;
}
.block-editor-list-view-leaf.is-selected {
.block-editor-list-view-block-contents {
svg.wc-block-editor-components-block-icon {
color: currentColor;
}
}
}
.theme-twentytwenty {
.wp-block {
.wc-block-grid__product-title,
.wc-block-active-filters__title,
.wc-block-attribute-filter__title,
.wc-block-price-filter__title,
.wc-block-stock-filter__title {
@include font-size(regular);
}
}
}

View File

@ -0,0 +1,351 @@
// These styles are for the server side rendered product grid blocks.
.wc-block-grid__products .wc-block-grid__product-image {
text-decoration: none;
display: block;
position: relative;
a {
text-decoration: none;
border: 0;
outline: 0;
box-shadow: none;
}
img {
height: auto;
width: auto;
max-width: 100%;
&[hidden] {
display: none;
}
&[alt=""] {
border: 1px solid $image-placeholder-border-color;
}
}
}
.edit-post-visual-editor .editor-block-list__block .wc-block-grid__product-title,
.editor-styles-wrapper .wc-block-grid__product-title,
.wc-block-grid__product-title {
font-family: inherit;
line-height: 1.2;
font-weight: 700;
padding: 0;
color: inherit;
font-size: inherit;
display: block;
}
.wc-block-grid__product-price {
display: block;
.wc-block-grid__product-price__regular {
margin-right: 0.5em;
}
}
.wc-block-grid__product-add-to-cart.wp-block-button {
word-break: break-word;
white-space: normal;
.wp-block-button__link {
word-break: break-word;
white-space: normal;
margin-right: auto !important;
margin-left: auto !important;
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;
}
&.added::after {
font-family: WooCommerce; /* stylelint-disable-line */
content: "\e017";
margin-left: 0.5em;
display: inline-block;
width: auto;
height: auto;
}
&.loading::after {
font-family: WooCommerce; /* stylelint-disable-line */
content: "\e031";
animation: spin 2s linear infinite;
margin-left: 0.5em;
display: inline-block;
width: auto;
height: auto;
}
}
}
// Remove button sugar if unlikely to fit.
.has-5-columns:not(.alignfull),
.has-6-columns,
.has-7-columns,
.has-8-columns,
.has-9-columns {
.wc-block-grid__product-add-to-cart.wp-block-button .wp-block-button__link::after {
content: "";
margin: 0;
}
}
.wc-block-grid__product-rating {
display: block;
.wc-block-grid__product-rating__stars,
.star-rating {
overflow: hidden;
position: relative;
width: 5.3em;
height: 1.618em;
line-height: 1.618;
font-size: 1em;
/* stylelint-disable-next-line font-family-no-missing-generic-family-keyword */
font-family: star;
font-weight: 400;
margin: 0 auto;
text-align: left;
&::before {
content: "\53\53\53\53\53";
top: 0;
left: 0;
right: 0;
position: absolute;
opacity: 0.5;
white-space: nowrap;
}
span {
overflow: hidden;
top: 0;
left: 0;
right: 0;
position: absolute;
padding-top: 1.5em;
}
span::before {
content: "\53\53\53\53\53";
color: inherit;
top: 0;
left: 0;
right: 0;
position: absolute;
white-space: nowrap;
}
}
}
.wc-block-grid__product-image .wc-block-grid__product-onsale,
.wc-block-grid .wc-block-grid__product-onsale {
@include font-size(small);
padding: em($gap-smallest) em($gap-small);
display: inline-block;
width: auto;
border: 1px solid #43454b;
border-radius: $universal-border-radius;
color: #43454b;
background: #fff;
text-align: center;
text-transform: uppercase;
font-weight: 600;
z-index: 9;
position: absolute;
top: 4px;
right: 4px;
left: auto;
}
// Element spacing.
.wc-block-grid__product {
// Prevent link and image taking the full width unnecessarily, which might cause: https://github.com/woocommerce/woocommerce-blocks/issues/11438
.wc-block-grid__product-link,
.wc-block-grid__product-image {
display: inline-block;
position: relative;
}
// Not operator necessary for avoid this problem: https://github.com/woocommerce/woocommerce-gutenberg-products-block/pull/5925/files#r814043454
.wc-block-grid__product-image:not(.wc-block-components-product-image),
.wc-block-grid__product-title {
margin: 0 0 $gap-small;
}
// If centered when toggling alignment on, use auto margins to prevent flexbox stretching it.
.wc-block-grid__product-price,
.wc-block-grid__product-rating,
.wc-block-grid__product-add-to-cart,
.wc-block-grid__product-onsale {
margin: 0 auto $gap-small;
}
}
.theme-twentysixteen {
.wc-block-grid {
// Prevent white theme styles.
.price ins {
color: #77a464;
}
}
}
.theme-twentynineteen {
.wc-block-grid__product {
font-size: 0.88889em;
}
// Change the title font to match headings.
.wc-block-grid__product-title,
.wc-block-grid__product-onsale,
.wc-block-components-product-title,
.wc-block-components-product-sale-badge {
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Oxygen, Ubuntu, Cantarell, "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
}
.wc-block-grid__product-title::before {
display: none;
}
.wc-block-grid__product-onsale,
.wc-block-components-product-sale-badge {
line-height: 1;
}
.editor-styles-wrapper .wp-block-button .wp-block-button__link:not(.has-text-color) {
color: #fff;
}
}
.theme-twentytwenty {
$twentytwenty-headings: -apple-system, blinkmacsystemfont, "Helvetica Neue", helvetica, sans-serif;
$twentytwenty-highlights-color: #cd2653;
.wc-block-grid__product-link {
color: #000;
}
.wc-block-grid__product-title,
.wc-block-components-product-title {
font-family: $twentytwenty-headings;
color: $twentytwenty-highlights-color;
@include font-size(regular);
}
.wp-block-columns .wc-block-components-product-title {
margin-top: 0;
}
.wc-block-grid__product-price,
.wc-block-components-product-price {
&__value,
.woocommerce-Price-amount {
font-family: $twentytwenty-headings;
font-size: 0.9em;
}
del {
opacity: 0.5;
}
ins {
text-decoration: none;
}
}
.wc-block-grid__product-rating,
.star-rating {
font-size: 0.7em;
.wc-block-grid__product-rating__stars,
.wc-block-components-product-rating__stars {
line-height: 1;
}
}
.wc-block-grid__product-add-to-cart > .wp-block-button__link,
.wc-block-components-product-button > .wp-block-button__link {
font-family: $twentytwenty-headings;
}
.wc-block-grid__products .wc-block-grid__product-onsale,
.wc-block-components-product-sale-badge {
background: $twentytwenty-highlights-color;
color: #fff;
font-family: $twentytwenty-headings;
font-weight: 700;
letter-spacing: -0.02em;
line-height: 1.2;
text-transform: uppercase;
}
// Override style from WC Core that set its position to absolute.
// These rulesets can be removed once https://github.com/woocommerce/woocommerce/pull/26516 is released.
.wc-block-grid__products .wc-block-components-product-sale-badge {
position: static;
}
.wc-block-grid__products .wc-block-grid__product-image .wc-block-components-product-sale-badge {
position: absolute;
}
// These styles are not applied to the All Products atomic block, so it can be positioned normally.
.wc-block-grid__products .wc-block-grid__product-onsale:not(.wc-block-components-product-sale-badge) {
position: absolute;
right: 4px;
top: 4px;
z-index: 1;
}
.wc-block-active-filters__title,
.wc-block-attribute-filter__title,
.wc-block-price-filter__title,
.wc-block-stock-filter__title {
@include font-size(regular);
}
.wc-block-active-filters .wc-block-active-filters__clear-all {
@include font-size(smaller);
}
.wc-block-grid__product-add-to-cart.wp-block-button .wp-block-button__link {
@include font-size(smaller);
}
@media only screen and (min-width: 768px) {
.wc-block-grid__products .wc-block-grid__product-onsale {
@include font-size(small);
padding: em($gap-smaller);
}
}
@media only screen and (min-width: 1168px) {
.wc-block-grid__products .wc-block-grid__product-onsale {
@include font-size(small);
padding: em($gap-smaller);
}
}
}
.theme-twentytwentytwo {
.wc-block-grid__product-add-to-cart {
.added_to_cart {
margin-top: $gap-small;
display: block;
}
}
.wc-block-components-product-price,
.wc-block-grid__product-price {
ins {
text-decoration: none;
}
}
}
// Default screen-reader styles. Included as a fallback for themes that don't have support.
.screen-reader-text {
@include visually-hidden();
}
.screen-reader-text:focus {
@include visually-hidden-focus-reveal();
}
.wp-block-group.woocommerce.product .up-sells.upsells.products {
max-width: var(--wp--style--global--wide-size);
}

View File

@ -0,0 +1,127 @@
/**
* External dependencies
*/
import { registerBlockComponent } from '@woocommerce/blocks-registry';
import { lazy } from '@wordpress/element';
import { WC_BLOCKS_BUILD_URL } from '@woocommerce/block-settings';
// Modify webpack publicPath at runtime based on location of WordPress Plugin.
// eslint-disable-next-line no-undef,camelcase
__webpack_public_path__ = WC_BLOCKS_BUILD_URL;
registerBlockComponent( {
blockName: 'woocommerce/product-price',
component: lazy( () =>
import(
/* webpackChunkName: "product-price" */ './product-elements/price/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-image',
component: lazy( () =>
import(
/* webpackChunkName: "product-image" */ './product-elements/image/frontend'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-title',
component: lazy( () =>
import(
/* webpackChunkName: "product-title" */ './product-elements/title/frontend'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-rating',
component: lazy( () =>
import(
/* webpackChunkName: "product-rating" */ './product-elements/rating/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-rating-stars',
component: lazy( () =>
import(
/* webpackChunkName: "product-rating-stars" */ './product-elements/rating-stars/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-rating-counter',
component: lazy( () =>
import(
/* webpackChunkName: "product-rating-counter" */ './product-elements/rating-counter/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-average-rating',
component: lazy( () =>
import(
/* webpackChunkName: "product-average-rating" */ './product-elements/average-rating/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-button',
component: lazy( () =>
import(
/* webpackChunkName: "product-button" */ './product-elements/button/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-summary',
component: lazy( () =>
import(
/* webpackChunkName: "product-summary" */ './product-elements/summary/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-sale-badge',
component: lazy( () =>
import(
/* webpackChunkName: "product-sale-badge" */ './product-elements/sale-badge/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-sku',
component: lazy( () =>
import(
/* webpackChunkName: "product-sku" */ './product-elements/sku/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-stock-indicator',
component: lazy( () =>
import(
/* webpackChunkName: "product-stock-indicator" */ './product-elements/stock-indicator/block'
)
),
} );
registerBlockComponent( {
blockName: 'woocommerce/product-add-to-cart',
component: lazy( () =>
import(
/* webpackChunkName: "product-add-to-cart" */ './product-elements/add-to-cart/frontend'
)
),
} );

View File

@ -0,0 +1,22 @@
/**
* Internal dependencies
*/
import './product-elements/title';
import './product-elements/price';
import './product-elements/image';
import './product-elements/rating';
import './product-elements/rating-stars';
import './product-elements/rating-counter';
import './product-elements/average-rating';
import './product-elements/button';
import './product-elements/summary';
import './product-elements/sale-badge';
import './product-elements/sku';
import './product-elements/stock-indicator';
import './product-elements/add-to-cart';
import './product-elements/add-to-cart-form';
import './product-elements/product-image-gallery';
import './product-elements/product-details';
import './product-elements/product-reviews';
import './product-elements/related-products';
import './product-elements/product-meta';

View File

@ -0,0 +1,18 @@
{
"name": "woocommerce/add-to-cart-form",
"version": "1.0.0",
"title": "Add to Cart with Options",
"description": "Display a button so the customer can add a product to their cart. Options will also be displayed depending on product type. e.g. quantity, variation.",
"attributes": {
"isDescendentOfSingleProductBlock": {
"type": "boolean",
"default": false
}
},
"category": "woocommerce",
"keywords": [ "WooCommerce" ],
"usesContext": ["postId"],
"textdomain": "woo-gutenberg-products-block",
"apiVersion": 2,
"$schema": "https://schemas.wp.org/trunk/block.json"
}

View File

@ -0,0 +1,69 @@
/**
* External dependencies
*/
import { useEffect } from '@wordpress/element';
import { useBlockProps } from '@wordpress/block-editor';
import { __ } from '@wordpress/i18n';
import { Disabled, Tooltip } from '@wordpress/components';
import { Skeleton } from '@woocommerce/base-components/skeleton';
import { BlockEditProps } from '@wordpress/blocks';
/**
* Internal dependencies
*/
import './editor.scss';
import { useIsDescendentOfSingleProductBlock } from '../shared/use-is-descendent-of-single-product-block';
export interface Attributes {
className?: string;
isDescendentOfSingleProductBlock: boolean;
}
const Edit = ( props: BlockEditProps< Attributes > ) => {
const { setAttributes } = props;
const blockProps = useBlockProps( {
className: 'wc-block-add-to-cart-form',
} );
const { isDescendentOfSingleProductBlock } =
useIsDescendentOfSingleProductBlock( {
blockClientId: blockProps?.id,
} );
useEffect( () => {
setAttributes( {
isDescendentOfSingleProductBlock,
} );
}, [ setAttributes, isDescendentOfSingleProductBlock ] );
return (
<div { ...blockProps }>
<Tooltip
text="Customer will see product add-to-cart options in this space, dependent on the product type. "
position="bottom right"
>
<div className="wc-block-editor-add-to-cart-form-container">
<Skeleton numberOfLines={ 3 } />
<Disabled>
<div className="quantity">
<input
type={ 'number' }
value={ '1' }
className={ 'input-text qty text' }
readOnly
/>
</div>
<button
className={ `single_add_to_cart_button button alt wp-element-button` }
>
{ __(
'Add to cart',
'woo-gutenberg-products-block'
) }
</button>
</Disabled>
</div>
</Tooltip>
</div>
);
};
export default Edit;

View File

@ -0,0 +1,6 @@
.wc-block-editor-add-to-cart-form-container {
cursor: help;
gap: 10px;
display: flex;
flex-direction: column;
}

View File

@ -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: (
<Icon
icon={ button }
className="wc-block-editor-components-block-icon"
/>
),
},
ancestor: [ 'woocommerce/single-product' ],
save() {
return null;
},
};
registerBlockSingleProductTemplate( {
blockName: metadata.name,
blockMetadata: metadata,
blockSettings,
isAvailableOnPostEditor: true,
} );

View File

@ -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;
}
}
}

View File

@ -0,0 +1,12 @@
export const blockAttributes = {
showFormElements: {
type: 'boolean',
default: false,
},
productId: {
type: 'number',
default: 0,
},
};
export default blockAttributes;

View File

@ -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 <VariableProductForm />;
}
if ( productType === 'grouped' ) {
return <GroupedProductForm />;
}
if ( productType === 'external' ) {
return <ExternalProductForm />;
}
if ( productType === 'simple' || productType === 'variation' ) {
return <SimpleProductForm />;
}
return null;
}
return <AddToCartButton />;
};
/**
* 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 (
<AddToCartFormContextProvider
product={ product }
showFormElements={ showFormElements }
>
<div className={ componentClass }>
<AddToCartForm />
</div>
</AddToCartFormContextProvider>
);
};
export default withProductDataContext( Block );

View File

@ -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 = (
<Icon icon={ cart } className="wc-block-editor-components-block-icon" />
);
export const BLOCK_DESCRIPTION = __(
'Displays an add to cart button. Optionally displays other add to cart form elements.',
'woo-gutenberg-products-block'
);

View File

@ -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 (
<div
className={ classnames(
className,
'wc-block-components-product-add-to-cart'
) }
>
<EditProductLink productId={ product.id } />
<InspectorControls>
<PanelBody
title={ __( 'Layout', 'woo-gutenberg-products-block' ) }
>
{ productSupportsAddToCartForm( product ) ? (
<ToggleControl
label={ __(
'Display form elements',
'woo-gutenberg-products-block'
) }
help={ __(
'Depending on product type, allow customers to select a quantity, variations etc.',
'woo-gutenberg-products-block'
) }
checked={ showFormElements }
onChange={ () =>
setAttributes( {
showFormElements: ! showFormElements,
} )
}
/>
) : (
<Notice
className="wc-block-components-product-add-to-cart-notice"
isDismissible={ false }
status="info"
>
{ __(
'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'
) }
</Notice>
) }
</PanelBody>
</InspectorControls>
<Disabled>
<Block { ...attributes } />
</Disabled>
</div>
);
};
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 );

View File

@ -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 );

View File

@ -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,
} );

Some files were not shown because too many files have changed in this diff Show More