diff --git a/.betterleaks-history-baseline.json b/.betterleaks-history-baseline.json new file mode 100644 index 0000000..9830a16 --- /dev/null +++ b/.betterleaks-history-baseline.json @@ -0,0 +1,216 @@ +[ + { + "RuleID": "secret-literal-assignment", + "Description": "Secret-like literal assignment in source, YAML, env and config files", + "StartLine": 8, + "EndLine": 8, + "StartColumn": 3, + "EndColumn": 20, + "Match": "password = 'REDACTED'", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "valentinab25", + "git.author_name": "valentinab25", + "git.date": "2021-05-25T17:18:22Z", + "git.message": "Cypress coverage", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "d274f575bc425483bcf1bb84e1762bdf22462ec1", + "path": "cypress/support/commands.js", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/d274f575bc425483bcf1bb84e1762bdf22462ec1/cypress/support/commands.js#L8" + }, + "Tags": [ + "literal-secret", + "literal-secret" + ], + "Fingerprint": "d274f575bc425483bcf1bb84e1762bdf22462ec1:cypress/support/commands.js:secret-literal-assignment:8", + "File": "cypress/support/commands.js", + "SymlinkFile": "", + "Commit": "d274f575bc425483bcf1bb84e1762bdf22462ec1", + "Entropy": 2.321928, + "Author": "valentinab25", + "Email": "valentinab25", + "Date": "2021-05-25T17:18:22Z", + "Message": "Cypress coverage" + }, + { + "RuleID": "secret-literal-assignment", + "Description": "Secret-like literal assignment in source, YAML, env and config files", + "StartLine": 15, + "EndLine": 15, + "StartColumn": 28, + "EndColumn": 46, + "Match": "password: REDACTED", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "valentinab25", + "git.author_name": "valentinab25", + "git.date": "2021-05-25T17:18:22Z", + "git.message": "Cypress coverage", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "d274f575bc425483bcf1bb84e1762bdf22462ec1", + "path": "cypress/support/commands.js", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/d274f575bc425483bcf1bb84e1762bdf22462ec1/cypress/support/commands.js#L15" + }, + "Tags": [ + "literal-secret", + "literal-secret" + ], + "Fingerprint": "d274f575bc425483bcf1bb84e1762bdf22462ec1:cypress/support/commands.js:secret-literal-assignment:15", + "File": "cypress/support/commands.js", + "SymlinkFile": "", + "Commit": "d274f575bc425483bcf1bb84e1762bdf22462ec1", + "Entropy": 2.947703, + "Author": "valentinab25", + "Email": "valentinab25", + "Date": "2021-05-25T17:18:22Z", + "Message": "Cypress coverage" + }, + { + "RuleID": "secret-literal-assignment", + "Description": "Secret-like literal assignment in source, YAML, env and config files", + "StartLine": 8, + "EndLine": 8, + "StartColumn": 3, + "EndColumn": 20, + "Match": "password = 'REDACTED'", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "alin.voinea@eaudeweb.ro", + "git.author_name": "Alin Voinea", + "git.date": "2021-06-04T14:07:58Z", + "git.message": "Cypress coverage (#8)\n\n* Cypress coverage\n\n* Automated release 2.2.2\n\nCo-authored-by: valentinab25 \u003cvalentinab25\u003e\nCo-authored-by: EEA Jenkins \u003c@users.noreply.github.com\u003e", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "883e419076e90ec9b21cfb31961c01310f2ad68a", + "path": "cypress/support/commands.js", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/883e419076e90ec9b21cfb31961c01310f2ad68a/cypress/support/commands.js#L8" + }, + "Tags": [ + "literal-secret", + "literal-secret" + ], + "Fingerprint": "883e419076e90ec9b21cfb31961c01310f2ad68a:cypress/support/commands.js:secret-literal-assignment:8", + "File": "cypress/support/commands.js", + "SymlinkFile": "", + "Commit": "883e419076e90ec9b21cfb31961c01310f2ad68a", + "Entropy": 2.321928, + "Author": "Alin Voinea", + "Email": "alin.voinea@eaudeweb.ro", + "Date": "2021-06-04T14:07:58Z", + "Message": "Cypress coverage (#8)\n\n* Cypress coverage\n\n* Automated release 2.2.2\n\nCo-authored-by: valentinab25 \u003cvalentinab25\u003e\nCo-authored-by: EEA Jenkins \u003c@users.noreply.github.com\u003e" + }, + { + "RuleID": "secret-literal-assignment", + "Description": "Secret-like literal assignment in source, YAML, env and config files", + "StartLine": 15, + "EndLine": 15, + "StartColumn": 28, + "EndColumn": 46, + "Match": "password: REDACTED", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "alin.voinea@eaudeweb.ro", + "git.author_name": "Alin Voinea", + "git.date": "2021-06-04T14:07:58Z", + "git.message": "Cypress coverage (#8)\n\n* Cypress coverage\n\n* Automated release 2.2.2\n\nCo-authored-by: valentinab25 \u003cvalentinab25\u003e\nCo-authored-by: EEA Jenkins \u003c@users.noreply.github.com\u003e", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "883e419076e90ec9b21cfb31961c01310f2ad68a", + "path": "cypress/support/commands.js", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/883e419076e90ec9b21cfb31961c01310f2ad68a/cypress/support/commands.js#L15" + }, + "Tags": [ + "literal-secret", + "literal-secret" + ], + "Fingerprint": "883e419076e90ec9b21cfb31961c01310f2ad68a:cypress/support/commands.js:secret-literal-assignment:15", + "File": "cypress/support/commands.js", + "SymlinkFile": "", + "Commit": "883e419076e90ec9b21cfb31961c01310f2ad68a", + "Entropy": 2.947703, + "Author": "Alin Voinea", + "Email": "alin.voinea@eaudeweb.ro", + "Date": "2021-06-04T14:07:58Z", + "Message": "Cypress coverage (#8)\n\n* Cypress coverage\n\n* Automated release 2.2.2\n\nCo-authored-by: valentinab25 \u003cvalentinab25\u003e\nCo-authored-by: EEA Jenkins \u003c@users.noreply.github.com\u003e" + }, + { + "RuleID": "env-short-secret-assignment", + "Description": "Uppercase env-style PASS/TOKEN/SECRET assignment", + "StartLine": 36, + "EndLine": 36, + "StartColumn": 11, + "EndColumn": 49, + "Match": "GITHUB_TOKEN=REDACTED", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "miu.razvan28@gmail.com", + "git.author_name": "Miu Razvan", + "git.date": "2022-10-25T10:29:27Z", + "git.message": "Use latest cypress + bring add-on up to date", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "f1c4c50797ea25365d4bc28839f5bb10013ad423", + "path": "RELEASE.md", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/f1c4c50797ea25365d4bc28839f5bb10013ad423/RELEASE.md?plain=1#L36" + }, + "Tags": [ + "env", + "literal-secret", + "env", + "literal-secret" + ], + "Fingerprint": "f1c4c50797ea25365d4bc28839f5bb10013ad423:RELEASE.md:env-short-secret-assignment:36", + "File": "RELEASE.md", + "SymlinkFile": "", + "Commit": "f1c4c50797ea25365d4bc28839f5bb10013ad423", + "Entropy": 0.23519339, + "Author": "Miu Razvan", + "Email": "miu.razvan28@gmail.com", + "Date": "2022-10-25T10:29:27Z", + "Message": "Use latest cypress + bring add-on up to date" + }, + { + "RuleID": "env-short-secret-assignment", + "Description": "Uppercase env-style PASS/TOKEN/SECRET assignment", + "StartLine": 235, + "EndLine": 235, + "StartColumn": 11, + "EndColumn": 49, + "Match": "GITHUB_TOKEN=REDACTED", + "Secret": "REDACTED", + "Attributes": { + "git.author_email": "valentinab25", + "git.author_name": "valentinab25", + "git.date": "2021-12-16T17:01:46Z", + "git.message": "[JENKINS] Refs #142742 - Add release documentation", + "git.platform": "github", + "git.remote_url": "https://github.com/eea/volto-object-widget", + "git.sha": "9e888e25f098d4d1e556472eb1d1d85419050466", + "path": "README.md", + "resource": "git.patch_content", + "url": "https://github.com/eea/volto-object-widget/blob/9e888e25f098d4d1e556472eb1d1d85419050466/README.md?plain=1#L235" + }, + "Tags": [ + "env", + "literal-secret", + "env", + "literal-secret" + ], + "Fingerprint": "9e888e25f098d4d1e556472eb1d1d85419050466:README.md:env-short-secret-assignment:235", + "File": "README.md", + "SymlinkFile": "", + "Commit": "9e888e25f098d4d1e556472eb1d1d85419050466", + "Entropy": 0.23519339, + "Author": "valentinab25", + "Email": "valentinab25", + "Date": "2021-12-16T17:01:46Z", + "Message": "[JENKINS] Refs #142742 - Add release documentation" + } +] diff --git a/.cookieplone.json b/.cookieplone.json new file mode 100644 index 0000000..382620a --- /dev/null +++ b/.cookieplone.json @@ -0,0 +1,7 @@ +{ + "title": "Object Widget", + "frontend_addon_name": "volto-object-widget", + "description": "volto-object-widget: Volto add-on", + "volto_version": "19.3.0", + "__template__": "frontend_addon" +} diff --git a/.coverage.babel.config.js b/.coverage.babel.config.js index 37219fd..c1a8b42 100644 --- a/.coverage.babel.config.js +++ b/.coverage.babel.config.js @@ -1,9 +1,27 @@ -const defaultBabel = require('@plone/volto/babel'); +// Coverage-enabled variant of the Volto babel config. `make start-ci` copies +// this file over core/packages/volto/babel.config.js so that +// babel-plugin-istanbul instruments the app and Cypress can collect +// end-to-end coverage. +// +// Instrumenting the whole workspace breaks the client build (webpack 5 pulls +// server-only code in once tree-shaking is disabled), so only the add-on +// sources are instrumented: they are the only ones SonarQube analyses. +// `cwd` must be the workspace root (/app), otherwise test-exclude would +// ignore the add-on files, which live outside the Volto core package. +const path = require('path'); -function applyDefault(api) { +const defaultBabel = require('./babel'); + +const workspaceRoot = path.resolve(__dirname, '../../..'); + +module.exports = function (api) { const voltoBabel = defaultBabel(api); - voltoBabel.plugins.push('istanbul'); + voltoBabel.plugins.push([ + 'istanbul', + { + cwd: workspaceRoot, + include: ['packages/*/src/**'], + }, + ]); return voltoBabel; -} - -module.exports = applyDefault; +}; diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..b9a4d6e --- /dev/null +++ b/.dockerignore @@ -0,0 +1,10 @@ +.git +node_modules +core +build +coverage +*.log +.DS_Store +cypress/screenshots +cypress/videos +cypress/reports \ No newline at end of file diff --git a/.env b/.env deleted file mode 100644 index ef282fa..0000000 --- a/.env +++ /dev/null @@ -1,3 +0,0 @@ -# Jest configuration variables -# - possible values: ON, OFF -JEST_USE_SETUP=OFF \ No newline at end of file diff --git a/.eslintrc.js b/.eslintrc.js index c3c4cc1..be1ba7c 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -1,23 +1,14 @@ const fs = require('fs'); -const path = require('path'); -const projectRootPath = fs.realpathSync(__dirname + '/../../../'); - -let voltoPath = path.join(projectRootPath, 'node_modules/@plone/volto'); -let configFile; -if (fs.existsSync(`${projectRootPath}/tsconfig.json`)) - configFile = `${projectRootPath}/tsconfig.json`; -else if (fs.existsSync(`${projectRootPath}/jsconfig.json`)) - configFile = `${projectRootPath}/jsconfig.json`; +const projectRootPath = __dirname; +const { AddonRegistry } = require('@plone/registry/addon-registry'); -if (configFile) { - const jsConfig = require(configFile).compilerOptions; - const pathsConfig = jsConfig.paths; - if (pathsConfig['@plone/volto']) - voltoPath = `./${jsConfig.baseUrl}/${pathsConfig['@plone/volto'][0]}`; -} +let coreLocation; +if (fs.existsSync(`${projectRootPath}/core`)) + coreLocation = `${projectRootPath}/core`; +else if (fs.existsSync(`${projectRootPath}/../../core`)) + coreLocation = `${projectRootPath}/../../core`; -const { AddonRegistry } = require('@plone/registry/addon-registry'); -const { registry } = AddonRegistry.init(projectRootPath); +const { registry } = AddonRegistry.init(`${coreLocation}/packages/volto`); // Extends ESlint configuration for adding the aliases to `src` directories in Volto addons const addonAliases = Object.keys(registry.packages).map((o) => [ @@ -25,41 +16,26 @@ const addonAliases = Object.keys(registry.packages).map((o) => [ registry.packages[o].modulePath, ]); -const addonExtenders = registry.getEslintExtenders().map((m) => require(m)); - -const defaultConfig = { - extends: `${voltoPath}/.eslintrc`, +module.exports = { + extends: `${coreLocation}/packages/volto/.eslintrc`, + rules: { + 'import/no-unresolved': 1, + }, settings: { 'import/resolver': { alias: { map: [ - ['@plone/volto', '@plone/volto/src'], - ['@plone/volto-slate', '@plone/volto-slate/src'], + ['@plone/volto', `${coreLocation}/packages/volto/src`], + ['@plone/volto-slate', `${coreLocation}/packages/volto-slate/src`], + ['@plone/registry', `${coreLocation}/packages/registry/src`], + [ + '@eeacms/volto-object-widget', + './packages/volto-object-widget/src', + ], ...addonAliases, - ['@package', `${__dirname}/src`], - ['@root', `${__dirname}/src`], - ['~', `${__dirname}/src`], ], - extensions: ['.js', '.jsx', '.json'], - }, - 'babel-plugin-root-import': { - rootPathSuffix: 'src', + extensions: ['.js', '.jsx', '.ts', '.tsx', '.json'], }, }, }, - rules: { - 'react/jsx-no-target-blank': [ - 'error', - { - allowReferrer: true, - }, - ], - } }; - -const config = addonExtenders.reduce( - (acc, extender) => extender.modify(acc), - defaultConfig, -); - -module.exports = config; diff --git a/.github/workflows/betterleaks-audit.yml b/.github/workflows/betterleaks-audit.yml new file mode 100644 index 0000000..d68f013 --- /dev/null +++ b/.github/workflows/betterleaks-audit.yml @@ -0,0 +1,29 @@ +name: Betterleaks history audit + +on: + schedule: + - cron: "0 3 * * 1" # Mondays 03:00 UTC + workflow_dispatch: + +permissions: + contents: read + +jobs: + audit: + name: Scan all commits for secrets + runs-on: ubuntu-latest + timeout-minutes: 70 # outer guard; the scan itself stops after timeout-minutes below + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 0 # all commits of all branches + + # Shared EEA secret scan: https://github.com/eea/github-actions/tree/main/betterleaks#weekly-full-history-audit + # Findings already handled are listed in .betterleaks-history-baseline.json. + - uses: eea/github-actions/betterleaks@v1 + with: + mode: git + log-opts: --all + baseline: .betterleaks-history-baseline.json + timeout-minutes: 60 diff --git a/.github/workflows/betterleaks.yml b/.github/workflows/betterleaks.yml new file mode 100644 index 0000000..e916b59 --- /dev/null +++ b/.github/workflows/betterleaks.yml @@ -0,0 +1,34 @@ +name: Betterleaks + +on: + push: + pull_request: + +permissions: + contents: write + +jobs: + scan: + name: Scan for secrets + # push covers branches in this repo; pull_request is only needed for forks + if: github.event_name == 'push' || github.event.pull_request.head.repo.full_name != github.repository + runs-on: ubuntu-latest + timeout-minutes: 20 # outer guard; the scan itself stops after timeout-minutes below + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 + with: + persist-credentials: false + fetch-depth: 1 + ref: ${{ github.event.pull_request.head.sha || github.sha }} + + # Shared EEA secret scan: https://github.com/eea/github-actions/tree/main/betterleaks + # Findings show as annotations on this check (file and line), with a job summary. + - uses: eea/github-actions/betterleaks@v1 + with: + timeout-minutes: 15 + mention-author: "true" + smtp-url: ${{ secrets.SMTP_URL }} + smtp-port: ${{ secrets.SMTP_PORT || '25' }} + smtp-email: ${{ secrets.SMTP_EMAIL }} + smtp-password: ${{ secrets.SMTP_PASSWORD }} + fallback-email: ${{ vars.BETTERLEAKS_FALLBACK_EMAIL }} diff --git a/.gitignore b/.gitignore index f1be4ff..321c66e 100644 --- a/.gitignore +++ b/.gitignore @@ -24,3 +24,12 @@ videos .env.test.local .env.production.local *~ +.*project +.settings/ +.vscode +acceptance/cypress/videos/ +acceptance/node_modules +.storybook-build +/core +results +/public diff --git a/.gitleaks.toml b/.gitleaks.toml new file mode 100644 index 0000000..2b75f29 --- /dev/null +++ b/.gitleaks.toml @@ -0,0 +1,83 @@ +title = "Betterleaks config" + +[extend] +useDefault = true + +[[rules]] +id = "secret-literal-assignment" +description = "Secret-like literal assignment in source, YAML, env and config files" +regex = '''(?i)([A-Za-z0-9_.-]*(?:password|passwd|pwd|api[_-]?key|apikey|access[_-]?key|secret[_-]?access[_-]?key|private[_-]?key|client[_-]?secret|consumer[_-]?key|consumer[_-]?secret|(?:auth|access|refresh|session|api|bearer|id|jwt|csrf|xsrf|oauth)[_-]?token|translate[_-]?auth|translation[_-]?auth|auth[_-]?password|auth[_-]?key|auth[_-]?credentials|database[_-]?url|connection[_-]?string)[A-Za-z0-9_.-]*)[ \t]*[:=][ \t]*["'']?([^"''[:space:]#{}$.][^"''\n#{}]{2,})["'']?''' +secretGroup = 2 +keywords = [ + "password", + "passwd", + "pwd", + "api_key", + "apikey", + "access_key", + "private_key", + "client_secret", + "consumer_key", + "consumer_secret", + "auth_token", + "access_token", + "refresh_token", + "session_token", + "api_token", + "bearer_token", + "id_token", + "jwt_token", + "csrf_token", + "xsrf_token", + "oauth_token", + "translate_auth", + "translation_auth", + "auth_password", + "auth_key", + "auth_credentials", + "database_url", + "connection_string" +] +tags = ["literal-secret"] + +[[rules]] +id = "env-short-secret-assignment" +description = "Uppercase env-style PASS/TOKEN/SECRET assignment" +regex = '''\b((?:PASS|TOKEN|SECRET|[A-Z0-9_]*(?:_PASS|_TOKEN|_SECRET|PASS_|TOKEN_|SECRET_)[A-Z0-9_]*))[ \t]*[:=][ \t]*["'']?([^"''[:space:]#{}$.][^"''\n#{}]{2,})["'']?''' +secretGroup = 2 +keywords = [ + "PASS", + "TOKEN", + "SECRET" +] +tags = ["env", "literal-secret"] + +[[rules]] +id = "standalone-sk-token" +description = "Standalone sk-* token not attached to a secret-like variable name" +regex = '''(?i)\b(sk-[A-Za-z0-9][A-Za-z0-9_-]{20,})\b''' +secretGroup = 1 +entropy = 2.5 +keywords = ["sk-"] +tags = ["standalone-token", "generic"] + +[[rules]] +id = "forbidden-secret-file" +description = "Forbidden secret-bearing file committed to repository" +path = '''(?i)(^|/)(\.env\..*|\.pypirc|id_rsa|id_ed25519|.*\.(pem|key|p12|pfx|jks|kubeconfig))$''' +regex = '''(?s).{1,}''' +tags = ["file", "secret-file"] + +[[allowlists]] +description = "Allow Jenkins SonarQube token environment variable reference" +regexTarget = "match" +regexes = [ + '''SONAR_AUTH_TOKEN''', +] + +[[allowlists]] +description = "Ignore generated development workspace dependencies" +paths = [ + '''(^|/)core/''', + '''(^|/)node_modules/''', +] diff --git a/.husky/pre-commit b/.husky/pre-commit index 9183f9d..17092dc 100755 --- a/.husky/pre-commit +++ b/.husky/pre-commit @@ -1,2 +1,2 @@ [ -n "$CI" ] && exit 0 -yarn lint-staged +pnpm lint-staged diff --git a/.npmignore b/.npmignore index 080322a..eb6fa94 100644 --- a/.npmignore +++ b/.npmignore @@ -1,96 +1,16 @@ -# https://docs.npmjs.com/using-npm/developers.html#keeping-files-out-of-your-package - -# Directories -api/ -bin/ -build/ -lib/ -g-api/ -tests/ - -# Docs -docs/ - -# Cypress -cypress/ - -# Tests -__tests__/ -*.snap - -# Files -.travis.yml -requirements-docs.txt -requirements-tests.txt -yarn.lock -.dockerignore -.gitattributes -.yarnrc -.nvmrc -changelogupdater.js -pip-selfcheck.json -Dockerfile -CNAME -entrypoint.sh -Jenkinsfile -Makefile - -# Logs +.vscode/ +.history logs *.log npm-debug.log* -yarn-debug.log* -yarn-error.log* - -# Runtime data -pids -*.pid -*.seed -*.pid.lock - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# node-waf configuration -.lock-wscript - -# Compiled binary addons (https://nodejs.org/api/addons.html) -build/Release - -# Dependency directories -node_modules/ -jspm_packages/ - -# TypeScript v1 declaration files -typings/ - -# Optional npm cache directory -.npm - -# Optional eslint cache -.eslintcache - -# Optional REPL history -.node_repl_history - -# Output of 'npm pack' -*.tgz - -# Yarn Integrity file -.yarn-integrity - -# dotenv environment variables file -.env - -# next.js build output -.next - -styleguide.config -.vscode -packages +.DS_Store +*.swp +yarn-error.log + +node_modules +dockerfiles +acceptance +build +dist +yarn.lock +.storybook diff --git a/.npmrc b/.npmrc new file mode 100644 index 0000000..a770dea --- /dev/null +++ b/.npmrc @@ -0,0 +1,6 @@ +public-hoist-pattern[]=*eslint* +public-hoist-pattern[]=*prettier* +public-hoist-pattern[]=*stylelint* +public-hoist-pattern[]=*cypress* +public-hoist-pattern[]=babel-plugin-react-intl +public-hoist-pattern[]=*babel-preset-razzle diff --git a/.pnpmfile.cjs b/.pnpmfile.cjs new file mode 100644 index 0000000..7e9c7b2 --- /dev/null +++ b/.pnpmfile.cjs @@ -0,0 +1,23 @@ +/* eslint-disable */ +const fs = require('fs'); +const path = require('path'); + +const catalogPath = path.resolve(__dirname, 'core/catalog.json'); +let catalog = {}; +if (fs.existsSync(catalogPath)) { + const catalogData = fs.readFileSync(catalogPath, 'utf-8'); + catalog = JSON.parse(catalogData); +} else { + console.error('Catalog file does not exist at:', catalogPath); +} + +module.exports = { + hooks: { + updateConfig(config) { + if (config.catalogs) { + config.catalogs.default ??= catalog; + } + return config; + }, + }, +}; diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..16f05c7 --- /dev/null +++ b/.prettierignore @@ -0,0 +1,3 @@ +.storybook +CHANGELOG.md +README.md diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..c56f626 --- /dev/null +++ b/.prettierrc @@ -0,0 +1,12 @@ +{ + "trailingComma": "all", + "singleQuote": true, + "overrides": [ + { + "files": "*.overrides", + "options": { + "parser": "less" + } + } + ] + } diff --git a/.storybook/main.js b/.storybook/main.js new file mode 100644 index 0000000..a645419 --- /dev/null +++ b/.storybook/main.js @@ -0,0 +1,192 @@ +const webpack = require('webpack'); +const fs = require('fs'); +const path = require('path'); + +const projectRootPath = path.resolve('.'); +const lessPlugin = require('@plone/volto/webpack-plugins/webpack-less-plugin'); +const RelativeResolverPlugin = require('@plone/volto/webpack-plugins/webpack-relative-resolver'); +const scssPlugin = require('@plone/volto/webpack-plugins/webpack-scss-plugin'); +const createConfig = require('@plone/razzle/config/createConfigAsync.js'); +const razzleConfig = require(path.join(projectRootPath, 'razzle.config.js')); + +const SVGLOADER = { + test: /icons\/.*\.svg$/, + use: [ + { + loader: 'svg-loader', + }, + { + loader: 'svgo-loader', + options: { + plugins: [ + { + name: 'preset-default', + params: { + overrides: { + convertPathData: false, + removeViewBox: false, + }, + }, + }, + 'removeTitle', + 'removeUselessStrokeAndFill', + ], + }, + }, + ], +}; + +const defaultRazzleOptions = { + verbose: false, + debug: {}, + buildType: 'iso', + cssPrefix: 'static/css', + jsPrefix: 'static/js', + enableSourceMaps: true, + enableReactRefresh: true, + enableTargetBabelrc: false, + enableBabelCache: true, + forceRuntimeEnvVars: [], + mediaPrefix: 'static/media', + staticCssInDev: false, + emitOnErrors: false, + disableWebpackbar: false, + browserslist: [ + '>1%', + 'last 4 versions', + 'Firefox ESR', + 'not ie 11', + 'not dead', + ], +}; + +module.exports = { + stories: [ + '../packages/**/*.mdx', + '../packages/**/*.stories.@(js|jsx|ts|tsx)', + ], + addons: [ + '@storybook/addon-links', + '@storybook/addon-essentials', + '@storybook/addon-webpack5-compiler-babel', + ], + framework: { + name: '@storybook/react-webpack5', + options: { builder: { useSWC: true } }, + }, + typescript: { + check: false, + checkOptions: {}, + reactDocgen: 'react-docgen-typescript', + reactDocgenTypescriptOptions: { + compilerOptions: { + allowSyntheticDefaultImports: false, + esModuleInterop: false, + }, + propFilter: () => true, + }, + }, + webpackFinal: async (config, { configType }) => { + // `configType` has a value of 'DEVELOPMENT' or 'PRODUCTION' + // You can change the configuration based on that. + // 'PRODUCTION' is used when building the static version of storybook. + + // Make whatever fine-grained changes you need + let baseConfig; + baseConfig = await createConfig( + 'web', + 'dev', + { + // clearConsole: false, + modifyWebpackConfig: razzleConfig.modifyWebpackConfig, + plugins: razzleConfig.plugins, + }, + webpack, + false, + undefined, + [], + defaultRazzleOptions, + ); + const { AddonRegistry } = require('@plone/registry/addon-registry'); + + const { registry } = AddonRegistry.init(projectRootPath); + + config = lessPlugin({ registry }).modifyWebpackConfig({ + env: { target: 'web', dev: 'dev' }, + webpackConfig: config, + webpackObject: webpack, + options: {}, + }); + + config = scssPlugin.modifyWebpackConfig({ + env: { target: 'web', dev: 'dev' }, + webpackConfig: config, + webpackObject: webpack, + options: { razzleOptions: {} }, + }); + + // Put the SVG loader on top and prevent the asset/resource rule + // from processing the app's SVGs + config.module.rules.unshift(SVGLOADER); + const fileLoaderRule = config.module.rules.find((rule) => + rule.test.test('.svg'), + ); + fileLoaderRule.exclude = /icons\/.*\.svg$/; + + config.plugins.unshift( + new webpack.DefinePlugin({ + __DEVELOPMENT__: true, + __CLIENT__: true, + __SERVER__: false, + }), + ); + + const resultConfig = { + ...config, + resolve: { + ...config.resolve, + alias: { ...config.resolve.alias, ...baseConfig.resolve.alias }, + fallback: { ...config.resolve.fallback, zlib: false }, + plugins: [ + ...(config.resolve.plugins || []), + new RelativeResolverPlugin(registry), + ], + }, + }; + + // Add-ons have to be loaded with babel + const addonPaths = registry + .getAddons() + .map((addon) => fs.realpathSync(addon.modulePath)); + + resultConfig.module.rules[13].exclude = (input) => + // exclude every input from node_modules except from @plone/volto + /node_modules\/(?!(@plone\/volto)\/)/.test(input) && + // Storybook default exclusions + /storybook-config-entry\.js$/.test(input) && + /storybook-stories\.js$/.test(input) && + // If input is in an addon, DON'T exclude it + !addonPaths.some((p) => input.includes(p)); + + resultConfig.module.rules[13].include = [ + /preview\.jsx/, + ...resultConfig.module.rules[13].include, + ...addonPaths, + ]; + + const addonExtenders = registry.getAddonExtenders().map((m) => require(m)); + + const extendedConfig = addonExtenders.reduce( + (acc, extender) => + extender.modify(acc, { target: 'web', dev: 'dev' }, config), + resultConfig, + ); + + // Note: we don't actually support razzle plugins, which are also a feature + // of the razzle.extend.js addons file. Those features are probably + // provided in a different manner by Storybook plugins (for example scss + // loaders). + + return extendedConfig; + }, +}; diff --git a/.storybook/preview.jsx b/.storybook/preview.jsx new file mode 100644 index 0000000..1d2ac84 --- /dev/null +++ b/.storybook/preview.jsx @@ -0,0 +1,26 @@ +import '@plone/volto/config'; // This is the bootstrap for the global config - client side +import React from 'react'; +import { StaticRouter } from 'react-router-dom'; +import { IntlProvider } from 'react-intl'; +import enMessages from '@root/../locales/en.json'; + +import '@root/theme'; + +export const parameters = { + controls: { + matchers: { + color: /(background|color)$/i, + date: /Date$/, + }, + }, +}; + +export const decorators = [ + (Story) => ( + + + + + + ), +]; diff --git a/.stylelintrc b/.stylelintrc new file mode 100644 index 0000000..09d4a27 --- /dev/null +++ b/.stylelintrc @@ -0,0 +1,32 @@ +{ + "extends": [ + "stylelint-config-idiomatic-order" + ], + "plugins": [ + "stylelint-prettier" + ], + "overrides": [ + { + "files": [ + "**/*.less" + ], + "customSyntax": "postcss-less" + }, + { + "files": [ + "**/*.overrides" + ], + "customSyntax": "postcss-less" + }, + { + "files": [ + "**/*.scss" + ], + "customSyntax": "postcss-scss" + } + ], + "rules": { + "prettier/prettier": true, + "order/properties-alphabetical-order": null + } +} diff --git a/DEVELOP.md b/DEVELOP.md index 61530df..362b745 100644 --- a/DEVELOP.md +++ b/DEVELOP.md @@ -106,3 +106,62 @@ Or run it: ```Bash make cypress-run ``` + +## Secret Scanning + +This repository uses the Betterleaks GitHub Action to scan the current +repository content on every push and pull request. The scan uses the rules in +`.gitleaks.toml` and uploads a `betterleaks-report` artifact when a finding is +detected. + +If the optional SMTP secrets are configured, failed scans also send an email to +the last commit committer. The workflow expects these repository or +organization secrets: + +- `SMTP_URL` +- `SMTP_PORT` (optional, defaults to `25`) +- `SMTP_EMAIL` +- `SMTP_PASSWORD` (optional if the SMTP server does not require authentication) + +Port `465` is sent with direct TLS; other ports use the default SMTP handshake. +The email includes a short finding summary from the redacted Betterleaks report, +including the redacted matched line from each finding. + +There are three common outcomes: + +1. **Everything is OK.** The `Betterleaks / Scan for secrets` check is green and + no action is needed. Regular references to runtime values are OK, for example: + + ```js + const tokenFromCookie = req.universalCookies.get('auth_token'); + ``` + +2. **A real secret was found.** The check is red and the workflow log asks you to + download the `betterleaks-report` artifact. Open the artifact from the GitHub + Actions run and check the reported file, line and rule. Remove the committed + value, move it to the proper secret store, and rotate it if it was exposed. + A report entry looks like this: + + ```json + { + "RuleID": "secret-literal-assignment", + "File": "src/config.js", + "StartLine": 12, + "Secret": "[REDACTED]" + } + ``` + +3. **The finding is a false positive.** Keep the value only if it is clearly not + sensitive, such as a test fixture, placeholder, or public example. Add + `betterleaks:allow` on the same line and include a short explanation in the + pull request. + + ```js + const testPassword = 'admin'; //betterleaks:allow + ``` + + ```yaml + password: "admin" #betterleaks:allow + ``` + +Do not add `betterleaks:allow` to real credentials. diff --git a/Dockerfile b/Dockerfile index 5745d68..e941e56 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,23 +1,14 @@ # syntax=docker/dockerfile:1 +# Add-on overlay onto eeacms/frontend-builder (Volto + Chromium base). ARG VOLTO_VERSION -FROM plone/frontend-builder:${VOLTO_VERSION} +FROM eeacms/frontend-builder:${VOLTO_VERSION} -ARG ADDON_NAME ARG ADDON_PATH -ENV HOST="0.0.0.0" - -USER root -RUN apt-get update -q \ - && apt-get install -qy --no-install-recommends \ - chromium libgtk2.0-0 libgtk-3-0 libgbm-dev libnotify-dev libgconf-2-4 libnss3 libxss1 libasound2 libxtst6 xauth xvfb \ - && rm -rf /var/lib/apt/lists/* -USER node +# Overlay the add-on onto the base; rm -rf /app/cypress so the add-on's EEA +# cypress replaces the base's upstream Volto one. COPY --chown=node:node ./ /app/src/addons/${ADDON_PATH}/ - -RUN /setupAddon -RUN yarn add jest-junit -RUN yarn install - -ENTRYPOINT ["yarn"] -CMD ["start"] +RUN rm -rf /app/cypress \ + && cp -r /app/src/addons/${ADDON_PATH}/. /app/ \ + && pnpm install \ + && make build-deps \ No newline at end of file diff --git a/Jenkinsfile b/Jenkinsfile index 06e372b..123be6c 100644 --- a/Jenkinsfile +++ b/Jenkinsfile @@ -2,6 +2,7 @@ pipeline { agent { node { label 'docker-host' } } + environment { GIT_NAME = "volto-object-widget" NAMESPACE = "@eeacms" @@ -9,8 +10,8 @@ pipeline { DEPENDENCIES = "" BACKEND_PROFILES = "eea.kitkat:testing" BACKEND_ADDONS = "" - CURRENT_VOLTO = "18-yarn" - PREVIOUS_VOLTO = "17" + CURRENT_VOLTO = "19" + PREVIOUS_VOLTO = "18" IMAGE_NAME = BUILD_TAG.toLowerCase() } @@ -71,13 +72,13 @@ pipeline { } parallel { - // Declarative stage names must stay string literals. - stage('Volto 18-yarn') { + // Volto 19 (current) — full testing with EEA Makefile targets + stage('Volto 19') { agent { node { label 'docker-1.13'} } stages { - stage('Build test image') { + stage('Build test image') { steps { - sh '''docker build --pull --build-arg="VOLTO_VERSION=$CURRENT_VOLTO" --build-arg="ADDON_NAME=$NAMESPACE/$GIT_NAME" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend-current''' + sh '''docker build --pull --build-arg="VOLTO_VERSION=$CURRENT_VOLTO" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend-current''' } } @@ -88,8 +89,8 @@ pipeline { } steps { script { - fix_result = sh(script: '''docker run --name="$IMAGE_NAME-fix-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current ci-fix''', returnStatus: true) - sh '''docker cp $IMAGE_NAME-fix-current:/app/src/addons/$GIT_NAME/src .''' + fix_result = sh(script: '''docker run --name="$IMAGE_NAME-fix-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current ci-fix''', returnStatus: true) + sh '''docker cp $IMAGE_NAME-fix-current:/app/packages/$GIT_NAME/src ./packages/$GIT_NAME/''' sh '''docker rm -v $IMAGE_NAME-fix-current''' FOUND_FIX = sh(script: '''git diff | wc -l''', returnStdout: true).trim() @@ -99,7 +100,7 @@ pipeline { } sh '''git fetch origin $GIT_BRANCH:$GIT_BRANCH''' sh '''git checkout $GIT_BRANCH''' - sh '''git add src/''' + sh '''git add packages/$GIT_NAME/src/''' sh '''git commit -m "style: Automated code fix" ''' sh '''git push --set-upstream origin $GIT_BRANCH''' sh '''exit 1''' @@ -111,35 +112,36 @@ pipeline { stage('ES lint') { when { environment name: 'SKIP_TESTS', value: '' } steps { - sh '''docker run --rm --name="$IMAGE_NAME-eslint-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current lint''' + sh '''docker run --rm --name="$IMAGE_NAME-eslint-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current lint''' } } stage('Style lint') { when { environment name: 'SKIP_TESTS', value: '' } steps { - sh '''docker run --rm --name="$IMAGE_NAME-stylelint-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current stylelint''' + sh '''docker run --rm --name="$IMAGE_NAME-stylelint-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current stylelint''' } } stage('Prettier') { when { environment name: 'SKIP_TESTS', value: '' } steps { - sh '''docker run --rm --name="$IMAGE_NAME-prettier-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current prettier''' + sh '''docker run --rm --name="$IMAGE_NAME-prettier-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current prettier''' } } + stage('Unit tests') { when { environment name: 'SKIP_TESTS', value: '' } steps { script { try { - sh '''docker run --name="$IMAGE_NAME-volto-current" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current test-ci''' + sh '''docker run --name="$IMAGE_NAME-volto-current" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current test-ci''' sh '''rm -rf xunit-reports-current''' sh '''mkdir -p xunit-reports-current''' - sh '''docker cp $IMAGE_NAME-volto-current:/app/coverage xunit-reports-current/''' - sh '''docker cp $IMAGE_NAME-volto-current:/app/junit.xml xunit-reports-current/''' + sh '''docker cp $IMAGE_NAME-volto-current:/app/packages/$GIT_NAME/coverage xunit-reports-current/ 2>/dev/null || true''' + sh '''docker cp $IMAGE_NAME-volto-current:/app/packages/$GIT_NAME/junit.xml xunit-reports-current/ 2>/dev/null || true''' publishHTML(target : [ - allowMissing: false, + allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: 'xunit-reports-current/coverage/lcov-report', @@ -156,35 +158,35 @@ pipeline { } } } - + stage('Integration tests') { when { environment name: 'SKIP_TESTS', value: '' } steps { script { try { sh '''docker run --pull always --rm -d --name="$IMAGE_NAME-plone-current" -e SITE="Plone" -e PROFILES="$BACKEND_PROFILES" -e ADDONS="$BACKEND_ADDONS" eeacms/plone-backend''' - sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone-current:plone --name="$IMAGE_NAME-cypress-current" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-current start-ci''' - frontend = sh script:'''docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress-current make check-ci''', returnStatus: true + sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone-current:plone --name="$IMAGE_NAME-cypress-current" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-current start-ci''' + frontend = sh script:'''docker exec --workdir=/app $IMAGE_NAME-cypress-current make check-ci''', returnStatus: true if ( frontend != 0 ) { sh '''docker logs $IMAGE_NAME-cypress-current; exit 1''' } - sh '''timeout -s 9 1800 docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress-current make cypress-ci''' + sh '''timeout -s 9 1800 docker exec --workdir=/app $IMAGE_NAME-cypress-current make cypress-ci''' } finally { try { if ( frontend == 0 ) { sh '''rm -rf cypress-videos-current cypress-results-current cypress-coverage-current cypress-screenshots-current''' sh '''mkdir -p cypress-videos-current cypress-results-current cypress-coverage-current cypress-screenshots-current''' - videos = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/src/addons/$GIT_NAME/cypress/videos cypress-videos-current/''', returnStatus: true - sh '''docker cp $IMAGE_NAME-cypress-current:/app/src/addons/$GIT_NAME/cypress/reports cypress-results-current/''' - screenshots = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/src/addons/$GIT_NAME/cypress/screenshots cypress-screenshots-current''', returnStatus: true + videos = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/cypress/videos cypress-videos-current/''', returnStatus: true + sh '''docker cp $IMAGE_NAME-cypress-current:/app/cypress/reports cypress-results-current/''' + screenshots = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/cypress/screenshots cypress-screenshots-current''', returnStatus: true archiveArtifacts artifacts: 'cypress-screenshots-current/**', fingerprint: true, allowEmptyArchive: true - coverage = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/src/addons/$GIT_NAME/coverage cypress-coverage-current''', returnStatus: true + coverage = sh script: '''docker cp $IMAGE_NAME-cypress-current:/app/coverage cypress-coverage-current''', returnStatus: true if ( coverage == 0 ) { - publishHTML(target : [allowMissing: false, + publishHTML(target : [allowMissing: true, alwaysLinkToLastBuild: true, keepAll: true, reportDir: 'cypress-coverage-current/coverage/lcov-report', @@ -240,15 +242,15 @@ pipeline { def scannerHome = tool 'SonarQubeScanner' def nodeJS = tool 'NodeJS' if (env.CHANGE_ID) { - env.sonarParams = " -Dsonar.pullrequest.base=${env.CHANGE_TARGET} -Dsonar.pullrequest.branch=${env.CHANGE_BRANCH} -Dsonar.pullrequest.key=${env.CHANGE_ID} " + env.sonarParams = " -Dsonar.pullrequest.base='${env.CHANGE_TARGET}' -Dsonar.pullrequest.branch='${env.CHANGE_BRANCH}' -Dsonar.pullrequest.key='${env.CHANGE_ID}' " } else { - env.sonarParams = " -Dsonar.branch.name=${env.BRANCH_NAME}" + env.sonarParams = " -Dsonar.branch.name='${env.BRANCH_NAME}'" } withSonarQubeEnv('Sonarqube') { - sh '''sed -i "s#/app/src/addons/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info''' - sh '''sed -i "s#src/addons/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info''' - sh "export PATH=${scannerHome}/bin:${nodeJS}/bin:$PATH; sonar-scanner -Dsonar.javascript.lcov.reportPaths=./xunit-reports-current/coverage/lcov.info,./cypress-coverage-current/coverage/lcov.info -Dsonar.sources=./src -Dsonar.projectKey=$GIT_NAME -Dsonar.projectName=$GIT_NAME -Dsonar.projectVersion=\$(jq -r '.version' package.json) ${env.sonarParams}" + sh '''sed -i "s#/app/packages/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info 2>/dev/null || true''' + sh '''sed -i "s#packages/${GIT_NAME}/##g" xunit-reports-current/coverage/lcov.info 2>/dev/null || true''' + sh "export PATH=${scannerHome}/bin:${nodeJS}/bin:$PATH; sonar-scanner -Dsonar.javascript.lcov.reportPaths=./xunit-reports-current/coverage/lcov.info,./cypress-coverage-current/coverage/lcov.info -Dsonar.sources=./packages/$GIT_NAME/src -Dsonar.projectKey=\"${GIT_NAME}\" -Dsonar.projectName=\"${GIT_NAME}\" -Dsonar.projectVersion=\$(jq '.version' packages/$GIT_NAME/package.json) ${env.sonarParams}" sh '''try=5; while [ \$try -gt 0 ]; do curl -s -XPOST -u "${SONAR_AUTH_TOKEN}:" "${SONAR_HOST_URL}api/project_tags/set?project=${GIT_NAME}&tags=${SONARQUBE_TAGS}" > set_tags_result; if [ \$(grep -ic error set_tags_result ) -eq 0 ]; then try=0; else cat set_tags_result; echo "... Will retry"; sleep 15; try=\$(( \$try - 1 )); fi; done''' } } @@ -259,7 +261,8 @@ pipeline { } } - stage('Volto 17') { + // Volto 18 (previous) — pnpm, same EEA Makefile flow as Volto 19 + stage('Volto 18') { agent { node { label 'integration'} } when { allOf { @@ -268,51 +271,51 @@ pipeline { } } stages { - stage('Build test image') { + stage('Build test image') { steps { - sh '''docker build --pull --build-arg="VOLTO_VERSION=$PREVIOUS_VOLTO" --build-arg="ADDON_NAME=$NAMESPACE/$GIT_NAME" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend-previous''' + sh '''docker build --pull --build-arg="VOLTO_VERSION=$PREVIOUS_VOLTO" --build-arg="ADDON_PATH=$GIT_NAME" . -t $IMAGE_NAME-frontend-previous''' } } - stage('Unit tests') { + stage('Integration tests') { steps { script { try { - sh '''docker run --name="$IMAGE_NAME-volto-previous" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-previous test-ci''' - sh '''rm -rf xunit-reports-previous''' - sh '''mkdir -p xunit-reports-previous''' - sh '''docker cp $IMAGE_NAME-volto-previous:/app/junit.xml xunit-reports-previous/''' - } finally { - catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { - junit testResults: 'xunit-reports-previous/junit.xml', allowEmptyResults: true + sh '''docker run --pull always --rm -d --name="$IMAGE_NAME-plone-previous" -e SITE="Plone" -e PROFILES="$BACKEND_PROFILES" -e ADDONS="$BACKEND_ADDONS" eeacms/plone-backend''' + sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone-previous:plone --name="$IMAGE_NAME-cypress-previous" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app $IMAGE_NAME-frontend-previous start-ci''' + frontend = sh script:'''docker exec --workdir=/app $IMAGE_NAME-cypress-previous make check-ci''', returnStatus: true + if ( frontend != 0 ) { + sh '''docker logs $IMAGE_NAME-cypress-previous; exit 1''' } - sh script: '''docker rm -v $IMAGE_NAME-volto-previous''', returnStatus: true - } - } - } - } - stage('Integration tests') { - steps { - script { - try { - sh '''docker run --pull always --rm -d --name="$IMAGE_NAME-plone-previous" -e SITE="Plone" -e PROFILES="$BACKEND_PROFILES" -e ADDONS="$BACKEND_ADDONS" eeacms/plone-backend''' - sh '''docker run -d --shm-size=4g --link $IMAGE_NAME-plone-previous:plone --name="$IMAGE_NAME-cypress-previous" -e "RAZZLE_INTERNAL_API_PATH=http://plone:8080/Plone" --entrypoint=make --workdir=/app/src/addons/$GIT_NAME $IMAGE_NAME-frontend-previous start-ci''' - sh '''timeout -s 9 1800 docker exec --workdir=/app/src/addons/${GIT_NAME} $IMAGE_NAME-cypress-previous make cypress-ci''' + sh '''timeout -s 9 1800 docker exec --workdir=/app $IMAGE_NAME-cypress-previous make cypress-ci''' } finally { try { + if ( frontend == 0 ) { sh '''rm -rf cypress-videos-previous cypress-results-previous cypress-coverage-previous cypress-screenshots-previous''' sh '''mkdir -p cypress-videos-previous cypress-results-previous cypress-coverage-previous cypress-screenshots-previous''' - videos = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/src/addons/$GIT_NAME/cypress/videos cypress-videos-previous/''', returnStatus: true - sh '''docker cp $IMAGE_NAME-cypress-previous:/app/src/addons/$GIT_NAME/cypress/reports cypress-results-previous/''' - screenshots = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/src/addons/$GIT_NAME/cypress/screenshots cypress-screenshots-previous''', returnStatus: true + videos = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/cypress/videos cypress-videos-previous/''', returnStatus: true + sh '''docker cp $IMAGE_NAME-cypress-previous:/app/cypress/reports cypress-results-previous/''' + screenshots = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/cypress/screenshots cypress-screenshots-previous''', returnStatus: true archiveArtifacts artifacts: 'cypress-screenshots-previous/**', fingerprint: true, allowEmptyArchive: true + coverage = sh script: '''docker cp $IMAGE_NAME-cypress-previous:/app/coverage cypress-coverage-previous''', returnStatus: true + + if ( coverage == 0 ) { + publishHTML(target : [allowMissing: true, + alwaysLinkToLastBuild: true, + keepAll: true, + reportDir: 'cypress-coverage-previous/coverage/lcov-report', + reportFiles: 'index.html', + reportName: 'CypressCoverage (Volto 18)', + reportTitles: 'Integration Tests Code Coverage']) + } if ( videos == 0 ) { sh '''for file in $(find cypress-results-previous -name *.xml); do if [ $(grep -E 'failures="[1-9].*"' $file | wc -l) -eq 0 ]; then testname=$(grep -E 'file=.*failures="0"' $file | sed 's#.* file=".*\\/\\(.*\\.[jsxt]\\+\\)" time.*#\\1#' ); rm -f cypress-videos-previous/videos/$testname.mp4; fi; done''' archiveArtifacts artifacts: 'cypress-videos-previous/**/*.mp4', fingerprint: true, allowEmptyArchive: true } + } } finally { catchError(buildResult: 'SUCCESS', stageResult: 'SUCCESS') { junit testResults: 'cypress-results-previous/**/*.xml', allowEmptyResults: true @@ -328,7 +331,7 @@ pipeline { } } } - } + } } } @@ -348,10 +351,10 @@ pipeline { allOf { not { environment name: 'CHANGE_ID', value: '' } environment name: 'CHANGE_TARGET', value: 'develop' - environment name: 'SKIP_TESTS', value: '' + environment name: 'SKIP_TESTS', value: '' } allOf { - environment name: 'SKIP_TESTS', value: '' + environment name: 'SKIP_TESTS', value: '' environment name: 'CHANGE_ID', value: '' branch 'develop' not { changelog '.*^Automated release [0-9\\.]+$' } @@ -412,4 +415,3 @@ pipeline { } } } - diff --git a/Makefile b/Makefile index 2537fb4..26e935f 100644 --- a/Makefile +++ b/Makefile @@ -1,12 +1,16 @@ ############################################################################## # Run: -# make +# make install # make start # # Go to: # # http://localhost:3000 # +# Backend: +# +# make backend-docker-start +# # Cypress: # # make cypress-open @@ -43,123 +47,120 @@ endif ############################################################################## # SETTINGS AND VARIABLE -DIR=$(shell basename $$(pwd)) -NODE_MODULES?="../../../node_modules" -PLONE_VERSION?=6 -VOLTO_VERSION?=18-yarn -ADDON_PATH="${DIR}" -ADDON_NAME="@eeacms/${ADDON_PATH}" -DOCKER_COMPOSE=PLONE_VERSION=${PLONE_VERSION} VOLTO_VERSION=${VOLTO_VERSION} ADDON_NAME=${ADDON_NAME} ADDON_PATH=${ADDON_PATH} docker compose -RAZZLE_INTERNAL_API_PATH?="http://localhost:8080/Plone" -RAZZLE_DEV_PROXY_API_PATH?="${RAZZLE_INTERNAL_API_PATH}" -CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" - +CURRENT_DIR:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST)))) +RAZZLE_INTERNAL_API_PATH?=http://localhost:8080/Plone +export RAZZLE_INTERNAL_API_PATH # Top-level targets .PHONY: all -all: clean install +all: help .PHONY: clean clean: ## Cleanup development environment - ${DOCKER_COMPOSE} down --volumes --remove-orphans + docker compose down --volumes --remove-orphans + rm -rf core node_modules .PHONY: install -install: ## Build and install development environment - echo "Running: ${DOCKER_COMPOSE} build" - ${DOCKER_COMPOSE} pull - ${DOCKER_COMPOSE} build +install: ## Install development environment + pnpm dlx mrs-developer missdev --no-config --fetch-https + pnpm i + make build-deps .PHONY: start -start: ## Start development environment - echo "Running: ${DOCKER_COMPOSE} up" - ${DOCKER_COMPOSE} up +start: ## Start backend and Volto frontend + docker compose up -d backend + pnpm start + +.PHONY: backend-docker-start +backend-docker-start: ## Start Plone backend on port 8080 + docker compose up backend -.PHONY: shell -shell: ## Start a shell in the frontend container - echo "Running: ${DOCKER_COMPOSE} run frontend bash" - ${DOCKER_COMPOSE} run --entrypoint=bash frontend +.PHONY: build +build: ## Build production bundle + pnpm build + +.PHONY: build-deps +build-deps: ## Build Volto dependencies + pnpm --filter @plone/registry --filter @plone/components build .PHONY: cypress-open -cypress-open: ## Open cypress integration tests - CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development CYPRESS_COVERAGE=true $(NODE_MODULES)/cypress/bin/cypress open +CYPRESS_SPEC_PATTERN=$(CURRENT_DIR)/cypress/tests/**/*.{js,jsx,ts,tsx} + +cypress-open: ## Open Cypress interactive runner + pnpm --filter @plone/volto exec cypress open --project $(CURRENT_DIR) --config-file $(CURRENT_DIR)/cypress.config.js --config specPattern='$(CYPRESS_SPEC_PATTERN)' --env API_PATH="$(RAZZLE_INTERNAL_API_PATH)" .PHONY: cypress-run -cypress-run: ## Run cypress integration tests - CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development CYPRESS_COVERAGE=true $(NODE_MODULES)/cypress/bin/cypress run --env coverage=true +cypress-run: ## Run Cypress tests headless + pnpm --filter @plone/volto exec cypress run --project $(CURRENT_DIR) --config-file $(CURRENT_DIR)/cypress.config.js --config specPattern='$(CYPRESS_SPEC_PATTERN)' --env API_PATH="$(RAZZLE_INTERNAL_API_PATH)" -.PHONY: test -test: ## Run jest tests - ${DOCKER_COMPOSE} run --no-deps -e CI=1 frontend test +.PHONY: cypress +cypress: cypress-run ## Run Cypress tests headless -.PHONY: test-update -test-update: ## Update jest tests snapshots - ${DOCKER_COMPOSE} run --no-deps -e CI=1 frontend test -u +.PHONY: test +test: ## Run unit tests + pnpm test -.PHONY: stylelint -stylelint: ## Stylelint - $(NODE_MODULES)/.bin/stylelint --allow-empty-input 'src/**/*.{css,less}' +.PHONY: i18n +i18n: ## Extract and compile translations + pnpm i18n -.PHONY: stylelint-overrides -stylelint-overrides: - $(NODE_MODULES)/.bin/stylelint --custom-syntax less --allow-empty-input 'theme/**/*.overrides' 'src/**/*.overrides' +.PHONY: lint +lint: ## ESLint check + pnpm lint -.PHONY: stylelint-fix -stylelint-fix: ## Fix stylelint - $(NODE_MODULES)/.bin/stylelint --allow-empty-input 'src/**/*.{css,less}' --fix - $(NODE_MODULES)/.bin/stylelint --custom-syntax less --allow-empty-input 'theme/**/*.overrides' 'src/**/*.overrides' --fix +.PHONY: lint-fix +lint-fix: ## ESLint fix + pnpm lint:fix .PHONY: prettier -prettier: ## Prettier - $(NODE_MODULES)/.bin/prettier --single-quote --check 'src/**/*.{js,jsx,json,css,less,md}' +prettier: ## Prettier check + pnpm prettier .PHONY: prettier-fix -prettier-fix: ## Fix prettier - $(NODE_MODULES)/.bin/prettier --single-quote --write 'src/**/*.{js,jsx,json,css,less,md}' +prettier-fix: ## Prettier fix + pnpm prettier:fix -.PHONY: lint -lint: ## ES Lint - $(NODE_MODULES)/.bin/eslint --max-warnings=0 'src/**/*.{js,jsx}' - -.PHONY: lint-fix -lint-fix: ## Fix ES Lint - $(NODE_MODULES)/.bin/eslint --fix 'src/**/*.{js,jsx}' - -.PHONY: i18n -i18n: ## i18n - rm -rf build/messages - NODE_ENV=development $(NODE_MODULES)/.bin/i18n --addon +.PHONY: stylelint +stylelint: ## Stylelint check + pnpm stylelint -.PHONY: help -help: ## Show this help. - @echo -e "$$(grep -hE '^\S+:.*##' $(MAKEFILE_LIST) | sed -e 's/:.*##\s*/:/' -e 's/^\(.\+\):\(.*\)/\\x1b[36m\1\\x1b[m:\2/' | column -c2 -t -s :)" - head -n 14 Makefile +.PHONY: stylelint-fix +stylelint-fix: ## Stylelint fix + pnpm stylelint:fix .PHONY: ci-fix -ci-fix: - echo "Running lint-fix" - make lint-fix - echo "Running prettier-fix" - make prettier-fix - echo "Running stylelint-fix" - make stylelint-fix +ci-fix: ## Fix code style (used by CI) + pnpm lint:fix + pnpm prettier:fix + pnpm stylelint:fix .PHONY: test-ci -test-ci: - cd /app - RAZZLE_JEST_CONFIG=src/addons/${ADDON_PATH}/jest-addon.config.js CI=true yarn test src/addons/${ADDON_PATH}/src --watchAll=false --reporters=default --reporters=jest-junit --collectCoverage --coverageReporters lcov cobertura text +test-ci: ## Run unit tests in CI + VOLTOCONFIG=$(CURRENT_DIR)/volto.config.js pnpm --filter @plone/volto i18n + CI=1 pnpm run test --passWithNoTests --coverage --coverage.reporter=lcov --coverage.reporter=text --reporter=junit --outputFile=junit.xml .PHONY: start-ci -start-ci: - cp .coverage.babel.config.js /app/babel.config.js - cd ../.. - RAZZLE_CI=true yarn start +start-ci: ## Start frontend in production mode (used by CI) + # Instrument the build (babel-plugin-istanbul) so Cypress can collect + # end-to-end coverage; the original babel config is restored on exit. + # RAZZLE_CI gates the demo block registration in packages/volto-object-widget/src/index.js, + # which the integration tests rely on. + cp core/packages/volto/babel.config.js core/packages/volto/babel.config.js.orig + trap 'mv -f core/packages/volto/babel.config.js.orig core/packages/volto/babel.config.js' EXIT + cp .coverage.babel.config.js core/packages/volto/babel.config.js + RAZZLE_CI=true pnpm build + RAZZLE_CI=true pnpm start:prod .PHONY: check-ci -check-ci: - $(NODE_MODULES)/.bin/wait-on -t 240000 http://localhost:3000 +check-ci: ## Wait for frontend to be ready + @timeout 600 bash -c 'until (echo > /dev/tcp/localhost/3000) 2>/dev/null; do sleep 2; done' .PHONY: cypress-ci -cypress-ci: - $(NODE_MODULES)/.bin/wait-on -t 240000 http://localhost:3000 - CYPRESS_API_PATH="${RAZZLE_DEV_PROXY_API_PATH}" NODE_ENV=development RAZZLE_CI=true $(NODE_MODULES)/cypress/bin/cypress run --browser electron +cypress-ci: ## Run Cypress tests headless (used by CI) + pnpm --filter @plone/volto exec cypress run --project $(CURRENT_DIR) --config-file $(CURRENT_DIR)/cypress.config.js --config specPattern='$(CYPRESS_SPEC_PATTERN)' --env API_PATH="$(RAZZLE_INTERNAL_API_PATH)" --browser chromium + +.PHONY: help +help: ## Show this help. + @echo -e "$$(grep -hE '^\S+:.*##' $(MAKEFILE_LIST) | sed -e 's/:.*##\s*/:/' -e 's/^\(.\+\):\(.*\)/\\x1b[36m\1\\x1b[m:\2/' | column -c2 -t -s :)" + @head -n 18 Makefile diff --git a/README.md b/README.md index 32775ef..67fa32b 100644 --- a/README.md +++ b/README.md @@ -1,245 +1,25 @@ # volto-object-widget [![Releases](https://img.shields.io/github/v/release/eea/volto-object-widget)](https://github.com/eea/volto-object-widget/releases) - [![Pipeline](https://ci.eionet.europa.eu/buildStatus/icon?job=volto-addons%2Fvolto-object-widget%2Fmaster&subject=master)](https://ci.eionet.europa.eu/view/Github/job/volto-addons/job/volto-object-widget/job/master/display/redirect) -[![Lines of Code](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=ncloc)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) [![Coverage](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=coverage)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) -[![Bugs](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=bugs)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) -[![Duplicated Lines (%)](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=duplicated_lines_density)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) - -[![Pipeline](https://ci.eionet.europa.eu/buildStatus/icon?job=volto-addons%2Fvolto-object-widget%2Fdevelop&subject=develop)](https://ci.eionet.europa.eu/view/Github/job/volto-addons/job/volto-object-widget/job/develop/display/redirect) -[![Lines of Code](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&branch=develop&metric=ncloc)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget&branch=develop) -[![Coverage](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&branch=develop&metric=coverage)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget&branch=develop) -[![Bugs](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&branch=develop&metric=bugs)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget&branch=develop) -[![Duplicated Lines (%)](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&branch=develop&metric=duplicated_lines_density)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget&branch=develop) [Volto](https://github.com/plone/volto) add-on: Various Volto schema-based widgets. -## Features - -This Volto addon provides several "abstract" widgets, to allow complex -information to be editable by the schema-based forms. It centers around the -concept: "we can create a form to edit a JSON object by using a schema" and so -it provides, right now, widgets to edit "list of JSON objects", a "mapping of -JSON objects" and a single "JSON object, but I choose the schema for it". - -### FlatListObject - -![Flat List object](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/flat-list-widget.png) - -This widget allows you to edit a list of objects by creating, editing and -deleting instances of objects editable with the provided `schema` parameter. -The list is sortable with drag&drop. You can also provide a schema extender, -a function with signature `(schema, data) => schema`, which will adjust, per -instance of object, its schema. To use this widget, in the schema, set the -`widget` field to `object_list_inline`. - -Example of how the data could look like for a block: - -``` -"a55c5053-ba81-4f73-ab29-7cdea74df20f": { - "@type": "dataTable", - "columns": [ - { - "@id": "f899ca76-68be-4ded-aa0b-669c04c27309", - "column": " PERC_HA_07\n(in %)", - "renderer": "progress", - "title": "21" - }, - { - "@id": "94315c5a-e031-4b7e-acb2-93887878a252", - "column": " PERC_HA_07\n(in %)", - "title": "12" - } - ], -} -``` - -The `columns` field, in this case, is data generated by the `FlatListObject`. -The schema for this field could look like (`ColumnSchema()` just generates -another instance of a schema, suitable for the `column` definition of our -specific use case): - -``` -columns: { - title: 'Columns', - description: 'Leave empty to show all columns', - schema: ColumnSchema(), - widget: 'object_list_inline', -}, -``` - -### Mapping Widget - -![Mapping widget](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/mapping-widget.png) - -This widget allows editing the properties of an object. For example, in the -following block data, the `row_colors` value is generated by an instance of the -`MappingWidget`. - -``` -"4430a32a-a266-497b-88e7-72fead5ab718": { - "@type": "dottedTableChart", - "column_data": "habitat_group", - "row_colors": { - "Bad": "#ed1834", - "F - Heathland, scrub and tundra": "#88c24f", - "Good": "#3c8000", - "Poor": "#f2a70e", - "Unknown": "#8d8d8d" - }, - "row_data": "assessment", - "size_data": "quantity" -}, -``` - -You need to provide the `options`, which is a list of objects with `{id, title}` and the `field_props`, which are parameters for the actual field that -will be used to edit the values. In our case the schema definition that was -used to edit the above value is (note, the options are empty, we're populating -them in the edit component, before passing the schema to the form): - -``` -row_colors: { - title: 'Colors', - widget: 'option_mapping', - field_props: { - widget: 'simple_color', - available_colors: settings.available_colors, - }, - options: [], -} -``` - -To use this widget, in the schema, set the `widget` field to `option_mapping`. - -### Object by type - -![Object by type](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/object-by-type-widget.png) - -With this widget you can choose the type of value that will be used, from -a predefined list of schemas. A schema that would use this type of widget could -look like: - -``` -const LinkEditSchema = { - title: 'Link', - fieldsets: [ - { - id: 'default', - title: 'Default', - fields: ['link'], - }, - ], - properties: { - link: { - title: 'Link', - widget: 'object_by_type', - schemas: [ - { - id: 'internal', - icon: internalSVG, - schema: InternalLinkSchema, - }, - { - id: 'external', - icon: externalSVG, - schema: ExternalLinkSchema, - }, - { - id: 'email', - icon: emailSVG, - schema: EmailLinkSchema, - }, - ], - }, - }, - required: [], -}; -``` - -To use this widget, in the schema, set the `widget` field to `object_by_type`. - -## Getting started +The add-on package lives in [`packages/volto-object-widget`](packages/volto-object-widget), +its [README](packages/volto-object-widget/README.md) documents installation and usage. -### Try volto-object-widget with Docker +## Development - git clone https://github.com/eea/volto-object-widget.git - cd volto-object-widget - make - make start - -Go to http://localhost:3000 - -`make start` now defaults to Volto 18. To run the same setup against Volto 17, use: - - VOLTO_VERSION=17 make - VOLTO_VERSION=17 make start - -### Add volto-object-widget to your Volto project - -1. Make sure you have a [Plone backend](https://plone.org/download) up-and-running at http://localhost:8080/Plone - - ```Bash - docker compose up backend - ``` - -1. Start Volto frontend - -* If you already have a volto project, just update `package.json`: - - ```JSON - "dependencies": { - "@eeacms/volto-object-widget": "*" - } - ``` - - and `volto.config.js`: - - ```JavaScript - const addons = ['@eeacms/volto-object-widget']; - ``` - -* If not, create one with Cookieplone, as recommended by the official Plone documentation for Volto 18+: - - ``` - uvx cookieplone project - cd project-title - ``` - -1. Install or update dependencies, then start the project: - - ``` - make install - ``` - - For a Cookieplone project, start the backend and frontend in separate terminals: - - ``` - make backend-start - make frontend-start - ``` - - For a legacy Volto 17 project, install the package with `yarn` and restart the frontend as usual. - -1. Go to http://localhost:3000 - -1. Happy editing! +See [DEVELOP.md](DEVELOP.md). ## Release -See [RELEASE.md](https://github.com/eea/volto-object-widget/blob/master/RELEASE.md). - -## How to contribute - -See [DEVELOP.md](https://github.com/eea/volto-object-widget/blob/master/DEVELOP.md). - -## Copyright and license +See [RELEASE.md](RELEASE.md). -The Initial Owner of the Original Code is European Environment Agency (EEA). -All Rights Reserved. +## License -See [LICENSE.md](https://github.com/eea/volto-object-widget/blob/master/LICENSE.md) for details. +See [LICENSE.md](LICENSE.md) for details. ## Funding diff --git a/RELEASE.md b/RELEASE.md index 4e311a0..27baae1 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -33,7 +33,7 @@ Release-it is a tool that automates 4 important steps in the release process: To configure the authentification, you need to export GITHUB_TOKEN for [GitHub](https://github.com/settings/tokens) ``` - export GITHUB_TOKEN=XXX-XXXXXXXXXXXXXXXXXXXXXX + export GITHUB_TOKEN="${GITHUB_TOKEN}" ``` To configure npm, you can use the `npm login` command or use a configuration file with a TOKEN : diff --git a/babel.config.js b/babel.config.js deleted file mode 100644 index 51bd52b..0000000 --- a/babel.config.js +++ /dev/null @@ -1,17 +0,0 @@ -module.exports = function (api) { - api.cache(true); - const presets = ['razzle']; - const plugins = [ - [ - 'react-intl', // React Intl extractor, required for the whole i18n infrastructure to work - { - messagesDir: './build/messages/', - }, - ], - ]; - - return { - plugins, - presets, - }; -}; diff --git a/bootstrap b/bootstrap deleted file mode 100644 index 8613750..0000000 --- a/bootstrap +++ /dev/null @@ -1,41 +0,0 @@ -const path = require('path'); -const fs = require('fs'); -const ejs = require('ejs'); - -const currentDir = path.basename(process.cwd()); - -const bootstrap = function (ofile) { - fs.readFile(ofile, 'utf8', function (err, data) { - if (err) { - return console.log(err); - } - const result = ejs.render(data, { - addonName: `@eeacms/${currentDir}`, - name: currentDir - }); - const output = ofile.replace('.tpl', ''); - fs.writeFile(output, result, 'utf8', function (err) { - if (err) { - return console.log(err); - } - }); - if (ofile.includes('.tpl')) { - fs.unlink(ofile, (err) => { - if (err) { - return console.error(err); - } - }); - } - }); -} - -fs.readdir(".", { withFileTypes: true }, (err, dirents) => { - const files = dirents - .filter(dirent => dirent.isFile()) - .map(dirent => dirent.name); - files.forEach(function (file) { - if (file != 'bootstrap') { - bootstrap(file); - } - }); -}); diff --git a/cypress.config.js b/cypress.config.js index 7a9e0be..3fd03ff 100644 --- a/cypress.config.js +++ b/cypress.config.js @@ -2,25 +2,28 @@ const { defineConfig } = require('cypress'); module.exports = defineConfig({ viewportWidth: 1280, - defaultCommandTimeout: 8888, - chromeWebSecurity: false, - reporter: 'junit', - video: false, + viewportHeight: 1280, retries: { - runMode: 2, - openMode: 0, + runMode: 3, }, + // JUnit reporter so the EEA Jenkinsfile can publish Cypress results + // (it copies cypress/reports/*.xml via `junit testResults: 'cypress-results-current/**/*.xml'`). + reporter: 'junit', reporterOptions: { mochaFile: 'cypress/reports/cypress-[hash].xml', jenkinsMode: true, toConsole: true, }, e2e: { + // Register the code-coverage task so cypress/support/e2e.js's + // `@cypress/code-coverage/support` has somewhere to send coverage to. + // Coverage is only collected when the frontend is built/started with + // babel-plugin-istanbul instrumentation (see Makefile `start-ci`). setupNodeEvents(on, config) { - // e2e testing node events setup code require('@cypress/code-coverage/task')(on, config); return config; }, baseUrl: 'http://localhost:3000', + specPattern: 'cypress/tests/**/*.cy.{js,jsx,ts,tsx}', }, }); diff --git a/cypress/support/commands.js b/cypress/support/commands.js index 8b091db..13c1161 100644 --- a/cypress/support/commands.js +++ b/cypress/support/commands.js @@ -8,14 +8,14 @@ Cypress.Commands.add('autologin', () => { let api_url, user, password; api_url = Cypress.env('API_PATH') || 'http://localhost:8080/Plone'; user = 'admin'; - password = 'admin'; + password = 'admin'; //betterleaks:allow return cy .request({ method: 'POST', url: `${api_url}/@login`, headers: { Accept: 'application/json' }, - body: { login: user, password: password }, + body: { login: user, password: password }, //betterleaks:allow }) .then((response) => cy.setCookie('auth_token', response.body.token)); }); diff --git a/cypress/support/e2e.js b/cypress/support/e2e.js index bc4138a..0c05bcf 100644 --- a/cypress/support/e2e.js +++ b/cypress/support/e2e.js @@ -40,9 +40,11 @@ export const slateBeforeEach = (contentType = 'Document') => { contentTitle: 'My Image', path: 'cypress/my-page', }); - cy.visit('/cypress/my-page'); - cy.waitForResourceToLoad('my-page'); - cy.navigate('/cypress/my-page/edit'); + // Load the edit route directly instead of pushing it through the SPA + // history: an appHistory push can race with the client hydration, which + // then settles back on the server-rendered view URL and the edit UI + // (including the title editor) never mounts. + cy.visit('/cypress/my-page/edit'); }; export const slateAfterEach = () => { diff --git a/cypress/e2e/01-attached-image-widget-external-url.cy.js b/cypress/tests/01-attached-image-widget-external-url.cy.js similarity index 100% rename from cypress/e2e/01-attached-image-widget-external-url.cy.js rename to cypress/tests/01-attached-image-widget-external-url.cy.js diff --git a/cypress/e2e/02-attached-image-widget-internal-url.cy.js b/cypress/tests/02-attached-image-widget-internal-url.cy.js similarity index 100% rename from cypress/e2e/02-attached-image-widget-internal-url.cy.js rename to cypress/tests/02-attached-image-widget-internal-url.cy.js diff --git a/cypress/e2e/03-attached-image-widget-clear-url.cy.js b/cypress/tests/03-attached-image-widget-clear-url.cy.js similarity index 100% rename from cypress/e2e/03-attached-image-widget-clear-url.cy.js rename to cypress/tests/03-attached-image-widget-clear-url.cy.js diff --git a/cypress/e2e/04-attached-image-widget-submit-disabled.cy.js b/cypress/tests/04-attached-image-widget-submit-disabled.cy.js similarity index 100% rename from cypress/e2e/04-attached-image-widget-submit-disabled.cy.js rename to cypress/tests/04-attached-image-widget-submit-disabled.cy.js diff --git a/cypress/e2e/05-attached-image-widget-object-browser.cy.js b/cypress/tests/05-attached-image-widget-object-browser.cy.js similarity index 100% rename from cypress/e2e/05-attached-image-widget-object-browser.cy.js rename to cypress/tests/05-attached-image-widget-object-browser.cy.js diff --git a/cypress/e2e/06-attached-image-widget-preview-clear.cy.js b/cypress/tests/06-attached-image-widget-preview-clear.cy.js similarity index 100% rename from cypress/e2e/06-attached-image-widget-preview-clear.cy.js rename to cypress/tests/06-attached-image-widget-preview-clear.cy.js diff --git a/cypress/e2e/07-attached-image-widget-upload-loading.cy.js b/cypress/tests/07-attached-image-widget-upload-loading.cy.js similarity index 100% rename from cypress/e2e/07-attached-image-widget-upload-loading.cy.js rename to cypress/tests/07-attached-image-widget-upload-loading.cy.js diff --git a/cypress/e2e/08-attached-image-widget-dragging-state.cy.js b/cypress/tests/08-attached-image-widget-dragging-state.cy.js similarity index 100% rename from cypress/e2e/08-attached-image-widget-dragging-state.cy.js rename to cypress/tests/08-attached-image-widget-dragging-state.cy.js diff --git a/cypress/e2e/09-attached-image-widget-conflict-dialog.cy.js b/cypress/tests/09-attached-image-widget-conflict-dialog.cy.js similarity index 100% rename from cypress/e2e/09-attached-image-widget-conflict-dialog.cy.js rename to cypress/tests/09-attached-image-widget-conflict-dialog.cy.js diff --git a/cypress/e2e/10-attached-image-widget-replace-existing.cy.js b/cypress/tests/10-attached-image-widget-replace-existing.cy.js similarity index 100% rename from cypress/e2e/10-attached-image-widget-replace-existing.cy.js rename to cypress/tests/10-attached-image-widget-replace-existing.cy.js diff --git a/cypress/e2e/11-attached-image-widget-use-existing.cy.js b/cypress/tests/11-attached-image-widget-use-existing.cy.js similarity index 100% rename from cypress/e2e/11-attached-image-widget-use-existing.cy.js rename to cypress/tests/11-attached-image-widget-use-existing.cy.js diff --git a/cypress/e2e/12-attached-image-widget-cancel-upload.cy.js b/cypress/tests/12-attached-image-widget-cancel-upload.cy.js similarity index 100% rename from cypress/e2e/12-attached-image-widget-cancel-upload.cy.js rename to cypress/tests/12-attached-image-widget-cancel-upload.cy.js diff --git a/cypress/tsconfig.json b/cypress/tsconfig.json new file mode 100644 index 0000000..74b7cb3 --- /dev/null +++ b/cypress/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "target": "es5", + "lib": ["es5", "dom"], + "types": ["cypress", "@testing-library/cypress", "node"] + }, + "include": ["**/*.ts"] +} diff --git a/docker-compose.yml b/docker-compose.yml index 18afc2e..9ebce08 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -1,33 +1,8 @@ -version: '3' services: backend: image: eeacms/plone-backend ports: - - '8080:8080' + - "8080:8080" environment: - SITE: 'Plone' - PROFILES: 'eea.kitkat:testing' - - frontend: - build: - context: ./ - dockerfile: ./Dockerfile - args: - ADDON_NAME: '${ADDON_NAME}' - ADDON_PATH: '${ADDON_PATH}' - VOLTO_VERSION: ${VOLTO_VERSION:-18-yarn} - ports: - - '3000:3000' - - '3001:3001' - depends_on: - - backend - volumes: - - ./:/app/src/addons/${ADDON_PATH} - environment: - RAZZLE_CI: 'true' - CI: 'true' - NODE_ENV: 'development' - RAZZLE_JEST_CONFIG: 'src/addons/${ADDON_PATH}/jest-addon.config.js' - RAZZLE_INTERNAL_API_PATH: 'http://backend:8080/Plone' - RAZZLE_DEV_PROXY_API_PATH: 'http://backend:8080/Plone' - HOST: '0.0.0.0' + SITE: "Plone" + PROFILES: "eea.kitkat:testing" diff --git a/jest-addon.config.js b/jest-addon.config.js deleted file mode 100644 index 477a6a9..0000000 --- a/jest-addon.config.js +++ /dev/null @@ -1,469 +0,0 @@ -/** - * Generic Jest configuration for Volto addons - * - * This configuration automatically: - * - Detects the addon name from the config file path - * - Configures test coverage to focus on the specific test path - * - Handles different ways of specifying test paths: - * - Full paths like src/addons/addon-name/src/components - * - Just filenames like Component.test.jsx - * - Just directory names like components - * - * Usage: - * RAZZLE_JEST_CONFIG=src/addons/addon-name/jest-addon.config.js CI=true yarn test [test-path] --collectCoverage - */ - -require('dotenv').config({ path: __dirname + '/.env' }); - -const path = require('path'); -const fs = require('fs'); -const fg = require('fast-glob'); - -const voltoSlatePath = fs.existsSync( - path.join(__dirname, '../../../node_modules/@plone/volto-slate/src'), -) - ? '/node_modules/@plone/volto-slate/src' - : '/node_modules/@plone/volto/packages/volto-slate/src'; - -// Get the addon name from the current file path -const pathParts = __filename.split(path.sep); -const addonsIdx = pathParts.lastIndexOf('addons'); -const addonName = - addonsIdx !== -1 && addonsIdx < pathParts.length - 1 - ? pathParts[addonsIdx + 1] - : path.basename(path.dirname(__filename)); // Fallback to folder name -const addonBasePath = `src/addons/${addonName}/src`; - -// --- Performance caches --- -const fileSearchCache = new Map(); -const dirSearchCache = new Map(); -const dirListingCache = new Map(); -const statCache = new Map(); -const implementationCache = new Map(); - -/** - * Cached fs.statSync wrapper to avoid redundant filesystem calls - * @param {string} p - * @returns {fs.Stats|null} - */ -const getStatSync = (p) => { - if (statCache.has(p)) return statCache.get(p); - try { - const s = fs.statSync(p); - statCache.set(p, s); - return s; - } catch { - statCache.set(p, null); - return null; - } -}; - -/** - * Find files that match a specific pattern using fast-glob - * @param {string} baseDir - The base directory to search in - * @param {string} fileName - The name of the file to find - * @param {string} [pathPattern=''] - Optional path pattern to filter results - * @returns {string[]} - Array of matching file paths - */ -const findFilesWithPattern = (baseDir, fileName, pathPattern = '') => { - const cacheKey = `${baseDir}|${fileName}|${pathPattern}`; - if (fileSearchCache.has(cacheKey)) { - return fileSearchCache.get(cacheKey); - } - - let files = []; - try { - const patterns = fileName - ? [`${baseDir}/**/${fileName}`] - : [`${baseDir}/**/*.{js,jsx,ts,tsx}`]; - - files = fg.sync(patterns, { onlyFiles: true }); - - if (pathPattern) { - files = files.filter((file) => file.includes(pathPattern)); - } - } catch { - files = []; - } - - fileSearchCache.set(cacheKey, files); - return files; -}; - -/** - * Find directories that match a specific pattern using fast-glob - * @param {string} baseDir - The base directory to search in - * @param {string} dirName - The name of the directory to find - * @param {string} [pathPattern=''] - Optional path pattern to filter results - * @returns {string[]} - Array of matching directory paths - */ -const findDirsWithPattern = (baseDir, dirName, pathPattern = '') => { - const cacheKey = `${baseDir}|${dirName}|${pathPattern}`; - if (dirSearchCache.has(cacheKey)) { - return dirSearchCache.get(cacheKey); - } - - let dirs = []; - try { - const patterns = dirName - ? [`${baseDir}/**/${dirName}`] - : [`${baseDir}/**/`]; - - dirs = fg.sync(patterns, { onlyDirectories: true }); - - if (pathPattern) { - dirs = dirs.filter((dir) => dir.includes(pathPattern)); - } - } catch { - dirs = []; - } - - dirSearchCache.set(cacheKey, dirs); - return dirs; -}; - -/** - * Find files or directories in the addon using fast-glob - * @param {string} name - The name to search for - * @param {string} type - The type of item to find ('f' for files, 'd' for directories) - * @param {string} [additionalOptions=''] - Additional options for flexible path matching - * @returns {string|null} - The path of the found item or null if not found - */ -const findInAddon = (name, type, additionalOptions = '') => { - const isFile = type === 'f'; - const isDirectory = type === 'd'; - const isFlexiblePathMatch = additionalOptions.includes('-path'); - - let pathPattern = ''; - if (isFlexiblePathMatch) { - const match = additionalOptions.match(/-path "([^"]+)"/); - if (match && match[1]) { - pathPattern = match[1].replace(/\*/g, ''); - } - } - - try { - let results = []; - if (isFile) { - results = findFilesWithPattern(addonBasePath, name, pathPattern); - } else if (isDirectory) { - results = findDirsWithPattern(addonBasePath, name, pathPattern); - } - return results.length > 0 ? results[0] : null; - } catch (error) { - return null; - } -}; - -/** - * Find the implementation file for a test file - * @param {string} testPath - Path to the test file - * @returns {string|null} - Path to the implementation file or null if not found - */ -const findImplementationFile = (testPath) => { - if (implementationCache.has(testPath)) { - return implementationCache.get(testPath); - } - - if (!fs.existsSync(testPath)) { - implementationCache.set(testPath, null); - return null; - } - - const dirPath = path.dirname(testPath); - const fileName = path.basename(testPath); - - // Regex for common test file patterns (e.g., .test.js, .spec.ts) - const TEST_OR_SPEC_FILE_REGEX = /\.(test|spec)\.[jt]sx?$/; - - if (!TEST_OR_SPEC_FILE_REGEX.test(fileName)) { - implementationCache.set(testPath, null); - return null; - } - - const baseFileName = path - .basename(fileName, path.extname(fileName)) - .replace(/\.(test|spec)$/, ''); // Remove .test or .spec - - let dirFiles = dirListingCache.get(dirPath); - if (!dirFiles) { - dirFiles = fs.readdirSync(dirPath); - dirListingCache.set(dirPath, dirFiles); - } - - const exactMatch = dirFiles.find((file) => { - const fileBaseName = path.basename(file, path.extname(file)); - return ( - fileBaseName === baseFileName && !TEST_OR_SPEC_FILE_REGEX.test(file) // Ensure it's not another test/spec file - ); - }); - - if (exactMatch) { - const result = `${dirPath}/${exactMatch}`; - implementationCache.set(testPath, result); - return result; - } - - const similarMatch = dirFiles.find((file) => { - if ( - TEST_OR_SPEC_FILE_REGEX.test(file) || - (getStatSync(`${dirPath}/${file}`)?.isDirectory() ?? false) - ) { - return false; - } - const fileBaseName = path.basename(file, path.extname(file)); - return ( - fileBaseName.toLowerCase().includes(baseFileName.toLowerCase()) || - baseFileName.toLowerCase().includes(fileBaseName.toLowerCase()) - ); - }); - - if (similarMatch) { - const result = `${dirPath}/${similarMatch}`; - implementationCache.set(testPath, result); - return result; - } - - implementationCache.set(testPath, null); - return null; -}; - -/** - * Get the test path from command line arguments - * @returns {string|null} - The resolved test path or null if not found - */ -const getTestPath = () => { - const args = process.argv; - let testPath = null; - const TEST_FILE_REGEX = /\.test\.[jt]sx?$/; // Matches .test.js, .test.jsx, .test.ts, .test.tsx - - testPath = args.find( - (arg) => - arg.includes(addonName) && - !arg.startsWith('--') && - arg !== 'test' && - arg !== 'node', - ); - - if (!testPath) { - const testIndex = args.findIndex((arg) => arg === 'test'); - if (testIndex !== -1 && testIndex < args.length - 1) { - const nextArg = args[testIndex + 1]; - if (!nextArg.startsWith('--')) { - testPath = nextArg; - } - } - } - - if (!testPath) { - testPath = args.find((arg) => TEST_FILE_REGEX.test(arg)); - } - - if (!testPath) { - return null; - } - - if (!testPath.includes(path.sep)) { - if (TEST_FILE_REGEX.test(testPath)) { - const foundTestFile = findInAddon(testPath, 'f'); - if (foundTestFile) { - return foundTestFile; - } - } else { - const foundDir = findInAddon(testPath, 'd'); - if (foundDir) { - return foundDir; - } - const flexibleDir = findInAddon(testPath, 'd', `-path "*${testPath}*"`); - if (flexibleDir) { - return flexibleDir; - } - } - } else if ( - TEST_FILE_REGEX.test(testPath) && // Check if it looks like a test file path - !testPath.startsWith('src/addons/') - ) { - const testFileName = path.basename(testPath); - const foundTestFile = findInAddon(testFileName, 'f'); - if (foundTestFile) { - const relativePath = path.dirname(testPath); - if (foundTestFile.includes(relativePath)) { - return foundTestFile; - } - const similarFiles = findFilesWithPattern( - addonBasePath, - testFileName, - relativePath, - ); - if (similarFiles && similarFiles.length > 0) { - return similarFiles[0]; - } - } - } - - if ( - !path - .normalize(testPath) - .startsWith(path.join('src', 'addons', addonName, 'src')) && - !path.isAbsolute(testPath) // Use path.isAbsolute for robust check - ) { - testPath = path.join(addonBasePath, testPath); // Use path.join for OS-agnostic paths - } - - if (fs.existsSync(testPath)) { - return testPath; - } - - const pathWithoutTrailingSlash = testPath.endsWith(path.sep) - ? testPath.slice(0, -1) - : null; - if (pathWithoutTrailingSlash && fs.existsSync(pathWithoutTrailingSlash)) { - return pathWithoutTrailingSlash; - } - - const pathWithTrailingSlash = !testPath.endsWith(path.sep) - ? testPath + path.sep - : null; - if (pathWithTrailingSlash && fs.existsSync(pathWithTrailingSlash)) { - // Generally, return paths without trailing slashes for consistency, - // unless it's specifically needed for a directory that only exists with it (rare). - return testPath; - } - return testPath; // Return the original path if no variations exist -}; - -/** - * Determine collectCoverageFrom patterns based on test path - * @returns {string[]} - Array of coverage patterns - */ -const getCoveragePatterns = () => { - const excludePatterns = [ - '!src/**/*.d.ts', - '!**/*.test.{js,jsx,ts,tsx}', - '!**/*.spec.{js,jsx,ts,tsx}', - ]; - - const defaultPatterns = [ - `${addonBasePath}/**/*.{js,jsx,ts,tsx}`, - ...excludePatterns, - ]; - - const ANY_SCRIPT_FILE_REGEX = /\.[jt]sx?$/; - - const directoryArg = process.argv.find( - (arg) => - !arg.includes(path.sep) && - !arg.startsWith('--') && - arg !== 'test' && - arg !== 'node' && - !ANY_SCRIPT_FILE_REGEX.test(arg) && - ![ - 'yarn', - 'npm', - 'npx', - 'collectCoverage', - 'CI', - 'RAZZLE_JEST_CONFIG', - ].some( - (reserved) => - arg === reserved || arg.startsWith(reserved.split('=')[0] + '='), - ) && - process.argv.indexOf(arg) > - process.argv.findIndex((item) => item === 'test'), - ); - - if (directoryArg) { - const foundDir = findInAddon(directoryArg, 'd'); - if (foundDir) { - return [`${foundDir}/**/*.{js,jsx,ts,tsx}`, ...excludePatterns]; - } - } - - let testPath = getTestPath(); - - if (!testPath) { - return defaultPatterns; - } - - if (testPath.endsWith(path.sep)) { - testPath = testPath.slice(0, -1); - } - - const stats = getStatSync(testPath); - - if (stats && stats.isFile()) { - const implFile = findImplementationFile(testPath); - if (implFile) { - return [implFile, '!src/**/*.d.ts']; - } - const dirPath = path.dirname(testPath); - return [`${dirPath}/**/*.{js,jsx,ts,tsx}`, ...excludePatterns]; - } else if (stats && stats.isDirectory()) { - return [`${testPath}/**/*.{js,jsx,ts,tsx}`, ...excludePatterns]; - } - - return defaultPatterns; -}; - -const coverageConfig = getCoveragePatterns(); - -module.exports = { - testMatch: ['**/src/addons/**/?(*.)+(spec|test).[jt]s?(x)'], - collectCoverageFrom: coverageConfig, - coveragePathIgnorePatterns: [ - '/node_modules/', - 'schema\\.[jt]s?$', - 'index\\.[jt]s?$', - 'config\\.[jt]sx?$', - ], - moduleNameMapper: { - '\\.(css|less|scss|sass)$': 'identity-obj-proxy', - '@plone/volto/cypress': '/node_modules/@plone/volto/cypress', - '@plone/volto/babel': '/node_modules/@plone/volto/babel', - '@plone/volto/(.*)$': '/node_modules/@plone/volto/src/$1', - '@package/(.*)$': '/node_modules/@plone/volto/src/$1', - '@root/(.*)$': '/node_modules/@plone/volto/src/$1', - '@plone/volto-quanta/(.*)$': '/src/addons/volto-quanta/src/$1', - '@eeacms/search/(.*)$': '/src/addons/volto-searchlib/searchlib/$1', - '@eeacms/search': '/src/addons/volto-searchlib/searchlib', - '@eeacms/(.*?)/(.*)$': '/node_modules/@eeacms/$1/src/$2', - '@plone/volto-slate$': voltoSlatePath, - '@plone/volto-slate/(.*)$': `${voltoSlatePath}/$1`, - '~/(.*)$': '/src/$1', - 'load-volto-addons': - '/node_modules/@plone/volto/jest-addons-loader.js', - }, - transformIgnorePatterns: [ - '/node_modules/(?!(@plone|@root|@package|@eeacms)/).*/', - ], - transform: { - '^.+\\.js(x)?$': 'babel-jest', - '^.+\\.ts(x)?$': 'babel-jest', - '^.+\\.(png)$': 'jest-file', - '^.+\\.(jpg)$': 'jest-file', - '^.+\\.(svg)$': './node_modules/@plone/volto/jest-svgsystem-transform.js', - }, - coverageThreshold: { - global: { - branches: 5, - functions: 5, - lines: 5, - statements: 5, - }, - }, - ...(process.env.JEST_USE_SETUP === 'ON' && { - setupFilesAfterEnv: [ - fs.existsSync( - path.join( - __dirname, - 'node_modules', - '@eeacms', - addonName, - 'jest.setup.js', - ), - ) - ? `/node_modules/@eeacms/${addonName}/jest.setup.js` - : `/src/addons/${addonName}/jest.setup.js`, - ], - }), -}; diff --git a/jest.setup.js b/jest.setup.js deleted file mode 100644 index 85b16f7..0000000 --- a/jest.setup.js +++ /dev/null @@ -1,65 +0,0 @@ -import { jest } from '@jest/globals'; -import configureStore from 'redux-mock-store'; -import thunk from 'redux-thunk'; -import { blocksConfig } from '@plone/volto/config/Blocks'; -import installSlate from '@plone/volto-slate/index'; - -var mockSemanticComponents = jest.requireActual('semantic-ui-react'); -var mockComponents = jest.requireActual('@plone/volto/components'); -var config = jest.requireActual('@plone/volto/registry').default; - -config.blocks.blocksConfig = { - ...blocksConfig, - ...config.blocks.blocksConfig, -}; - -jest.doMock('semantic-ui-react', () => ({ - __esModule: true, - ...mockSemanticComponents, - Popup: ({ content, trigger }) => { - return ( -
-
{trigger}
-
{content}
-
- ); - }, -})); - -jest.doMock('@plone/volto/components', () => { - return { - __esModule: true, - ...mockComponents, - SidebarPortal: ({ children }) => , - }; -}); - -jest.doMock('@plone/volto/registry', () => - [installSlate].reduce((acc, apply) => apply(acc), config), -); - -const mockStore = configureStore([thunk]); - -global.fetch = jest.fn(() => - Promise.resolve({ - json: () => Promise.resolve({}), - }), -); - -global.store = mockStore({ - intl: { - locale: 'en', - messages: {}, - formatMessage: jest.fn(), - }, - content: { - create: {}, - subrequests: [], - }, - connected_data_parameters: {}, - screen: { - page: { - width: 768, - }, - }, -}); diff --git a/mrs.developer.json b/mrs.developer.json new file mode 100644 index 0000000..19fe64c --- /dev/null +++ b/mrs.developer.json @@ -0,0 +1,10 @@ +{ + "core": { + "output": "./", + "package": "@plone/volto", + "url": "git@github.com:plone/volto.git", + "https": "https://github.com/plone/volto.git", + "tag": "19.5.0", + "filterBlobs": true + } +} diff --git a/package.json b/package.json index 239532f..3c29b9a 100644 --- a/package.json +++ b/package.json @@ -1,11 +1,11 @@ { - "name": "@eeacms/volto-object-widget", - "version": "9.1.1", + "name": "@eeacms/volto-object-widget-dev", + "private": true, + "version": "10.0.0", "description": "volto-object-widget: Volto add-on", - "main": "src/index.js", "author": "European Environment Agency: IDM2 A-Team", - "license": "MIT", "homepage": "https://github.com/eea/volto-object-widget", + "license": "MIT", "keywords": [ "volto-addon", "volto-widget", @@ -13,63 +13,54 @@ "plone", "react" ], - "repository": { - "type": "git", - "url": "git@github.com:eea/volto-object-widget.git" + "scripts": { + "preinstall": "npx only-allow pnpm", + "start": "VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto start", + "start:prod": "pnpm --filter @plone/volto start:prod", + "build": "VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto build", + "build:deps": "pnpm --filter @plone/registry --filter @plone/components build", + "i18n": "pnpm --filter @eeacms/volto-object-widget i18n && VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto i18n", + "test": "pnpm --filter @eeacms/volto-object-widget exec vitest", + "lint": "VOLTOCONFIG=$(pwd)/volto.config.js eslint --max-warnings=0 'packages/**/src/**/*.{js,jsx,ts,tsx}'", + "lint:fix": "VOLTOCONFIG=$(pwd)/volto.config.js eslint --fix 'packages/**/src/**/*.{js,jsx,ts,tsx}'", + "prettier": "prettier --check 'packages/**/src/**/*.{js,jsx,ts,tsx}'", + "prettier:fix": "prettier --write 'packages/**/src/**/*.{js,jsx,ts,tsx}' ", + "stylelint": "stylelint 'packages/**/src/**/*.{css,scss,less}' --allow-empty-input", + "stylelint:fix": "stylelint 'packages/**/src/**/*.{css,scss,less}' --fix --allow-empty-input", + "dry-release": "pnpm --filter @eeacms/volto-object-widget dry-release", + "release": "pnpm --filter @eeacms/volto-object-widget release", + "release-major-alpha": "pnpm --filter @eeacms/volto-object-widget release-major-alpha", + "release-alpha": "pnpm --filter @eeacms/volto-object-widget release-alpha", + "storybook": "VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto storybook dev -p 6006 -c $(pwd)/.storybook", + "storybook-build": "VOLTOCONFIG=$(pwd)/volto.config.js pnpm --filter @plone/volto build-storybook -c $(pwd)/.storybook" }, "dependencies": { - "jsoneditor": "10.2.0" + "@plone/volto": "workspace:*", + "@plone/registry": "workspace:*", + "@eeacms/volto-object-widget": "workspace:*" }, "devDependencies": { - "@cypress/code-coverage": "^3.10.0", - "@plone/scripts": "^3.6.2", - "babel-plugin-transform-class-properties": "^6.24.1", - "cypress": "13.1.0", - "cypress-file-upload": "^5.0.8", - "dotenv": "^16.3.2", - "husky": "^8.0.3", - "lint-staged": "^14.0.1", - "md5": "^2.3.0" + "babel-plugin-istanbul": "^6.1.1", + "mrs-developer": "^2.2.0" }, - "lint-staged": { - "src/**/*.{js,jsx,ts,tsx,json}": [ - "make lint-fix", - "make prettier-fix" - ], - "src/**/*.{jsx}": [ - "make i18n" + "pnpm": { + "overrides": { + "@pmmmwh/react-refresh-webpack-plugin": "^0.5.15", + "react-refresh": "^0.14.2" + }, + "ignoredBuiltDependencies": [ + "@parcel/watcher" ], - "theme/**/*.{css,less}": [ - "make stylelint-fix" - ], - "src/**/*.{css,less}": [ - "make stylelint-fix" - ], - "theme/**/*.overrides": [ - "make stylelint-fix" - ], - "src/**/*.overrides": [ - "make stylelint-fix" + "onlyBuiltDependencies": [ + "core-js", + "core-js-pure", + "cypress", + "es5-ext", + "esbuild", + "full-icu", + "lightningcss-cli", + "unrs-resolver" ] }, - "scripts": { - "release": "release-it", - "release-major-beta": "release-it major --preRelease=beta", - "release-beta": "release-it --preRelease=beta", - "bootstrap": "npm install -g ejs; npm link ejs; node bootstrap", - "test": "make test", - "test:fix": "make test-update", - "pre-commit": "yarn stylelint:fix && yarn prettier:fix && yarn lint:fix", - "stylelint": "make stylelint", - "stylelint:overrides": "make stylelint-overrides", - "stylelint:fix": "make stylelint-fix", - "prettier": "make prettier", - "prettier:fix": "make prettier-fix", - "lint": "make lint", - "lint:fix": "make lint-fix", - "i18n": "make i18n", - "cypress:run": "make cypress-run", - "cypress:open": "make cypress-open", - "prepare": "husky install" - } + "packageManager": "pnpm@10.20.0" } diff --git a/packages/volto-object-widget/.env b/packages/volto-object-widget/.env new file mode 100644 index 0000000..1762bf3 --- /dev/null +++ b/packages/volto-object-widget/.env @@ -0,0 +1 @@ +VITEST_USE_SETUP=ON # Vitest configuration variables: ON, OFF diff --git a/packages/volto-object-widget/.npmignore b/packages/volto-object-widget/.npmignore new file mode 100644 index 0000000..080322a --- /dev/null +++ b/packages/volto-object-widget/.npmignore @@ -0,0 +1,96 @@ +# https://docs.npmjs.com/using-npm/developers.html#keeping-files-out-of-your-package + +# Directories +api/ +bin/ +build/ +lib/ +g-api/ +tests/ + +# Docs +docs/ + +# Cypress +cypress/ + +# Tests +__tests__/ +*.snap + +# Files +.travis.yml +requirements-docs.txt +requirements-tests.txt +yarn.lock +.dockerignore +.gitattributes +.yarnrc +.nvmrc +changelogupdater.js +pip-selfcheck.json +Dockerfile +CNAME +entrypoint.sh +Jenkinsfile +Makefile + +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* + +# Runtime data +pids +*.pid +*.seed +*.pid.lock + +# Directory for instrumented libs generated by jscoverage/JSCover +lib-cov + +# Coverage directory used by tools like istanbul +coverage + +# nyc test coverage +.nyc_output + +# node-waf configuration +.lock-wscript + +# Compiled binary addons (https://nodejs.org/api/addons.html) +build/Release + +# Dependency directories +node_modules/ +jspm_packages/ + +# TypeScript v1 declaration files +typings/ + +# Optional npm cache directory +.npm + +# Optional eslint cache +.eslintcache + +# Optional REPL history +.node_repl_history + +# Output of 'npm pack' +*.tgz + +# Yarn Integrity file +.yarn-integrity + +# dotenv environment variables file +.env + +# next.js build output +.next + +styleguide.config +.vscode +packages diff --git a/.release-it.json b/packages/volto-object-widget/.release-it.json similarity index 100% rename from .release-it.json rename to packages/volto-object-widget/.release-it.json diff --git a/CHANGELOG.md b/packages/volto-object-widget/CHANGELOG.md similarity index 79% rename from CHANGELOG.md rename to packages/volto-object-widget/CHANGELOG.md index b9228f9..ee2e6b2 100644 --- a/CHANGELOG.md +++ b/packages/volto-object-widget/CHANGELOG.md @@ -4,6 +4,19 @@ All notable changes to this project will be documented in this file. Dates are d Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). +### [10.0.0](https://github.com/eea/volto-object-widget/compare/9.1.1...10.0.0) - 19 November 2026 + +#### :rocket: New Features + +- feat: Volto 19 support - refs #297832 [dobri1408 - [`954b35f`](https://github.com/eea/volto-object-widget/commit/954b35f80537b4fc40cd01aa6789fa3f0ebd7808)] + +#### :bug: Bug Fixes + +- fix: Add betterleaks github action - refs #304517 [dobri1408 - [`dd7345f`](https://github.com/eea/volto-object-widget/commit/dd7345fa06c05c6b31db6445a4a0764721597eca)] + +#### :hammer_and_wrench: Others + +- test: pin Chromium version 149 to work with Cypress [valentinab25 - [`d4548ba`](https://github.com/eea/volto-object-widget/commit/d4548baced643a9bb58a1ac2e2b672ef2f3af639)] ### [9.1.1](https://github.com/eea/volto-object-widget/compare/9.1.0...9.1.1) - 28 April 2026 #### :bug: Bug Fixes @@ -40,11 +53,6 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - fix: make test [Alin V. (Claudiu) - [`1c762c0`](https://github.com/eea/volto-object-widget/commit/1c762c053d6e68ada30fb044e862bc3fc352ed17)] -#### :house: Internal changes - -- chore: [JENKINSFILE] add package version in sonarqube [valentinab25 - [`92483a5`](https://github.com/eea/volto-object-widget/commit/92483a5984fe178d8fb91af72487b61f78c76a17)] -- chore: [JENKINSFILE] use sonarqube branches [EEA Jenkins - [`2497abe`](https://github.com/eea/volto-object-widget/commit/2497abe7e1d59729052205761e306d05063dc88e)] - #### :hammer_and_wrench: Others - tests: Fix Sonar Qube tags - refs #297339 [Alin Voinea - [`16f7acb`](https://github.com/eea/volto-object-widget/commit/16f7acbe5e6c2db94d631ad6e917c3bb916570e4)] @@ -90,19 +98,13 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). #### :hammer_and_wrench: Others -- Add Sonarqube tag using clms-frontend addons list [EEA Jenkins - [`d263cef`](https://github.com/eea/volto-object-widget/commit/d263cef130160ddae04145c8eed87f61a3b6c87d)] -- Add Sonarqube tag using clms-frontend addons list [EEA Jenkins - [`984bd88`](https://github.com/eea/volto-object-widget/commit/984bd8800078a3a324a34788c820eebece3b1b9c)] -- Add Sonarqube tag using eea-website-frontend addons list [EEA Jenkins - [`84fcbeb`](https://github.com/eea/volto-object-widget/commit/84fcbeba09f0d1adb0cb38f36a7d874b18e08bcc)] -- Add Sonarqube tag using eea-website-frontend addons list [EEA Jenkins - [`d9516fb`](https://github.com/eea/volto-object-widget/commit/d9516fbc3e1e725cea970c6f454c22881278951c)] - removed volto 16 check and attempt to pass RAZZLE_CI also to start-ci plus switch to electron browser from chromium [David Ichim - [`b00f64a`](https://github.com/eea/volto-object-widget/commit/b00f64ab0dbb6f4699926402e4a03bfbfc2f2b77)] - fix tests and test warning [David Ichim - [`60ead51`](https://github.com/eea/volto-object-widget/commit/60ead511aa756bfc3e3fbda9c293742588dda21f)] - WIp adding cypress tests for attachedimage [David Ichim - [`0a2b61f`](https://github.com/eea/volto-object-widget/commit/0a2b61f6beeb81ecc7fb8b8b211b162842b0976d)] -- Add Sonarqube tag using clms-frontend addons list [EEA Jenkins - [`586e487`](https://github.com/eea/volto-object-widget/commit/586e4873e7d015f5ae427d62affecf219faf3c10)] - fix test since we don't return only uuid [David Ichim - [`3dd2373`](https://github.com/eea/volto-object-widget/commit/3dd237388b339bf30df2e5f699b8c892d34db3a9)] - update uuid mock to avoid complaint when method it's called more than once [David Ichim - [`19153e4`](https://github.com/eea/volto-object-widget/commit/19153e4ad9b178db4c78521df4070a02b1bf829e)] - eslint fix, skip volto 16 check and bump package version to 8 to represent the major change [David Ichim - [`ec4d346`](https://github.com/eea/volto-object-widget/commit/ec4d346b0f6f1250d9f8ad07865669e519b7d819)] - Brought fixes and tests from volto-hero-block within volto-object-widget [David Ichim - [`3d335ba`](https://github.com/eea/volto-object-widget/commit/3d335ba07285f52743c6a953ad82037b672ce771)] -- Add Sonarqube tag using ied-frontend addons list [EEA Jenkins - [`5adfb29`](https://github.com/eea/volto-object-widget/commit/5adfb296105429683a950069968ffcb625322cf1)] - Added info for image_field and image_scales as added by the new Volto ImageWidget [David Ichim - [`47ec783`](https://github.com/eea/volto-object-widget/commit/47ec783e32197fd232f79967aae5ea9981b89f27)] - Update package.json [dobri1408 - [`e15b893`](https://github.com/eea/volto-object-widget/commit/e15b8937a9e879efad1ed923f7766fb07e20294e)] - Update package.json [dobri1408 - [`1a73ce2`](https://github.com/eea/volto-object-widget/commit/1a73ce26e12f015c425c5de18ffba08b39efd6d6)] @@ -123,11 +125,6 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - feat: Release 7.0.0 - Volto 17 support [alin - [`085cb98`](https://github.com/eea/volto-object-widget/commit/085cb980fe9d29a99f00232b21a946a085903739)] - feat: Volto 17 support - refs #264527 [EEA Jenkins - [`47612bf`](https://github.com/eea/volto-object-widget/commit/47612bf9a6eb63847c0581cef6443b28034e0867)] -#### :hammer_and_wrench: Others - -- Add Sonarqube tag using insitu-frontend addons list [EEA Jenkins - [`ede6218`](https://github.com/eea/volto-object-widget/commit/ede62186cfedba1b020b83ba26cc3e4b18599ea2)] -- Add Sonarqube tag using clms-frontend addons list [EEA Jenkins - [`8465373`](https://github.com/eea/volto-object-widget/commit/8465373b20cdd370bad9569f63b2ad3b16d01661)] -- Add Sonarqube tag using insitu-frontend addons list [EEA Jenkins - [`6bb1c9c`](https://github.com/eea/volto-object-widget/commit/6bb1c9cd9e319d5046e386a59ca4ab197a8075d2)] ## [6.0.0](https://github.com/eea/volto-object-widget/compare/5.2.0...6.0.0) - 8 December 2023 #### :hammer_and_wrench: Others @@ -139,18 +136,9 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - feat: Allow attachedImageWidget to use also object browser values for backwards compatibility - refs #258136 [dobri1408 - [`031a597`](https://github.com/eea/volto-object-widget/commit/031a597249561722586f28e3cc7f0d6df4d18a6f)] -#### :house: Internal changes - -- chore: [JENKINS] Refactor automated testing [valentinab25 - [`28aecaf`](https://github.com/eea/volto-object-widget/commit/28aecaf0c283d1c1eed29acce4b1f438753323d2)] - #### :hammer_and_wrench: Others - Release 5.2.0 [Alin Voinea - [`4429e99`](https://github.com/eea/volto-object-widget/commit/4429e9922712ea59cc87fec29b19bee2e1d3c82b)] -- test: [JENKINS] Use java17 for sonarqube scanner [valentinab25 - [`436b844`](https://github.com/eea/volto-object-widget/commit/436b8449d8630c5a8972cafdc72defa4f0f30857)] -- test: [JENKINS] Run cypress in started frontend container [valentinab25 - [`a287958`](https://github.com/eea/volto-object-widget/commit/a2879582c925c5b83016cad5c091f7985b864dbc)] -- test: [JENKINS] Add cpu limit on cypress docker [valentinab25 - [`8f7f7b1`](https://github.com/eea/volto-object-widget/commit/8f7f7b1a7b1e3d8b40097bf6f2a911c349114b1b)] -- test: [JENKINS] Increase shm-size to cypress docker [valentinab25 - [`13a8897`](https://github.com/eea/volto-object-widget/commit/13a8897896597c189328636f51851d45be8e7915)] -- test: [JENKINS] Improve cypress time [valentinab25 - [`2953a70`](https://github.com/eea/volto-object-widget/commit/2953a70e7e75edf3bdcb735e3596a2acef9d0d44)] ### [5.1.5](https://github.com/eea/volto-object-widget/compare/5.1.4...5.1.5) - 22 October 2023 #### :house: Internal changes @@ -176,9 +164,7 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - test: add unit tests - refs #254313 [ana-oprea - [`ec53971`](https://github.com/eea/volto-object-widget/commit/ec53971d38d4458d65ca3a627976054c8eeceef8)] - test: EN locales, pre-commit fix, feature PRs checks Refs #257193 [valentinab25 - [`fa47506`](https://github.com/eea/volto-object-widget/commit/fa475064b0e8800bd8f5a775ddeccd3995b16533)] -- test: Fix eslint and yarn i18n [Alin Voinea - [`b566224`](https://github.com/eea/volto-object-widget/commit/b56622406cf196fe09641583c84197497a9cff83)] - i18n: Add en [Alin Voinea - [`e96fb5b`](https://github.com/eea/volto-object-widget/commit/e96fb5b25300c78f29c682dfed579990a1a7baf2)] -- test: Update Makefile and docker-compose to align it with Jenkinsfile [valentinab25 - [`99817cd`](https://github.com/eea/volto-object-widget/commit/99817cd62e3e85fd0214157977f8dc8aff638097)] ### [5.1.3](https://github.com/eea/volto-object-widget/compare/5.1.2...5.1.3) - 24 July 2023 #### :hammer_and_wrench: Others @@ -190,10 +176,6 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - feat: File picker object browser - refs #253430 [dobri1408 - [`62fb1d0`](https://github.com/eea/volto-object-widget/commit/62fb1d01ea85cab458e496ecb011f114d9ffa88a)] -#### :house: Internal changes - -- chore: [JENKINS] Deprecate circularity website [valentinab25 - [`da1cf7d`](https://github.com/eea/volto-object-widget/commit/da1cf7d96f01e677293eeba2602804727a360571)] - #### :hammer_and_wrench: Others - test: jest should look for addons in node_modules Refs #253277 [valentinab25 - [`6a639c5`](https://github.com/eea/volto-object-widget/commit/6a639c5917f66e6addb614d629988b195cda4ad7)] @@ -214,19 +196,8 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - * version [andreiggr - [`052c684`](https://github.com/eea/volto-object-widget/commit/052c684180dd1f46af435e4cbc9e7e8641abebe7)] - Revert changes on AttachedImageWidget [Miu Razvan - [`88eafeb`](https://github.com/eea/volto-object-widget/commit/88eafeb363f495faae7d915aa1f8867c86a5f1d6)] - Revert fc658b5 [Miu Razvan - [`669d06f`](https://github.com/eea/volto-object-widget/commit/669d06f8b8856599feab29f96981eb67e21dc2b0)] -- Revert "Add Sonarqube tag using eea-website-frontend addons list" [Miu Razvan - [`fc658b5`](https://github.com/eea/volto-object-widget/commit/fc658b5291c1c4fdebd21da609463f85841b38ce)] -- Add Sonarqube tag using eea-website-frontend addons list [EEA Jenkins - [`45e4f91`](https://github.com/eea/volto-object-widget/commit/45e4f9134390f4ee2f1636edc17320365d2f13d7)] ### [5.1.0](https://github.com/eea/volto-object-widget/compare/5.0.1...5.1.0) - 27 March 2023 -#### :hammer_and_wrench: Others - -- Add Sonarqube tag using eea-website-frontend addons list [EEA Jenkins - [`38ae79f`](https://github.com/eea/volto-object-widget/commit/38ae79f2d63a0240885a9685ce9a0e5f698ef957)] -- Add Sonarqube tag using advisory-board-frontend addons list [EEA Jenkins - [`ea09d1e`](https://github.com/eea/volto-object-widget/commit/ea09d1ec24dc6e46c79d57d8b90f2b943e3b41e3)] -- Add Sonarqube tag using advisory-board-frontend addons list [EEA Jenkins - [`48e235e`](https://github.com/eea/volto-object-widget/commit/48e235e0a1f3aa6fcf6fe6b8021cbf57d89f3bff)] -- test(Jenkins): Run tests and cypress with latest canary @plone/volto [Alin Voinea - [`33ab4d9`](https://github.com/eea/volto-object-widget/commit/33ab4d94a61939763e245c721acc9c300e8deba6)] -- Add Sonarqube tag using cca-frontend addons list [EEA Jenkins - [`e95a916`](https://github.com/eea/volto-object-widget/commit/e95a91628659c5447ceea8668162109ac10a67ff)] -- yarn 3 [Alin Voinea - [`aabc72c`](https://github.com/eea/volto-object-widget/commit/aabc72cb720dced56f7888bfaaf6d9b7668392b8)] -- Add Sonarqube tag using demo-kitkat-frontend addons list [EEA Jenkins - [`bcbaa9e`](https://github.com/eea/volto-object-widget/commit/bcbaa9e6644bdd53cf9d269ef9eede823706d2ae)] ### [5.0.1](https://github.com/eea/volto-object-widget/compare/5.0.0...5.0.1) - 16 November 2022 #### :hammer_and_wrench: Others @@ -241,14 +212,9 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - Typo [Miu Razvan - [`0eac194`](https://github.com/eea/volto-object-widget/commit/0eac194761c04db9807ca63381b25c13c7a854bd)] - Prepare 5.0.0 release [Miu Razvan - [`2a12c37`](https://github.com/eea/volto-object-widget/commit/2a12c377a7bf5a1a51966ab1e1c867f1b55ccb95)] - Update babel & jest config [Miu Razvan - [`8269b4a`](https://github.com/eea/volto-object-widget/commit/8269b4ac4aa9d487579b35ff41d0fea9dce5fc45)] -- Add Sonarqube tag using marine-frontend addons list [EEA Jenkins - [`2b550d7`](https://github.com/eea/volto-object-widget/commit/2b550d76313569397fda8967147e0052176f823e)] -- Add Sonarqube tag using eea-website-frontend addons list [EEA Jenkins - [`08aa211`](https://github.com/eea/volto-object-widget/commit/08aa211cdfa1b48817a4af6a21c3b033ef6642ea)] - update(jest): add @plone/volto-slate resolver refs- #153447 [nileshgulia1 - [`6963a87`](https://github.com/eea/volto-object-widget/commit/6963a87a0c84910c0ef695652d944115d487b24e)] ### [4.0.2](https://github.com/eea/volto-object-widget/compare/4.0.1...4.0.2) - 30 June 2022 -#### :hammer_and_wrench: Others - -- Add Sonarqube tag using circularity-frontend addons list [EEA Jenkins - [`f7e9285`](https://github.com/eea/volto-object-widget/commit/f7e928506f881dcf6bcd5f1bd5897148af2c4c38)] ### [4.0.1](https://github.com/eea/volto-object-widget/compare/4.0.0...4.0.1) - 20 May 2022 ## [4.0.0](https://github.com/eea/volto-object-widget/compare/3.0.3...4.0.0) - 19 May 2022 @@ -262,33 +228,21 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). - Release 4.0.0 [Alin Voinea - [`553e4ab`](https://github.com/eea/volto-object-widget/commit/553e4ab8b5888a2af43dcaf8be6d955cc3949513)] - Improved style for attached image widget [Miu Razvan - [`8c770cd`](https://github.com/eea/volto-object-widget/commit/8c770cdeb6af776208bd9a3936f33f5370d70fd7)] - Release 3.1.0 [Alin Voinea - [`61dd13b`](https://github.com/eea/volto-object-widget/commit/61dd13b20b2e00305af00b762e3e4d734a03cf0d)] -- Add Sonarqube tag using clms-frontend addons list [EEA Jenkins - [`0912594`](https://github.com/eea/volto-object-widget/commit/09125945f04192d8af200c6828c9388a29f4e8ff)] -- Add Sonarqube tag using eea-website-frontend addons list [EEA Jenkins - [`beb8f0b`](https://github.com/eea/volto-object-widget/commit/beb8f0ba5091911428b885e39b2bcdcdf390104c)] ### [3.0.3](https://github.com/eea/volto-object-widget/compare/3.0.2...3.0.3) - 3 January 2022 ### [3.0.2](https://github.com/eea/volto-object-widget/compare/3.0.1...3.0.2) - 18 December 2021 -#### :hammer_and_wrench: Others - -- Add Sonarqube tag using freshwater-frontend addons list [EEA Jenkins - [`5f6c212`](https://github.com/eea/volto-object-widget/commit/5f6c212134fee7d1096c9733e215a517d9842279)] ### [3.0.1](https://github.com/eea/volto-object-widget/compare/3.0.0...3.0.1) - 10 December 2021 #### :hammer_and_wrench: Others - Refs #142010 - Optimize Volto-addons gitflow pipelines [valentinab25 - [`0598f50`](https://github.com/eea/volto-object-widget/commit/0598f50fd11e720e3b78d039987d92580ad6c7d6)] -- Add Sonarqube tag using industry-frontend addons list [EEA Jenkins - [`0eb9ee2`](https://github.com/eea/volto-object-widget/commit/0eb9ee20b47872dcd13fbd016443226968b93e6b)] -- Add Sonarqube tag using clms-frontend addons list [EEA Jenkins - [`da90a9b`](https://github.com/eea/volto-object-widget/commit/da90a9bcd52894ca8e2303e9f4d6f39f6e7c727a)] -- Add Sonarqube tag using sustainability-frontend addons list [EEA Jenkins - [`b9f9262`](https://github.com/eea/volto-object-widget/commit/b9f9262a51f8c7b21081ed7a3c471ed1f54d600d)] -- Add Sonarqube tag using climate-energy-frontend addons list [EEA Jenkins - [`5374fa5`](https://github.com/eea/volto-object-widget/commit/5374fa5d6fb973c1534d1608a623f1e0a1ec5266)] -- Add Sonarqube tag using ims-frontend addons list [EEA Jenkins - [`c954416`](https://github.com/eea/volto-object-widget/commit/c9544161ee8717e6568535527d720f884347160c)] ## [3.0.0](https://github.com/eea/volto-object-widget/compare/2.2.3...3.0.0) - 3 September 2021 #### :hammer_and_wrench: Others - Fix ObjectListWidget tests [Alin Voinea - [`149c3ae`](https://github.com/eea/volto-object-widget/commit/149c3aee0fe40c5a80d58cc8a12bd1b67a66366f)] - Remove DEPRECATED ObjectWidget. Moved to Volto core. [Alin Voinea - [`415e7a9`](https://github.com/eea/volto-object-widget/commit/415e7a91652d7fc68e0c0dd6648f9bc5a50170f9)] -- Add Sonarqube tag using frontend addons list [EEA Jenkins - [`49e4e6e`](https://github.com/eea/volto-object-widget/commit/49e4e6e6376bbacbf657925811ae087da3bd2d30)] -- Add Sonarqube tag using frontend addons list [EEA Jenkins - [`4c3c118`](https://github.com/eea/volto-object-widget/commit/4c3c118290cbd25432111c60090f6aade1bac1d2)] ### [2.2.3](https://github.com/eea/volto-object-widget/compare/2.2.2...2.2.3) - 4 June 2021 #### :hammer_and_wrench: Others @@ -310,7 +264,6 @@ Generated by [`auto-changelog`](https://github.com/CookPete/auto-changelog). #### :hammer_and_wrench: Others - Release 2.1.0 [Alin Voinea - [`59eee3c`](https://github.com/eea/volto-object-widget/commit/59eee3c2b65b0d5f911eca0f59169c2687df33f8)] -- Cleanup Jenkinsfile [Alin Voinea - [`b7773c6`](https://github.com/eea/volto-object-widget/commit/b7773c662a77d9de377a0bce1f701cdafd8cbe8b)] - Revert "Move addons dependencies to package.json" [Alin Voinea - [`b746230`](https://github.com/eea/volto-object-widget/commit/b7462300dd606a984700b304e924d8dbb42c4f64)] - Move addons dependencies to package.json [Alin Voinea - [`9249c71`](https://github.com/eea/volto-object-widget/commit/9249c712aa9db813d62fab90cefe6170fbd8993e)] - remove volto-blocks-form dependency [nileshgulia1 - [`2c215bc`](https://github.com/eea/volto-object-widget/commit/2c215bc31a6ad8279825008b7098359843c9f497)] diff --git a/packages/volto-object-widget/LICENSE.md b/packages/volto-object-widget/LICENSE.md new file mode 100644 index 0000000..0992c00 --- /dev/null +++ b/packages/volto-object-widget/LICENSE.md @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) 2020 European Environment Agency + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/packages/volto-object-widget/README.md b/packages/volto-object-widget/README.md new file mode 100644 index 0000000..a285516 --- /dev/null +++ b/packages/volto-object-widget/README.md @@ -0,0 +1,232 @@ +# @eeacms/volto-object-widget + +[![Releases](https://img.shields.io/github/v/release/eea/volto-object-widget)](https://github.com/eea/volto-object-widget/releases) +[![Pipeline](https://ci.eionet.europa.eu/buildStatus/icon?job=volto-addons%2Fvolto-object-widget%2Fmaster&subject=master)](https://ci.eionet.europa.eu/view/Github/job/volto-addons/job/volto-object-widget/job/master/display/redirect) +[![Coverage](https://sonarqube.eea.europa.eu/api/project_badges/measure?project=volto-object-widget&metric=coverage)](https://sonarqube.eea.europa.eu/dashboard?id=volto-object-widget) + +[Volto](https://github.com/plone/volto) add-on: Various Volto schema-based widgets. + +## Features + +This Volto addon provides several "abstract" widgets, to allow complex +information to be editable by the schema-based forms. It centers around the +concept: "we can create a form to edit a JSON object by using a schema" and so +it provides, right now, widgets to edit "list of JSON objects", a "mapping of +JSON objects" and a single "JSON object, but I choose the schema for it". + +### FlatListObject + +![Flat List object](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/flat-list-widget.png) + +This widget allows you to edit a list of objects by creating, editing and +deleting instances of objects editable with the provided `schema` parameter. +The list is sortable with drag&drop. You can also provide a schema extender, +a function with signature `(schema, data) => schema`, which will adjust, per +instance of object, its schema. To use this widget, in the schema, set the +`widget` field to `object_list_inline`. + +Example of how the data could look like for a block: + +``` +"a55c5053-ba81-4f73-ab29-7cdea74df20f": { + "@type": "dataTable", + "columns": [ + { + "@id": "f899ca76-68be-4ded-aa0b-669c04c27309", + "column": " PERC_HA_07\n(in %)", + "renderer": "progress", + "title": "21" + }, + { + "@id": "94315c5a-e031-4b7e-acb2-93887878a252", + "column": " PERC_HA_07\n(in %)", + "title": "12" + } + ], +} +``` + +The `columns` field, in this case, is data generated by the `FlatListObject`. +The schema for this field could look like (`ColumnSchema()` just generates +another instance of a schema, suitable for the `column` definition of our +specific use case): + +``` +columns: { + title: 'Columns', + description: 'Leave empty to show all columns', + schema: ColumnSchema(), + widget: 'object_list_inline', +}, +``` + +### Mapping Widget + +![Mapping widget](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/mapping-widget.png) + +This widget allows editing the properties of an object. For example, in the +following block data, the `row_colors` value is generated by an instance of the +`MappingWidget`. + +``` +"4430a32a-a266-497b-88e7-72fead5ab718": { + "@type": "dottedTableChart", + "column_data": "habitat_group", + "row_colors": { + "Bad": "#ed1834", + "F - Heathland, scrub and tundra": "#88c24f", + "Good": "#3c8000", + "Poor": "#f2a70e", + "Unknown": "#8d8d8d" + }, + "row_data": "assessment", + "size_data": "quantity" +}, +``` + +You need to provide the `options`, which is a list of objects with `{id, title}` and the `field_props`, which are parameters for the actual field that +will be used to edit the values. In our case the schema definition that was +used to edit the above value is (note, the options are empty, we're populating +them in the edit component, before passing the schema to the form): + +``` +row_colors: { + title: 'Colors', + widget: 'option_mapping', + field_props: { + widget: 'simple_color', + available_colors: settings.available_colors, + }, + options: [], +} +``` + +To use this widget, in the schema, set the `widget` field to `option_mapping`. + +### Object by type + +![Object by type](https://raw.githubusercontent.com/eea/volto-object-widget/master/img/object-by-type-widget.png) + +With this widget you can choose the type of value that will be used, from +a predefined list of schemas. A schema that would use this type of widget could +look like: + +``` +const LinkEditSchema = { + title: 'Link', + fieldsets: [ + { + id: 'default', + title: 'Default', + fields: ['link'], + }, + ], + properties: { + link: { + title: 'Link', + widget: 'object_by_type', + schemas: [ + { + id: 'internal', + icon: internalSVG, + schema: InternalLinkSchema, + }, + { + id: 'external', + icon: externalSVG, + schema: ExternalLinkSchema, + }, + { + id: 'email', + icon: emailSVG, + schema: EmailLinkSchema, + }, + ], + }, + }, + required: [], +}; +``` + +To use this widget, in the schema, set the `widget` field to `object_by_type`. + +## Upgrade + +### Upgrading to 10.x + +> This version requires `Volto 18` or `Volto 19` and Node.js 22. + +Every widget it registers (`object_list_popup`, `object_list_inline`, `object_by_type`, `option_mapping`, `attachedimage`, `attachedfile`, `object_types_widget`, `url`, `internal_url`, `json`) and every export other add-ons import keeps the same name and behaviour, so upgrading from 9.x on Volto 18 needs no content changes. The release adds Volto 19 support and moves the repository to the Volto 19 layout, where the published package lives in `packages/volto-object-widget`. + +#### Breaking changes + +- **Node.js 22 or newer is required** (`engines.node >= 22`), 9.x declared no engine. +- **React 18 is required.** The package declares `react` and `react-dom` as `^18.2.0` peers, 9.x declared no peers. +- **The package no longer ships the Jest setup.** `jest-addon.config.js` and `jest.setup.js` were removed in favour of Vitest, so a Volto 18 project that still runs the Jest harness has to keep its own copy. + +## Requirements + +### Backend + +- [Plone](https://plone.org/download) +- [plone.restapi](https://pypi.org/project/plone.restapi/) + +### Frontend + +- Node.js: `>=22.0.0` + +## Installation + +1. Make sure you have a [Plone backend](https://plone.org/download) up-and-running at http://localhost:8080/Plone + + ```Bash + docker compose up backend + ``` + +1. Start Volto frontend + +* If you already have a volto project, just update `package.json`: + + ```JSON + "dependencies": { + "@eeacms/volto-object-widget": "*" + } + ``` + + and `volto.config.js`: + + ```JavaScript + const addons = ['@eeacms/volto-object-widget']; + ``` + +* If not, create one with Cookieplone, as recommended by the official Plone documentation for Volto 18+: + + ``` + uvx cookieplone project + cd project-title + ``` + +1. Install or update dependencies, then start the project: + + ``` + make install + ``` + + For a Cookieplone project, start the backend and frontend in separate terminals: + + ``` + make backend-start + make frontend-start + ``` + +1. Go to http://localhost:3000 + +1. Happy editing! + +## License + +See [LICENSE.md](LICENSE.md) for details. + +## Funding + +[European Environment Agency (EU)](http://eea.europa.eu) diff --git a/packages/volto-object-widget/babel.config.js b/packages/volto-object-widget/babel.config.js new file mode 100644 index 0000000..a900a75 --- /dev/null +++ b/packages/volto-object-widget/babel.config.js @@ -0,0 +1 @@ +module.exports = require('@plone/volto/babel'); diff --git a/locales/de/LC_MESSAGES/volto.po b/packages/volto-object-widget/locales/de/LC_MESSAGES/volto.po similarity index 100% rename from locales/de/LC_MESSAGES/volto.po rename to packages/volto-object-widget/locales/de/LC_MESSAGES/volto.po diff --git a/locales/en/LC_MESSAGES/volto.po b/packages/volto-object-widget/locales/en/LC_MESSAGES/volto.po similarity index 100% rename from locales/en/LC_MESSAGES/volto.po rename to packages/volto-object-widget/locales/en/LC_MESSAGES/volto.po diff --git a/locales/it/LC_MESSAGES/volto.po b/packages/volto-object-widget/locales/it/LC_MESSAGES/volto.po similarity index 100% rename from locales/it/LC_MESSAGES/volto.po rename to packages/volto-object-widget/locales/it/LC_MESSAGES/volto.po diff --git a/locales/ro/LC_MESSAGES/volto.po b/packages/volto-object-widget/locales/ro/LC_MESSAGES/volto.po similarity index 100% rename from locales/ro/LC_MESSAGES/volto.po rename to packages/volto-object-widget/locales/ro/LC_MESSAGES/volto.po diff --git a/locales/volto.pot b/packages/volto-object-widget/locales/volto.pot similarity index 100% rename from locales/volto.pot rename to packages/volto-object-widget/locales/volto.pot diff --git a/packages/volto-object-widget/package.json b/packages/volto-object-widget/package.json new file mode 100644 index 0000000..732dbc8 --- /dev/null +++ b/packages/volto-object-widget/package.json @@ -0,0 +1,93 @@ +{ + "name": "@eeacms/volto-object-widget", + "version": "10.0.0", + "description": "volto-object-widget: Volto add-on", + "main": "src/index.js", + "author": "European Environment Agency: IDM2 A-Team", + "license": "MIT", + "homepage": "https://github.com/eea/volto-object-widget", + "keywords": [ + "volto-addon", + "volto-widget", + "volto", + "plone", + "react" + ], + "repository": { + "type": "git", + "url": "git@github.com:eea/volto-object-widget.git" + }, + "dependencies": { + "jsoneditor": "10.2.0" + }, + "devDependencies": { + "@cypress/code-coverage": "^3.10.0", + "@plone/scripts": "workspace:*", + "babel-plugin-transform-class-properties": "^6.24.1", + "cypress": "13.1.0", + "cypress-file-upload": "^5.0.8", + "dotenv": "^16.3.2", + "husky": "^8.0.3", + "lint-staged": "^14.0.1", + "md5": "^2.3.0", + "@plone/registry": "workspace:*", + "@plone/types": "workspace:*", + "@testing-library/jest-dom": "6.9.1", + "@testing-library/react": "^16.3.2", + "@types/react": "^18.3.1", + "@types/react-dom": "^18.3.1", + "@vitejs/plugin-react": "4.7.0", + "@vitest/coverage-istanbul": "3.2.7", + "jsdom": "23.0.0", + "redux-mock-store": "1.5.4", + "redux-thunk": "^2.4.2", + "release-it": "^19.0.5", + "typescript": "^5.7.3", + "vite": "6.4.3", + "vitest": "3.2.7" + }, + "lint-staged": { + "src/**/*.{js,jsx,ts,tsx,json}": [ + "make lint-fix", + "make prettier-fix" + ], + "src/**/*.{jsx}": [ + "make i18n" + ], + "theme/**/*.{css,less}": [ + "make stylelint-fix" + ], + "src/**/*.{css,less}": [ + "make stylelint-fix" + ], + "theme/**/*.overrides": [ + "make stylelint-fix" + ], + "src/**/*.overrides": [ + "make stylelint-fix" + ] + }, + "scripts": { + "release": "release-it", + "release-major-beta": "release-it major --preRelease=beta", + "release-beta": "release-it --preRelease=beta", + "test": "vitest --config ./vitest.config.mjs run --passWithNoTests", + "test:fix": "vitest --config ./vitest.config.mjs run --passWithNoTests --update", + "i18n": "rm -rf build/messages && NODE_ENV=production i18n --addon", + "prepare": "cd ../.. && husky install || true", + "dry-release": "release-it --dry-run", + "release-major-alpha": "release-it major --preRelease=alpha", + "release-alpha": "release-it --preRelease=alpha" + }, + "packageManager": "pnpm@10.20.0", + "engines": { + "node": ">=22.0.0" + }, + "publishConfig": { + "access": "public" + }, + "peerDependencies": { + "react": "^18.2.0", + "react-dom": "^18.2.0" + } +} diff --git a/src/Widget/AttachedFileWidget.jsx b/packages/volto-object-widget/src/Widget/AttachedFileWidget.jsx similarity index 100% rename from src/Widget/AttachedFileWidget.jsx rename to packages/volto-object-widget/src/Widget/AttachedFileWidget.jsx diff --git a/src/Widget/AttachedFileWidget.test.jsx b/packages/volto-object-widget/src/Widget/AttachedFileWidget.test.jsx similarity index 90% rename from src/Widget/AttachedFileWidget.test.jsx rename to packages/volto-object-widget/src/Widget/AttachedFileWidget.test.jsx index a9e9e90..f0e42cd 100644 --- a/src/Widget/AttachedFileWidget.test.jsx +++ b/packages/volto-object-widget/src/Widget/AttachedFileWidget.test.jsx @@ -1,3 +1,4 @@ +import { vi } from 'vitest'; import React from 'react'; import { render, fireEvent, screen, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; @@ -5,12 +6,12 @@ import AttachedFileWidget from './AttachedFileWidget'; import { Provider } from 'react-intl-redux'; import configureStore from 'redux-mock-store'; -jest.mock('@plone/volto/components/manage/Sidebar/ObjectBrowser', () => { - return (Component) => Component; +vi.mock('@plone/volto/components/manage/Sidebar/ObjectBrowser', () => { + return { default: (Component) => Component }; }); -jest.mock('promise-file-reader', () => ({ - readAsDataURL: jest.fn(() => +vi.mock('promise-file-reader', () => ({ + readAsDataURL: vi.fn(() => Promise.resolve('data:text/plain;base64,SGVsbG8sIFdvcmxkIQ=='), ), })); @@ -20,7 +21,7 @@ const store = mockStore({ intl: { locale: 'en', messages: {}, - formatMessage: jest.fn(), + formatMessage: vi.fn(), subrequests: {}, }, router: { @@ -30,11 +31,11 @@ const store = mockStore({ }); describe('AttachedFileWidget', () => { - const mockOnChange = jest.fn(); - const mockOpenObjectBrowser = jest.fn(); + const mockOnChange = vi.fn(); + const mockOpenObjectBrowser = vi.fn(); beforeEach(() => { - jest.clearAllMocks(); + vi.clearAllMocks(); }); it('renders without crashing', () => { diff --git a/src/Widget/AttachedImageWidget.jsx b/packages/volto-object-widget/src/Widget/AttachedImageWidget.jsx similarity index 100% rename from src/Widget/AttachedImageWidget.jsx rename to packages/volto-object-widget/src/Widget/AttachedImageWidget.jsx diff --git a/src/Widget/InternalUrlWidget.jsx b/packages/volto-object-widget/src/Widget/InternalUrlWidget.jsx similarity index 100% rename from src/Widget/InternalUrlWidget.jsx rename to packages/volto-object-widget/src/Widget/InternalUrlWidget.jsx diff --git a/src/Widget/JsonWidget/JsonWidget.jsx b/packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.jsx similarity index 100% rename from src/Widget/JsonWidget/JsonWidget.jsx rename to packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.jsx diff --git a/src/Widget/JsonWidget/JsonWidget.test.jsx b/packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.test.jsx similarity index 78% rename from src/Widget/JsonWidget/JsonWidget.test.jsx rename to packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.test.jsx index 5cd7ed4..5733f31 100644 --- a/src/Widget/JsonWidget/JsonWidget.test.jsx +++ b/packages/volto-object-widget/src/Widget/JsonWidget/JsonWidget.test.jsx @@ -1,14 +1,15 @@ +import { vi } from 'vitest'; import React from 'react'; import { Provider } from 'react-intl-redux'; import { render, fireEvent, screen, waitFor } from '@testing-library/react'; import '@testing-library/jest-dom'; import configureStore from 'redux-mock-store'; import JsonWidget from './JsonWidget'; -jest.mock('jsoneditor/dist/jsoneditor.min.css', () => {}); -jest.mock('./json-widget.css', () => {}); +vi.mock('jsoneditor/dist/jsoneditor.min.css', () => ({})); +vi.mock('./json-widget.css', () => ({})); // Mock semantic-ui-react components to simple HTML elements -jest.mock('semantic-ui-react', () => { +vi.mock('semantic-ui-react', () => { const Button = (props) => ; const Segment = (props) =>
{props.children}
; const TextArea = (props) =>