diff --git a/.github/workflows/nodejs.yml b/.github/workflows/nodejs.yml index 15d945ebcfc0..e224906029dc 100644 --- a/.github/workflows/nodejs.yml +++ b/.github/workflows/nodejs.yml @@ -52,7 +52,7 @@ jobs: CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }} NODE_OPTIONS: --max-old-space-size=4096 TZ: Europe/Amsterdam - - uses: actions/upload-artifact@v3 + - uses: actions/upload-artifact@v4 if: matrix.os == 'ubuntu-latest' && matrix.node-version == '20.x' && failure() with: name: cypress-results diff --git a/cypress/e2e/editorial_workflow_spec_test_backend.js b/cypress/e2e/editorial_workflow_spec_test_backend.js index 7d5fae36a968..7cd15ea7cffd 100644 --- a/cypress/e2e/editorial_workflow_spec_test_backend.js +++ b/cypress/e2e/editorial_workflow_spec_test_backend.js @@ -207,17 +207,16 @@ describe('Test Backend Editorial Workflow', () => { login(); inSidebar(() => cy.contains('a', 'Pages').click()); - inSidebar(() => cy.contains('a', 'Directory')); + inSidebar(() => cy.contains('a', /^Directory$/)); inGrid(() => cy.contains('a', 'Root Page')); - inGrid(() => cy.contains('a', 'Directory')); - inSidebar(() => cy.contains('a', 'Directory').click()); + inSidebar(() => cy.contains('a', /^Directory$/).click()); - inGrid(() => cy.contains('a', 'Sub Directory')); - inGrid(() => cy.contains('a', 'Another Sub Directory')); + inSidebar(() => cy.contains('a', /^Sub Directory$/)); + inSidebar(() => cy.contains('a', 'Another Sub Directory')); - inSidebar(() => cy.contains('a', 'Sub Directory').click()); - inGrid(() => cy.contains('a', 'Nested Directory')); + inSidebar(() => cy.contains('a', /^Sub Directory$/).click()); + inSidebar(() => cy.contains('a', 'Nested Directory')); cy.url().should( 'eq', 'http://localhost:8080/#/collections/pages/filter/directory/sub-directory', @@ -233,21 +232,17 @@ describe('Test Backend Editorial Workflow', () => { login(); inSidebar(() => cy.contains('a', 'Pages').click()); - inSidebar(() => cy.contains('a', 'Directory').click()); - inGrid(() => cy.contains('a', 'Another Sub Directory').click()); - - cy.url().should( - 'eq', - 'http://localhost:8080/#/collections/pages/entries/directory/another-sub-directory/index', - ); + inSidebar(() => cy.contains('a', /^Directory$/).click()); + inSidebar(() => cy.contains('a', 'Another Sub Directory').click()); + inGrid(() => cy.contains('a', 'Another Sub Directory')); }); it(`can create a new entry with custom path`, () => { login(); inSidebar(() => cy.contains('a', 'Pages').click()); - inSidebar(() => cy.contains('a', 'Directory').click()); - inSidebar(() => cy.contains('a', 'Sub Directory').click()); + inSidebar(() => cy.contains('a', /^Directory$/).click()); + inSidebar(() => cy.contains('a', /^Sub Directory$/).click()); cy.contains('a', 'New Page').click(); cy.get('[id^="path-field"]').should('have.value', 'directory/sub-directory'); @@ -262,9 +257,9 @@ describe('Test Backend Editorial Workflow', () => { publishEntryInEditor(publishTypes.publishNow); exitEditor(); - inGrid(() => cy.contains('a', 'New Path Title')); - inSidebar(() => cy.contains('a', 'Directory').click()); - inSidebar(() => cy.contains('a', 'Directory').click()); + inSidebar(() => cy.contains('a', 'New Path Title')); + inSidebar(() => cy.contains('a', /^Directory$/).click()); + inSidebar(() => cy.contains('a', /^Directory$/).click()); inGrid(() => cy.contains('a', 'New Path Title').should('not.exist')); }); @@ -272,8 +267,8 @@ describe('Test Backend Editorial Workflow', () => { login(); inSidebar(() => cy.contains('a', 'Pages').click()); - inSidebar(() => cy.contains('a', 'Directory').click()); - inSidebar(() => cy.contains('a', 'Sub Directory').click()); + inSidebar(() => cy.contains('a', /^Directory$/).click()); + inSidebar(() => cy.contains('a', /^Sub Directory$/).click()); cy.contains('a', 'New Page').click(); cy.get('[id^="title-field"]').type('New Path Title'); @@ -292,7 +287,8 @@ describe('Test Backend Editorial Workflow', () => { login(); inSidebar(() => cy.contains('a', 'Pages').click()); - inGrid(() => cy.contains('a', 'Directory').click()); + inSidebar(() => cy.contains('a', /^Directory$/).click()); + inGrid(() => cy.contains('a', /^Directory$/).click()); cy.get('[id^="path-field"]').should('have.value', 'directory'); cy.get('[id^="path-field"]').clear(); @@ -310,7 +306,7 @@ describe('Test Backend Editorial Workflow', () => { inSidebar(() => cy.contains('a', 'New Directory').click()); - inGrid(() => cy.contains('a', 'Sub Directory')); - inGrid(() => cy.contains('a', 'Another Sub Directory')); + inSidebar(() => cy.contains('a', /^Sub Directory$/)); + inSidebar(() => cy.contains('a', 'Another Sub Directory')); }); }); diff --git a/dev-test/config.yml b/dev-test/config.yml index d9bf6182a7cc..6eac43f98db9 100644 --- a/dev-test/config.yml +++ b/dev-test/config.yml @@ -17,6 +17,8 @@ collections: # A list of collections the CMS should be able to edit slug: '{{year}}-{{month}}-{{day}}-{{slug}}' summary: '{{title}} -- {{year}}/{{month}}/{{day}}' create: true # Allow users to create new documents in this collection + editor: + visualEditing: true view_filters: - label: Posts With Index field: title @@ -61,6 +63,8 @@ collections: # A list of collections the CMS should be able to edit slug: '{{year}}-{{month}}-{{day}}-{{slug}}' summary: '{{title}} -- {{year}}/{{month}}/{{day}}' create: true # Allow users to create new documents in this collection + editor: + visualEditing: true fields: # The fields each document in this collection have - { label: 'Title', name: 'title', widget: 'string', tagname: 'h1' } - { label: 'Body', name: 'body', widget: 'markdown', hint: 'Main content goes here.' } @@ -272,7 +276,7 @@ collections: # A list of collections the CMS should be able to edit label_singular: 'Page' folder: _pages create: true - nested: { depth: 100 } + nested: { depth: 100, subfolders: false } fields: - label: Title name: title diff --git a/package-lock.json b/package-lock.json index 9e1197d65412..128c523782d3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7718,6 +7718,11 @@ "url": "https://opencollective.com/typescript-eslint" } }, + "node_modules/@vercel/stega": { + "version": "0.1.2", + "resolved": "https://registry.npmjs.org/@vercel/stega/-/stega-0.1.2.tgz", + "integrity": "sha512-P7mafQXjkrsoyTRppnt0N21udKS9wUmLXHRyP9saLXLHw32j/FgUJ3FscSWgvSqRs4cj7wKZtwqJEvWJ2jbGmA==" + }, "node_modules/@webassemblyjs/ast": { "version": "1.11.6", "dev": true, @@ -33157,12 +33162,12 @@ } }, "packages/decap-cms": { - "version": "3.5.0", + "version": "3.6.3", "license": "MIT", "dependencies": { "codemirror": "^5.46.0", "create-react-class": "^15.7.0", - "decap-cms-app": "^3.5.0", + "decap-cms-app": "^3.6.3", "decap-cms-media-library-cloudinary": "^3.0.3", "decap-cms-media-library-uploadcare": "^3.0.2", "file-loader": "^6.2.0", @@ -33172,7 +33177,7 @@ } }, "packages/decap-cms-app": { - "version": "3.5.0", + "version": "3.6.3", "license": "MIT", "dependencies": { "@emotion/react": "^11.11.1", @@ -33188,10 +33193,10 @@ "decap-cms-backend-gitlab": "^3.2.2", "decap-cms-backend-proxy": "^3.1.4", "decap-cms-backend-test": "^3.1.3", - "decap-cms-core": "^3.5.0", + "decap-cms-core": "^3.6.2", "decap-cms-editor-component-image": "^3.1.3", "decap-cms-lib-auth": "^3.0.5", - "decap-cms-lib-util": "^3.1.0", + "decap-cms-lib-util": "^3.2.0", "decap-cms-lib-widgets": "^3.1.0", "decap-cms-locales": "^3.3.0", "decap-cms-ui-default": "^3.1.4", @@ -33201,11 +33206,11 @@ "decap-cms-widget-datetime": "^3.2.3", "decap-cms-widget-file": "^3.1.3", "decap-cms-widget-image": "^3.1.3", - "decap-cms-widget-list": "^3.2.2", + "decap-cms-widget-list": "^3.3.0", "decap-cms-widget-map": "^3.1.4", - "decap-cms-widget-markdown": "^3.2.0", + "decap-cms-widget-markdown": "^3.3.0", "decap-cms-widget-number": "^3.1.3", - "decap-cms-widget-object": "^3.2.0", + "decap-cms-widget-object": "^3.3.1", "decap-cms-widget-relation": "^3.3.2", "decap-cms-widget-select": "^3.2.2", "decap-cms-widget-string": "^3.1.3", @@ -33414,11 +33419,12 @@ } }, "packages/decap-cms-core": { - "version": "3.5.0", + "version": "3.6.2", "license": "MIT", "dependencies": { "@iarna/toml": "2.2.5", "@reduxjs/toolkit": "^1.9.1", + "@vercel/stega": "^0.1.2", "ajv": "8.12.0", "ajv-errors": "^3.0.0", "ajv-keywords": "^5.0.0", @@ -33562,7 +33568,7 @@ } }, "packages/decap-cms-lib-util": { - "version": "3.1.0", + "version": "3.2.0", "license": "MIT", "dependencies": { "js-sha256": "^0.9.0", @@ -33707,7 +33713,7 @@ } }, "packages/decap-cms-widget-list": { - "version": "3.2.2", + "version": "3.3.0", "license": "MIT", "dependencies": { "@dnd-kit/core": "^6.0.8", @@ -33743,7 +33749,7 @@ } }, "packages/decap-cms-widget-markdown": { - "version": "3.2.0", + "version": "3.3.0", "license": "MIT", "dependencies": { "dompurify": "^2.2.6", @@ -33888,7 +33894,7 @@ } }, "packages/decap-cms-widget-object": { - "version": "3.2.0", + "version": "3.3.1", "license": "MIT", "peerDependencies": { "@emotion/react": "^11.11.1", @@ -33960,7 +33966,7 @@ } }, "packages/decap-server": { - "version": "3.1.2", + "version": "3.2.0", "license": "MIT", "dependencies": { "@hapi/joi": "^17.0.2", @@ -33984,7 +33990,7 @@ "@types/morgan": "^1.7.37", "@types/node": "^16.0.0", "@types/vfile-message": "^2.0.0", - "decap-cms-lib-util": "^3.1.0", + "decap-cms-lib-util": "^3.2.0", "jest": "^27.0.0", "nodemon": "^2.0.2", "ts-jest": "^27.0.0", diff --git a/packages/decap-cms-app/CHANGELOG.md b/packages/decap-cms-app/CHANGELOG.md index 181afcbb5112..0b3594c5affa 100644 --- a/packages/decap-cms-app/CHANGELOG.md +++ b/packages/decap-cms-app/CHANGELOG.md @@ -3,6 +3,22 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.6.3](https://github.com/decaporg/decap-cms/compare/decap-cms-app@3.6.2...decap-cms-app@3.6.3) (2025-05-15) + +**Note:** Version bump only for package decap-cms-app + +## [3.6.2](https://github.com/decaporg/decap-cms/compare/decap-cms-app@3.6.1...decap-cms-app@3.6.2) (2025-02-13) + +**Note:** Version bump only for package decap-cms-app + +## [3.6.1](https://github.com/decaporg/decap-cms/compare/decap-cms-app@3.6.0...decap-cms-app@3.6.1) (2025-01-30) + +**Note:** Version bump only for package decap-cms-app + +# [3.6.0](https://github.com/decaporg/decap-cms/compare/decap-cms-app@3.5.0...decap-cms-app@3.6.0) (2025-01-29) + +**Note:** Version bump only for package decap-cms-app + # [3.5.0](https://github.com/decaporg/decap-cms/compare/decap-cms-app@3.4.0...decap-cms-app@3.5.0) (2025-01-15) ### Bug Fixes diff --git a/packages/decap-cms-app/package.json b/packages/decap-cms-app/package.json index 52fa65eca3c2..cb7a3e395173 100644 --- a/packages/decap-cms-app/package.json +++ b/packages/decap-cms-app/package.json @@ -1,7 +1,7 @@ { "name": "decap-cms-app", "description": "An extensible, open source, Git-based, React CMS for static sites. Reusable congiuration with React as peer.", - "version": "3.5.0", + "version": "3.6.3", "homepage": "https://www.decapcms.org", "repository": "https://github.com/decaporg/decap-cms/tree/main/packages/decap-cms-app", "bugs": "https://github.com/decaporg/decap-cms/issues", @@ -40,10 +40,10 @@ "decap-cms-backend-gitlab": "^3.2.2", "decap-cms-backend-proxy": "^3.1.4", "decap-cms-backend-test": "^3.1.3", - "decap-cms-core": "^3.5.0", + "decap-cms-core": "^3.6.2", "decap-cms-editor-component-image": "^3.1.3", "decap-cms-lib-auth": "^3.0.5", - "decap-cms-lib-util": "^3.1.0", + "decap-cms-lib-util": "^3.2.0", "decap-cms-lib-widgets": "^3.1.0", "decap-cms-locales": "^3.3.0", "decap-cms-ui-default": "^3.1.4", @@ -53,11 +53,11 @@ "decap-cms-widget-datetime": "^3.2.3", "decap-cms-widget-file": "^3.1.3", "decap-cms-widget-image": "^3.1.3", - "decap-cms-widget-list": "^3.2.2", + "decap-cms-widget-list": "^3.3.0", "decap-cms-widget-map": "^3.1.4", - "decap-cms-widget-markdown": "^3.2.0", + "decap-cms-widget-markdown": "^3.3.0", "decap-cms-widget-number": "^3.1.3", - "decap-cms-widget-object": "^3.2.0", + "decap-cms-widget-object": "^3.3.1", "decap-cms-widget-relation": "^3.3.2", "decap-cms-widget-select": "^3.2.2", "decap-cms-widget-string": "^3.1.3", diff --git a/packages/decap-cms-core/CHANGELOG.md b/packages/decap-cms-core/CHANGELOG.md index 9a4a6376dace..6be41063c9f8 100644 --- a/packages/decap-cms-core/CHANGELOG.md +++ b/packages/decap-cms-core/CHANGELOG.md @@ -3,6 +3,28 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.6.2](https://github.com/decaporg/decap-cms/compare/decap-cms-core@3.6.1...decap-cms-core@3.6.2) (2025-05-15) + +### Bug Fixes + +- **#7371:** Duplicate Localized Content When Duplicating Entries with i18n Enabled ([#7372](https://github.com/decaporg/decap-cms/issues/7372)) ([c5b1dfe](https://github.com/decaporg/decap-cms/commit/c5b1dfe50ae34230c735d58dd1df475fa17ee578)), closes [#7371](https://github.com/decaporg/decap-cms/issues/7371) +- **nested-i18n:** pass newPath only when customPath differs from current path ([#7418](https://github.com/decaporg/decap-cms/issues/7418)) ([86d41d7](https://github.com/decaporg/decap-cms/commit/86d41d79b20583041570bce30b46835a36bcecf2)) + +## [3.6.1](https://github.com/decaporg/decap-cms/compare/decap-cms-core@3.6.0...decap-cms-core@3.6.1) (2025-02-13) + +**Note:** Version bump only for package decap-cms-core + +# [3.6.0](https://github.com/decaporg/decap-cms/compare/decap-cms-core@3.5.0...decap-cms-core@3.6.0) (2025-01-29) + +### Bug Fixes + +- **widgetsFor:** return widgets for variable type lists ([#7296](https://github.com/decaporg/decap-cms/issues/7296)) ([9be2693](https://github.com/decaporg/decap-cms/commit/9be2693d1b35bf56c7ef05bdece6c24a21ba7567)), closes [/github.com/decaporg/decap-cms/issues/2307#issuecomment-638326225](https://github.com//github.com/decaporg/decap-cms/issues/2307/issues/issuecomment-638326225) + +### Features + +- **nested collections:** allow non-index files ([#7359](https://github.com/decaporg/decap-cms/issues/7359)) ([47a2f70](https://github.com/decaporg/decap-cms/commit/47a2f70ef788ae8e61bbbc0ac21e00d68d0029d0)), closes [#4972](https://github.com/decaporg/decap-cms/issues/4972) +- visual editing (click-to-edit) ([#7374](https://github.com/decaporg/decap-cms/issues/7374)) ([989c2dd](https://github.com/decaporg/decap-cms/commit/989c2dd6ed80f69b572b8b73c4e37b5106ae04fb)) + # [3.5.0](https://github.com/decaporg/decap-cms/compare/decap-cms-core@3.4.2...decap-cms-core@3.5.0) (2024-11-12) ### Bug Fixes diff --git a/packages/decap-cms-core/index.d.ts b/packages/decap-cms-core/index.d.ts index 404076566e06..ffb9ed93d8ae 100644 --- a/packages/decap-cms-core/index.d.ts +++ b/packages/decap-cms-core/index.d.ts @@ -311,6 +311,7 @@ declare module 'decap-cms-core' { publish?: boolean; nested?: { depth: number; + subfolders?: boolean; }; meta?: { path?: { label: string; widget: string; index_file: string } }; @@ -515,12 +516,20 @@ declare module 'decap-cms-core' { handler: ({ entry, author, + context, }: { entry: Map; author: { login: string; name: string }; + context?: HookContext; }) => any; } + export interface HookContext { + publishStack?: boolean; + actions?: Record; + [key: string]: any; + } + export type CmsEventListenerOptions = any; // TODO: type properly export type CmsLocalePhrases = any; // TODO: type properly diff --git a/packages/decap-cms-core/package.json b/packages/decap-cms-core/package.json index 59654f5a0fe4..1f678f4ab1d9 100644 --- a/packages/decap-cms-core/package.json +++ b/packages/decap-cms-core/package.json @@ -1,7 +1,7 @@ { "name": "decap-cms-core", "description": "Decap CMS core application, see decap-cms package for the main distribution.", - "version": "3.5.0", + "version": "3.6.2", "repository": "https://github.com/decaporg/decap-cms/tree/main/packages/decap-cms-core", "bugs": "https://github.com/decaporg/decap-cms/issues", "module": "dist/esm/index.js", @@ -26,6 +26,7 @@ "dependencies": { "@iarna/toml": "2.2.5", "@reduxjs/toolkit": "^1.9.1", + "@vercel/stega": "^0.1.2", "ajv": "8.12.0", "ajv-errors": "^3.0.0", "ajv-keywords": "^5.0.0", diff --git a/packages/decap-cms-core/src/actions/__tests__/entries.spec.js b/packages/decap-cms-core/src/actions/__tests__/entries.spec.js index 40697cb5ff10..1827cc588590 100644 --- a/packages/decap-cms-core/src/actions/__tests__/entries.spec.js +++ b/packages/decap-cms-core/src/actions/__tests__/entries.spec.js @@ -3,7 +3,7 @@ import configureMockStore from 'redux-mock-store'; import thunk from 'redux-thunk'; import { - createEmptyDraft, + createLocalEmptyDraft, createEmptyDraftData, retrieveLocalBackup, persistLocalBackup, @@ -40,7 +40,7 @@ describe('entries', () => { fields: [{ name: 'title' }], }); - return store.dispatch(createEmptyDraft(collection, '')).then(() => { + return store.dispatch(createLocalEmptyDraft(collection, '')).then(() => { const actions = store.getActions(); expect(actions).toHaveLength(1); @@ -73,7 +73,7 @@ describe('entries', () => { fields: [{ name: 'title' }, { name: 'boolean' }], }); - return store.dispatch(createEmptyDraft(collection, '?title=title&boolean=True')).then(() => { + return store.dispatch(createLocalEmptyDraft(collection, '?title=title&boolean=True')).then(() => { const actions = store.getActions(); expect(actions).toHaveLength(1); @@ -107,7 +107,7 @@ describe('entries', () => { }); return store - .dispatch(createEmptyDraft(collection, "?title=")) + .dispatch(createLocalEmptyDraft(collection, "?title=")) .then(() => { const actions = store.getActions(); expect(actions).toHaveLength(1); diff --git a/packages/decap-cms-core/src/actions/editorialWorkflow.ts b/packages/decap-cms-core/src/actions/editorialWorkflow.ts index b19914c98937..51b9ed2b7893 100644 --- a/packages/decap-cms-core/src/actions/editorialWorkflow.ts +++ b/packages/decap-cms-core/src/actions/editorialWorkflow.ts @@ -39,6 +39,7 @@ import type { AnyAction } from 'redux'; import type { EntryValue } from '../valueObjects/Entry'; import type { Status } from '../constants/publishModes'; import type { ThunkDispatch } from 'redux-thunk'; +import type { HookContext } from '../backend'; /* * Constant Declarations @@ -67,6 +68,8 @@ export const UNPUBLISHED_ENTRY_DELETE_REQUEST = 'UNPUBLISHED_ENTRY_DELETE_REQUES export const UNPUBLISHED_ENTRY_DELETE_SUCCESS = 'UNPUBLISHED_ENTRY_DELETE_SUCCESS'; export const UNPUBLISHED_ENTRY_DELETE_FAILURE = 'UNPUBLISHED_ENTRY_DELETE_FAILURE'; +export const UNPUBLISHED_ENTRY_DISMISS_ERROR = 'UNPUBLISHED_ENTRY_DISMISS_ERROR'; + /* * Simple Action Creators (Internal) */ @@ -271,6 +274,7 @@ export function loadUnpublishedEntry(collection: Collection, slug: string) { dispatch(unpublishedEntryLoaded(collection, entry)); dispatch(createDraftFromEntry(entry)); } catch (error) { + if (error.name === UNPUBLISHED_ENTRY_DISMISS_ERROR) return; if (error.name === EDITORIAL_WORKFLOW_ERROR && error.notUnderEditorialWorkflow) { dispatch(unpublishedEntryRedirected(collection, slug)); dispatch(loadEntry(collection, slug)); @@ -301,7 +305,7 @@ export function loadUnpublishedEntries(collections: Collections) { } dispatch(unpublishedEntriesLoading()); - backend + return backend .unpublishedEntries(collections) .then(response => dispatch(unpublishedEntriesLoaded(response.entries, response.pagination))) .catch((error: Error) => { @@ -321,21 +325,26 @@ export function loadUnpublishedEntries(collections: Collections) { }; } -export function persistUnpublishedEntry(collection: Collection, existingUnpublishedEntry: boolean) { +export function persistUnpublishedEntry( + collection: Collection, + existingUnpublishedEntry: boolean, + context: HookContext, + customEntryDraft?: EntryDraft, +) { return async (dispatch: ThunkDispatch, getState: () => State) => { const state = getState(); - const entryDraft = state.entryDraft; + const entryDraft = customEntryDraft || state.entryDraft; + const isCustomEntry = customEntryDraft && entryDraft.getIn(['entry', 'isCustomEntry'], true); + const status = customEntryDraft && customEntryDraft.getIn(['entry', 'status']); const fieldsErrors = entryDraft.get('fieldsErrors'); const unpublishedSlugs = selectUnpublishedSlugs(state, collection.get('name')); const publishedSlugs = selectPublishedSlugs(state, collection.get('name')); const usedSlugs = publishedSlugs.concat(unpublishedSlugs) as List; const entriesLoaded = get(state.editorialWorkflow.toJS(), 'pages.ids', false); - //load unpublishedEntries !entriesLoaded && dispatch(loadUnpublishedEntries(state.collections)); - // Early return if draft contains validation errors - if (!fieldsErrors.isEmpty()) { + if (fieldsErrors && !fieldsErrors.isEmpty()) { const hasPresenceErrors = fieldsErrors.some(errors => errors.some(error => error.type && error.type === ValidationErrorTypes.PRESENCE), ); @@ -375,6 +384,8 @@ export function persistUnpublishedEntry(collection: Collection, existingUnpublis entryDraft: serializedEntryDraft, assetProxies, usedSlugs, + context, + status, }); dispatch( addNotification({ @@ -385,12 +396,16 @@ export function persistUnpublishedEntry(collection: Collection, existingUnpublis dismissAfter: 4000, }), ); - dispatch(unpublishedEntryPersisted(collection, serializedEntry)); - if (entry.get('slug') !== newSlug) { - await dispatch(loadUnpublishedEntry(collection, newSlug)); - navigateToEntry(collection.get('name'), newSlug); + if (!isCustomEntry) { + dispatch(unpublishedEntryPersisted(collection, serializedEntry)); + if (entry.get('slug') !== newSlug) { + await dispatch(loadUnpublishedEntry(collection, newSlug)); + navigateToEntry(collection.get('name'), newSlug); + } } + + return newSlug; } catch (error) { dispatch( addNotification({ @@ -483,17 +498,19 @@ export function deleteUnpublishedEntry(collection: string, slug: string) { export function publishUnpublishedEntry( collectionName: string, slug: string, - publishStack: boolean, + context: HookContext, + customEntry?: EntryMap, ) { return async (dispatch: ThunkDispatch, getState: () => State) => { const state = getState(); const collections = state.collections; const backend = currentBackend(state.config); - const entry = selectUnpublishedEntry(state, collectionName, slug); + const entry = customEntry || selectUnpublishedEntry(state, collectionName, slug); + const isCustomEntry = customEntry && customEntry.get('isCustomEntry', true); const isDeleteWorkflow = entry.get('isDeleteWorkflow'); dispatch(unpublishedEntryPublishRequest(collectionName, slug)); try { - if (!publishStack && state.stack.status.status) { + if (!context.publishStack && state.stack.status.status) { dispatch( addNotification({ message: { @@ -507,7 +524,7 @@ export function publishUnpublishedEntry( return dispatch(unpublishedEntryPublishError(collectionName, slug)); } - await backend.publishUnpublishedEntry(entry, publishStack); + await backend.publishUnpublishedEntry(entry, context); await dispatch(checkStackStatus()); @@ -522,21 +539,24 @@ export function publishUnpublishedEntry( }), ); dispatch(unpublishedEntryPublished(collectionName, slug)); - const collection = collections.get(collectionName); - if (collection.has('nested')) { - dispatch(loadEntries(collection)); - const newSlug = slugFromCustomPath(collection, entry.get('path')); - loadEntry(collection, newSlug); - if (slug !== newSlug && selectEditingDraft(state.entryDraft)) { - navigateToEntry(collection.get('name'), newSlug); + if (!isCustomEntry) { + const collection = collections.get(collectionName); + if (!collection.has('nested')) { + dispatch(loadEntries(collection)); + const newSlug = slugFromCustomPath(collection, entry.get('path')); + loadEntry(collection, newSlug); + if (slug !== newSlug && selectEditingDraft(state.entryDraft)) { + navigateToEntry(collection.get('name'), newSlug); + } + } else if (isDeleteWorkflow) { + dispatch(unpublishedEntryDeleted(collectionName, slug)); + return navigateToCollection(collectionName); + } else { + return dispatch(loadEntry(collection, slug)); } - } else if (isDeleteWorkflow) { - dispatch(unpublishedEntryDeleted(collectionName, slug)); - return navigateToCollection(collectionName); - } else { - return dispatch(loadEntry(collection, slug)); } } catch (error) { + if (error.name === UNPUBLISHED_ENTRY_DISMISS_ERROR) return; dispatch( addNotification({ message: { key: 'ui.toast.onFailToPublishEntry', details: error }, @@ -549,11 +569,16 @@ export function publishUnpublishedEntry( }; } -export function unpublishPublishedEntry(collection: Collection, slug: string) { +export function unpublishPublishedEntry( + collection: Collection, + slug: string, + customEntry?: EntryMap, +) { return (dispatch: ThunkDispatch, getState: () => State) => { const state = getState(); const backend = currentBackend(state.config); - const entry = selectEntry(state, collection.get('name'), slug); + const entry = customEntry || selectEntry(state, collection.get('name'), slug); + const isCustomEntry = customEntry && customEntry.get('isCustomEntry', true); const entryDraft = Map().set('entry', entry) as unknown as EntryDraft; dispatch(unpublishedEntryPersisting(collection, slug)); return backend @@ -566,14 +591,16 @@ export function unpublishPublishedEntry(collection: Collection, slug: string) { entryDraft, assetProxies: [], usedSlugs: List(), - status: status.get('PENDING_PUBLISH'), + status: customEntry ? customEntry.get('status') : status.get('PENDING_PUBLISH'), }); } }) .then(() => { - dispatch(unpublishedEntryPersisted(collection, entry)); dispatch(entryDeleted(collection, slug)); - dispatch(loadUnpublishedEntry(collection, slug)); + if (!isCustomEntry) { + dispatch(unpublishedEntryPersisted(collection, entry)); + dispatch(loadUnpublishedEntry(collection, slug)); + } dispatch( addNotification({ message: { @@ -598,3 +625,20 @@ export function unpublishPublishedEntry(collection: Collection, slug: string) { }); }; } + +export function getUnpublishedEntries(collectionName?: string) { + return async (dispatch: ThunkDispatch, getState: () => State) => { + const state = getState(); + const entriesLoaded = get(state.editorialWorkflow.toJS(), 'pages.ids', false); + + if (!entriesLoaded) { + await dispatch(loadUnpublishedEntries(state.collections)); + } + + const unpublishedEntries = state.editorialWorkflow.get('entities'); + const entries = collectionName + ? unpublishedEntries.filter(entry => entry.get('collection') === collectionName) + : unpublishedEntries; + return List(entries.valueSeq()); + }; +} diff --git a/packages/decap-cms-core/src/actions/entries.ts b/packages/decap-cms-core/src/actions/entries.ts index d3fa33cf845b..1346f9735613 100644 --- a/packages/decap-cms-core/src/actions/entries.ts +++ b/packages/decap-cms-core/src/actions/entries.ts @@ -20,7 +20,7 @@ import { selectCustomPath } from '../reducers/entryDraft'; import { navigateToCollection, navigateToEntry } from '../routing/history'; import { getProcessSegment } from '../lib/formatters'; import { hasI18n, duplicateDefaultI18nFields, serializeI18n, I18N, I18N_FIELD } from '../lib/i18n'; -import { loadUnpublishedEntry } from './editorialWorkflow'; +import { loadUnpublishedEntry, UNPUBLISHED_ENTRY_DISMISS_ERROR } from './editorialWorkflow'; import { addNotification } from './notifications'; import type { ImplementationMediaFile } from 'decap-cms-lib-util'; @@ -35,9 +35,10 @@ import type { ViewFilter, ViewGroup, Entry, + EntryDraft, } from '../types/redux'; import type { EntryValue } from '../valueObjects/Entry'; -import type { Backend } from '../backend'; +import type { Backend, HookContext } from '../backend'; import type AssetProxy from '../valueObjects/AssetProxy'; import type { Set } from 'immutable'; @@ -323,6 +324,7 @@ export function entryPersisted(collection: Collection, entry: EntryMap, slug: st * Pass slug from backend for newly created entries. */ slug, + entry, }, }; } @@ -391,6 +393,7 @@ export function draftDuplicateEntry(entry: EntryMap) { type: DRAFT_CREATE_DUPLICATE_FROM_ENTRY, payload: createEntry(entry.get('collection'), '', '', { data: entry.get('data'), + i18n: entry.get('i18n'), mediaFiles: entry.get('mediaFiles').toJS(), }), }; @@ -766,6 +769,14 @@ export function createEmptyDraft(collection: Collection, search: string) { meta: meta as any, }); newEntry = await backend.processEntry(state, collection, newEntry); + + return newEntry; + }; +} + +export function createLocalEmptyDraft(collection: Collection, search: string) { + return async (dispatch: ThunkDispatch, getState: () => State) => { + const newEntry = await createEmptyDraft(collection, search)(dispatch, getState); dispatch(emptyDraftCreated(newEntry)); }; } @@ -885,15 +896,18 @@ export function getSerializedEntry(collection: Collection, entry: Entry) { return serializedEntry; } -export function persistEntry(collection: Collection, publishStack?: boolean) { +export function persistEntry( + collection: Collection, + context: HookContext, + customEntryDraft?: EntryDraft, +) { return async (dispatch: ThunkDispatch, getState: () => State) => { const state = getState(); - const entryDraft = state.entryDraft; + const entryDraft = customEntryDraft || state.entryDraft; + const fieldsErrors = entryDraft.get('fieldsErrors'); - const usedSlugs = selectPublishedSlugs(state, collection.get('name')); - // Early return if draft contains validation errors - if (!fieldsErrors.isEmpty()) { + if (fieldsErrors && !fieldsErrors.isEmpty()) { const hasPresenceErrors = fieldsErrors.some(errors => errors.some(error => error.type && error.type === ValidationErrorTypes.PRESENCE), ); @@ -913,15 +927,21 @@ export function persistEntry(collection: Collection, publishStack?: boolean) { return Promise.reject(); } + const usedSlugs = selectPublishedSlugs(state, collection.get('name')); + const backend = currentBackend(state.config); const entry = entryDraft.get('entry'); + const isCustomEntry = customEntryDraft && entry.get('isCustomEntry', true); + const status = customEntryDraft && entry.get('status'); const assetProxies = getMediaAssets({ entry, }); const serializedEntry = getSerializedEntry(collection, entry); const serializedEntryDraft = entryDraft.set('entry', serializedEntry); - dispatch(entryPersisting(collection, serializedEntry)); + if (!isCustomEntry) { + dispatch(entryPersisting(collection, serializedEntry)); + } return backend .persistEntry({ config: state.config, @@ -929,7 +949,8 @@ export function persistEntry(collection: Collection, publishStack?: boolean) { entryDraft: serializedEntryDraft, assetProxies, usedSlugs, - publishStack, + context, + status, }) .then(async (newSlug: string) => { dispatch( @@ -942,44 +963,57 @@ export function persistEntry(collection: Collection, publishStack?: boolean) { }), ); - // re-load media library if entry had media files - if (assetProxies.length > 0) { - await dispatch(loadMedia()); - } - dispatch(entryPersisted(collection, serializedEntry, newSlug)); - if (collection.has('nested')) { - await dispatch(loadEntries(collection)); - } - if (entry.get('slug') !== newSlug) { - await dispatch(loadEntry(collection, newSlug)); - navigateToEntry(collection.get('name'), newSlug); + if (!isCustomEntry) { + // re-load media library if entry had media files + if (assetProxies.length > 0) { + await dispatch(loadMedia()); + } + dispatch(entryPersisted(collection, serializedEntry, newSlug)); + if (collection.has('nested')) { + await dispatch(loadEntries(collection)); + } + if (entry.get('slug') !== newSlug) { + await dispatch(loadEntry(collection, newSlug)); + navigateToEntry(collection.get('name'), newSlug); + } } + + return newSlug; }) .catch((error: Error) => { - console.error(error); - dispatch( - addNotification({ - message: { - details: error, - key: 'ui.toast.onFailToPersist', - }, - type: 'error', - dismissAfter: 8000, - }), - ); + if (error.name !== UNPUBLISHED_ENTRY_DISMISS_ERROR) { + console.error(error); + dispatch( + addNotification({ + message: { + details: error, + key: 'ui.toast.onFailToPersist', + }, + type: 'error', + dismissAfter: 8000, + }), + ); + } + return Promise.reject(dispatch(entryPersistFail(collection, serializedEntry, error))); }); }; } -export function deleteEntry(collection: Collection, slug: string) { +export function deleteEntry( + collection: Collection, + slug: string, + context: HookContext, + entry?: EntryMap, +) { return (dispatch: ThunkDispatch, getState: () => State) => { const state = getState(); const backend = currentBackend(state.config); + const isCustomEntry = entry && entry.get('isCustomEntry', true); dispatch(entryDeleting(collection, slug)); return backend - .deleteEntry(state, collection, slug) + .deleteEntry(state, collection, slug, context, entry) .then(async () => { dispatch(entryDeleted(collection, slug)); dispatch( @@ -993,24 +1027,29 @@ export function deleteEntry(collection: Collection, slug: string) { dismissAfter: 4000, }), ); - if (backend.implementation.deleteCollectionFiles) { - dispatch(loadUnpublishedEntry(collection, slug)); - } else { - navigateToCollection(collection.get('name')); + if (!isCustomEntry) { + if (backend.implementation.deleteCollectionFiles) { + dispatch(loadUnpublishedEntry(collection, slug)); + } else { + navigateToCollection(collection.get('name')); + } } }) .catch((error: Error) => { - dispatch( - addNotification({ - message: { - details: error, - key: 'ui.toast.onFailToDelete', - }, - type: 'error', - dismissAfter: 8000, - }), - ); - console.error(error); + if (error.name !== UNPUBLISHED_ENTRY_DISMISS_ERROR) { + console.error(error); + dispatch( + addNotification({ + message: { + details: error, + key: 'ui.toast.onFailToDelete', + }, + type: 'error', + dismissAfter: 8000, + }), + ); + } + return Promise.reject(dispatch(entryDeleteFail(collection, slug, error))); }); }; diff --git a/packages/decap-cms-core/src/backend.ts b/packages/decap-cms-core/src/backend.ts index 62e30340943c..ce1cdeb9696d 100644 --- a/packages/decap-cms-core/src/backend.ts +++ b/packages/decap-cms-core/src/backend.ts @@ -146,7 +146,7 @@ export function extractSearchFields(searchFields: string[]) { searchFields.reduce((acc, field) => { const value = getEntryField(field, entry); if (value) { - return `${acc} ${value}`; + return acc ? `${acc} ${value}` : value; } else { return acc; } @@ -276,9 +276,9 @@ interface PersistArgs { entryDraft: EntryDraft; assetProxies: AssetProxy[]; usedSlugs: List; - publishStack?: boolean; unpublished?: boolean; status?: string; + context?: HookContext; } interface ImplementationInitOptions { @@ -291,6 +291,11 @@ type Implementation = BackendImplementation & { init: (config: CmsConfig, options: ImplementationInitOptions) => Implementation; }; +export interface HookContext { + publishStack?: boolean; + actions?: Record; +} + function prepareMetaPath(path: string, collection: Collection) { if (!selectHasMetaPath(collection)) { return path; @@ -617,6 +622,17 @@ export class Backend { // Perform a local search by requesting all entries. For each // collection, load it, search, and call onCollectionResults with // its results. + + if (searchTerm === null) { + const allEntries = await Promise.all( + collections.map(async collection => { + const entries = await this.listAllEntries(collection); + return entries; + }), + ); + return { entries: flatten(allEntries) }; + } + const errors: Error[] = []; const collectionEntriesRequests = collections .map(async collection => { @@ -703,7 +719,7 @@ export class Backend { } const merged = mergeExpandedEntries(hits); - return { query: searchTerm, hits: merged }; + return { query: searchTerm, hits: merged, collection }; } traverseCursor(cursor: Cursor, action: string) { @@ -949,7 +965,7 @@ export class Backend { data, dataFile.path, dataFile.newFile, - dataFile.deletedFile, + dataFile.deleteFile, ); return entryWithFormat; }; @@ -1103,11 +1119,11 @@ export class Backend { entryDraft: draft, assetProxies, usedSlugs, - publishStack = false, unpublished = false, status, + context, }: PersistArgs) { - const updatedEntity = await this.invokePreSaveEvent(draft.get('entry')); + const updatedEntity = await this.invokePreSaveEvent(draft.get('entry'), context); let entryDraft; if (updatedEntity.get('data') === undefined) { @@ -1144,12 +1160,13 @@ export class Backend { updateAssetProxies(assetProxies, config, collection, entryDraft, path); } else { const slug = entryDraft.getIn(['entry', 'slug']); + const path = entryDraft.getIn(['entry', 'path']); dataFile = { - path: entryDraft.getIn(['entry', 'path']), + path, // for workflow entries we refresh the slug on publish slug: customPath && !useWorkflow ? slugFromCustomPath(collection, customPath) : slug, raw: await this.entryToRaw(collection, entryDraft.get('entry')), - newPath: customPath, + newPath: customPath === path ? undefined : customPath, }; } @@ -1191,12 +1208,12 @@ export class Backend { commitMessage, collectionName, useWorkflow, - publishStack, + publishStack: context?.publishStack || false, ...updatedOptions, }; if (!useWorkflow) { - await this.invokePrePublishEvent(entryDraft.get('entry')); + await this.invokePrePublishEvent(entryDraft.get('entry'), context); } await this.implementation.persistEntry( @@ -1207,42 +1224,45 @@ export class Backend { opts, ); - await this.invokePostSaveEvent(entryDraft.get('entry')); + await this.invokePostSaveEvent(entryDraft.get('entry'), context); if (!useWorkflow) { - await this.invokePostPublishEvent(entryDraft.get('entry')); + await this.invokePostPublishEvent(entryDraft.get('entry'), context); } return slug; } - async invokeEventWithEntry(event: string, entry: EntryMap) { + async invokeEventWithEntry(event: string, entry: EntryMap, context: HookContext = {}) { const { login, name } = (await this.currentUser()) as User; - return await invokeEvent({ name: event, data: { entry, author: { login, name } } }); + return await invokeEvent({ + name: event, + data: { entry, author: { login, name }, context }, + }); } - async invokePrePublishEvent(entry: EntryMap) { - await this.invokeEventWithEntry('prePublish', entry); + async invokePrePublishEvent(entry: EntryMap, context?: HookContext) { + await this.invokeEventWithEntry('prePublish', entry, context); } - async invokePostPublishEvent(entry: EntryMap) { - await this.invokeEventWithEntry('postPublish', entry); + async invokePostPublishEvent(entry: EntryMap, context?: HookContext) { + await this.invokeEventWithEntry('postPublish', entry, context); } - async invokePreUnpublishEvent(entry: EntryMap) { - await this.invokeEventWithEntry('preUnpublish', entry); + async invokePreUnpublishEvent(entry: EntryMap, context?: HookContext) { + await this.invokeEventWithEntry('preUnpublish', entry, context); } - async invokePostUnpublishEvent(entry: EntryMap) { - await this.invokeEventWithEntry('postUnpublish', entry); + async invokePostUnpublishEvent(entry: EntryMap, context?: HookContext) { + await this.invokeEventWithEntry('postUnpublish', entry, context); } - async invokePreSaveEvent(entry: EntryMap) { - return await this.invokeEventWithEntry('preSave', entry); + async invokePreSaveEvent(entry: EntryMap, context?: HookContext) { + return await this.invokeEventWithEntry('preSave', entry, context); } - async invokePostSaveEvent(entry: EntryMap) { - await this.invokeEventWithEntry('postSave', entry); + async invokePostSaveEvent(entry: EntryMap, context?: HookContext) { + await this.invokeEventWithEntry('postSave', entry, context); } async persistMedia(config: CmsConfig, file: AssetProxy) { @@ -1262,10 +1282,17 @@ export class Backend { return this.implementation.persistMedia(file, options); } - async deleteEntry(state: State, collection: Collection, slug: string) { + async deleteEntry( + state: State, + collection: Collection, + slug: string, + context?: HookContext, + customEntry?: EntryMap, + ) { const config = state.config; const path = selectEntryPath(collection, slug) as string; const extension = selectFolderEntryExtension(collection) as string; + const entry = customEntry || selectEntry(state.entries, collection.get('name'), slug); if (!selectAllowDeletion(collection)) { throw new Error('Not allowed to delete entries in this collection'); @@ -1285,8 +1312,7 @@ export class Backend { user.useOpenAuthoring, ); - const entry = selectEntry(state.entries, collection.get('name'), slug); - await this.invokePreUnpublishEvent(entry); + await this.invokePreUnpublishEvent(entry, context); let paths = [path]; if (hasI18n(collection)) { paths = getFilePaths(collection, extension, path, slug); @@ -1303,7 +1329,7 @@ export class Backend { await this.implementation.deleteFiles(paths, commitMessage); } - await this.invokePostUnpublishEvent(entry); + await this.invokePostUnpublishEvent(entry, context); } async deleteMedia(config: CmsConfig, path: string) { @@ -1329,11 +1355,11 @@ export class Backend { return this.implementation.updateUnpublishedEntryStatus!(collection, slug, newStatus); } - async publishUnpublishedEntry(entry: EntryMap, publishStack?: boolean) { + async publishUnpublishedEntry(entry: EntryMap, context: HookContext) { const collection = entry.get('collection'); const slug = entry.get('slug'); - await this.invokePrePublishEvent(entry); + await this.invokePrePublishEvent(entry, context); const config = this.config; if (config.backend.stack) { @@ -1350,13 +1376,13 @@ export class Backend { ); await this.implementation.publishUnpublishedEntryStack!(collection, slug, { stackCommitMessage, - publishStack, + publishStack: context.publishStack, }); } else { await this.implementation.publishUnpublishedEntry!(collection, slug); } - await this.invokePostPublishEvent(entry); + await this.invokePostPublishEvent(entry, context); } deleteUnpublishedEntry(collection: string, slug: string) { diff --git a/packages/decap-cms-core/src/components/App/StackToolbar.js b/packages/decap-cms-core/src/components/App/StackToolbar.js index 7ff2ce385889..f7653fe2bc1f 100644 --- a/packages/decap-cms-core/src/components/App/StackToolbar.js +++ b/packages/decap-cms-core/src/components/App/StackToolbar.js @@ -90,6 +90,13 @@ const StatusButton = styled(DropdownButton)` background-color: ${colorsRaw.tealLight}; color: ${colorsRaw.teal}; + ${props => + props.label === 'processing' && + css` + background-color: ${colors.processingBackground}; + color: ${colors.processingText}; + `} + ${props => props.label === 'stale' && css` @@ -164,6 +171,7 @@ export class EditorToolbar extends React.Component { [status.get('DRAFT')]: t('editor.editorToolbar.draft'), [status.get('PENDING_REVIEW')]: t('editor.editorToolbar.inReview'), [status.get('PENDING_PUBLISH')]: t('editor.editorToolbar.ready'), + [status.get('PROCESSING')]: t('editor.editorToolbar.inProcessing'), [status.get('STALE')]: t('editor.editorToolbar.inStale'), }; diff --git a/packages/decap-cms-core/src/components/Collection/Entries/EntriesCollection.js b/packages/decap-cms-core/src/components/Collection/Entries/EntriesCollection.js index 830f7911de8c..7d7471872d4c 100644 --- a/packages/decap-cms-core/src/components/Collection/Entries/EntriesCollection.js +++ b/packages/decap-cms-core/src/components/Collection/Entries/EntriesCollection.js @@ -117,22 +117,28 @@ export class EntriesCollection extends React.Component { } } -export function filterNestedEntries(path, collectionFolder, entries) { +export function filterNestedEntries(path, collectionFolder, entries, subfolders) { const filtered = entries.filter(e => { - const entryPath = e.get('path').slice(collectionFolder.length + 1); + let entryPath = e.get('path').slice(collectionFolder.length + 1); if (!entryPath.startsWith(path)) { return false; } - // only show immediate children + // for subdirectories, trim off the parent folder corresponding to + // this nested collection entry if (path) { - // non root path - const trimmed = entryPath.slice(path.length + 1); - return trimmed.split('/').length === 2; - } else { - // root path - return entryPath.split('/').length <= 2; + entryPath = entryPath.slice(path.length + 1); + } + + // if subfolders legacy mode is enabled, show only immediate subfolders + // also show index file in root folder + if (subfolders) { + const depth = entryPath.split('/').length; + return path ? depth === 2 : depth <= 2; } + + // only show immediate children + return !entryPath.includes('/'); }); return filtered; } @@ -146,7 +152,12 @@ function mapStateToProps(state, ownProps) { if (collection.has('nested')) { const collectionFolder = collection.get('folder'); - entries = filterNestedEntries(filterTerm || '', collectionFolder, entries); + entries = filterNestedEntries( + filterTerm || '', + collectionFolder, + entries, + collection.get('nested').get('subfolders') !== false, + ); } const entriesLoaded = selectEntriesLoaded(state.entries, collection.get('name')); const isFetching = selectIsFetching(state.entries, collection.get('name')); diff --git a/packages/decap-cms-core/src/components/Collection/Entries/__tests__/EntriesCollection.spec.js b/packages/decap-cms-core/src/components/Collection/Entries/__tests__/EntriesCollection.spec.js index 5afbd19b19e2..c1aedfa9c464 100644 --- a/packages/decap-cms-core/src/components/Collection/Entries/__tests__/EntriesCollection.spec.js +++ b/packages/decap-cms-core/src/components/Collection/Entries/__tests__/EntriesCollection.spec.js @@ -45,11 +45,11 @@ describe('filterNestedEntries', () => { ]; const entries = fromJS(entriesArray); expect(filterNestedEntries('dir3', 'src/pages', entries).toJS()).toEqual([ - { slug: 'dir3/dir4/index', path: 'src/pages/dir3/dir4/index.md', data: { title: 'File 4' } }, + { slug: 'dir3/index', path: 'src/pages/dir3/index.md', data: { title: 'File 3' } }, ]); }); - it('should return immediate children and root for root path', () => { + it('should return only immediate children for root path', () => { const entriesArray = [ { slug: 'index', path: 'src/pages/index.md', data: { title: 'Root' } }, { slug: 'dir1/index', path: 'src/pages/dir1/index.md', data: { title: 'File 1' } }, @@ -60,8 +60,6 @@ describe('filterNestedEntries', () => { const entries = fromJS(entriesArray); expect(filterNestedEntries('', 'src/pages', entries).toJS()).toEqual([ { slug: 'index', path: 'src/pages/index.md', data: { title: 'Root' } }, - { slug: 'dir1/index', path: 'src/pages/dir1/index.md', data: { title: 'File 1' } }, - { slug: 'dir3/index', path: 'src/pages/dir3/index.md', data: { title: 'File 3' } }, ]); }); }); @@ -117,7 +115,9 @@ describe('EntriesCollection', () => { }); const { asFragment } = renderWithRedux( - , + , { store, }, @@ -126,7 +126,7 @@ describe('EntriesCollection', () => { expect(asFragment()).toMatchSnapshot(); }); - it('should render apply filter term for nested collections', () => { + it('should render with applied filter term for nested collections', () => { const entriesArray = [ { slug: 'index', path: 'src/pages/index.md', data: { title: 'Root' } }, { slug: 'dir1/index', path: 'src/pages/dir1/index.md', data: { title: 'File 1' } }, @@ -142,7 +142,7 @@ describe('EntriesCollection', () => { const { asFragment } = renderWithRedux( , { diff --git a/packages/decap-cms-core/src/components/Collection/Entries/__tests__/__snapshots__/EntriesCollection.spec.js.snap b/packages/decap-cms-core/src/components/Collection/Entries/__tests__/__snapshots__/EntriesCollection.spec.js.snap index ccc4d5911e89..6066c5547fc1 100644 --- a/packages/decap-cms-core/src/components/Collection/Entries/__tests__/__snapshots__/EntriesCollection.spec.js.snap +++ b/packages/decap-cms-core/src/components/Collection/Entries/__tests__/__snapshots__/EntriesCollection.spec.js.snap @@ -1,36 +1,36 @@ // Jest Snapshot v1, https://goo.gl/fbAQLP -exports[`EntriesCollection should render apply filter term for nested collections 1`] = ` +exports[`EntriesCollection should render connected component 1`] = ` `; -exports[`EntriesCollection should render connected component 1`] = ` +exports[`EntriesCollection should render show only immediate children for nested collection 1`] = ` `; -exports[`EntriesCollection should render show only immediate children for nested collection 1`] = ` +exports[`EntriesCollection should render with applied filter term for nested collections 1`] = ` diff --git a/packages/decap-cms-core/src/components/Collection/NestedCollection.js b/packages/decap-cms-core/src/components/Collection/NestedCollection.js index 0cc9a068c870..b5f0b1fac865 100644 --- a/packages/decap-cms-core/src/components/Collection/NestedCollection.js +++ b/packages/decap-cms-core/src/components/Collection/NestedCollection.js @@ -79,8 +79,13 @@ function TreeNode(props) { const collectionName = collection.get('name'); const sortedData = sortBy(treeData, getNodeTitle); + const subfolders = collection.get('nested')?.get('subfolders') !== false; return sortedData.map(node => { - const leaf = node.children.length <= 1 && !node.children[0]?.isDir && depth > 0; + const leaf = + depth > 0 && + (subfolders + ? node.children.length <= 1 && !node.children[0]?.isDir + : node.children.length === 0); if (leaf) { return null; } @@ -90,7 +95,11 @@ function TreeNode(props) { } const title = getNodeTitle(node); - const hasChildren = depth === 0 || node.children.some(c => c.children.some(c => c.isDir)); + const hasChildren = + depth === 0 || + (subfolders + ? node.children.some(c => c.children.some(c => c.isDir)) + : node.children.some(c => c.isDir)); return ( diff --git a/packages/decap-cms-core/src/components/Collection/__tests__/NestedCollection.spec.js b/packages/decap-cms-core/src/components/Collection/__tests__/NestedCollection.spec.js index 86380fde54ea..bdeac4040567 100644 --- a/packages/decap-cms-core/src/components/Collection/__tests__/NestedCollection.spec.js +++ b/packages/decap-cms-core/src/components/Collection/__tests__/NestedCollection.spec.js @@ -37,6 +37,9 @@ describe('NestedCollection', () => { label: 'Pages', folder: 'src/pages', fields: [{ name: 'title', widget: 'string' }], + nested: { + subfolders: false, + }, }); it('should render correctly with no entries', () => { diff --git a/packages/decap-cms-core/src/components/Collection/__tests__/__snapshots__/NestedCollection.spec.js.snap b/packages/decap-cms-core/src/components/Collection/__tests__/__snapshots__/NestedCollection.spec.js.snap index dd3f5fcd55ac..b643246f4411 100644 --- a/packages/decap-cms-core/src/components/Collection/__tests__/__snapshots__/NestedCollection.spec.js.snap +++ b/packages/decap-cms-core/src/components/Collection/__tests__/__snapshots__/NestedCollection.spec.js.snap @@ -138,6 +138,20 @@ exports[`NestedCollection should render connected component 1`] = ` margin-right: 4px; } +.emotion-6 { + position: relative; + top: 2px; + color: #fff; + width: 0; + height: 0; + border: 5px solid transparent; + border-radius: 2px; + border-left: 6px solid currentColor; + border-right: 0; + color: currentColor; + left: 2px; +} + File 1 +
.emotion-0 { @@ -207,6 +224,20 @@ exports[`NestedCollection should render connected component 1`] = ` margin-right: 4px; } +.emotion-6 { + position: relative; + top: 2px; + color: #fff; + width: 0; + height: 0; + border: 5px solid transparent; + border-radius: 2px; + border-left: 6px solid currentColor; + border-right: 0; + color: currentColor; + left: 2px; +} + File 2 +
@@ -367,6 +401,20 @@ exports[`NestedCollection should render correctly with nested entries 1`] = ` margin-right: 4px; } +.emotion-6 { + position: relative; + top: 2px; + color: #fff; + width: 0; + height: 0; + border: 5px solid transparent; + border-radius: 2px; + border-left: 6px solid currentColor; + border-right: 0; + color: currentColor; + left: 2px; +} + File 1 +
.emotion-0 { @@ -436,6 +487,20 @@ exports[`NestedCollection should render correctly with nested entries 1`] = ` margin-right: 4px; } +.emotion-6 { + position: relative; + top: 2px; + color: #fff; + width: 0; + height: 0; + border: 5px solid transparent; + border-radius: 2px; + border-left: 6px solid currentColor; + border-right: 0; + color: currentColor; + left: 2px; +} + File 2 +
diff --git a/packages/decap-cms-core/src/components/Editor/Editor.js b/packages/decap-cms-core/src/components/Editor/Editor.js index 385c95733505..7e6a39ab8f2b 100644 --- a/packages/decap-cms-core/src/components/Editor/Editor.js +++ b/packages/decap-cms-core/src/components/Editor/Editor.js @@ -12,6 +12,7 @@ import { loadEntry, loadEntries, createDraftDuplicateFromEntry, + createLocalEmptyDraft, createEmptyDraft, discardDraft, changeDraftField, @@ -25,13 +26,16 @@ import { removeDraftEntryMediaFiles, } from '../../actions/entries'; import { + getUnpublishedEntries, updateUnpublishedEntryStatus, publishUnpublishedEntry, unpublishPublishedEntry, deleteUnpublishedEntry, + persistUnpublishedEntry, } from '../../actions/editorialWorkflow'; import { removeAssets } from '../../actions/media'; import { loadDeployPreview } from '../../actions/deploys'; +import { searchEntries } from '../../actions/search'; import { selectEntry, selectUnpublishedEntry, selectDeployPreview } from '../../reducers'; import { selectFields } from '../../reducers/collections'; import { status, EDITORIAL_WORKFLOW } from '../../constants/publishModes'; @@ -44,12 +48,15 @@ export class Editor extends React.Component { changeDraftFieldValidation: PropTypes.func.isRequired, collection: ImmutablePropTypes.map.isRequired, createDraftDuplicateFromEntry: PropTypes.func.isRequired, + createLocalEmptyDraft: PropTypes.func.isRequired, createEmptyDraft: PropTypes.func.isRequired, discardDraft: PropTypes.func.isRequired, entry: ImmutablePropTypes.map, entryDraft: ImmutablePropTypes.map.isRequired, + getUnpublishedEntries: PropTypes.func.isRequired, loadEntry: PropTypes.func.isRequired, persistEntry: PropTypes.func.isRequired, + persistUnpublishedEntry: PropTypes.func.isRequired, deleteEntry: PropTypes.func.isRequired, showDelete: PropTypes.bool.isRequired, fields: ImmutablePropTypes.list.isRequired, @@ -71,6 +78,7 @@ export class Editor extends React.Component { loadDeployPreview: PropTypes.func.isRequired, currentStatus: PropTypes.string, user: PropTypes.object, + searchEntries: PropTypes.func.isRequired, location: PropTypes.shape({ pathname: PropTypes.string, search: PropTypes.string, @@ -90,7 +98,7 @@ export class Editor extends React.Component { collection, slug, loadEntry, - createEmptyDraft, + createLocalEmptyDraft, loadEntries, // retrieveLocalBackup, collectionEntriesLoaded, @@ -100,7 +108,7 @@ export class Editor extends React.Component { // retrieveLocalBackup(collection, slug); if (newEntry) { - createEmptyDraft(collection, this.props.location.search); + createLocalEmptyDraft(collection, this.props.location.search); } else { loadEntry(collection, slug); } @@ -185,7 +193,7 @@ export class Editor extends React.Component { const { newEntry, collection } = this.props; if (newEntry) { - prevProps.createEmptyDraft(collection, this.props.location.search); + prevProps.createLocalEmptyDraft(collection, this.props.location.search); } } @@ -224,6 +232,57 @@ export class Editor extends React.Component { // deleteLocalBackup(collection, !newEntry && slug); // } + createHookContext = (context) => { + const defaultContext = { + editor: { + props: this.props, + handlePersistEntry: this.handlePersistEntry, + handlePublishEntry: this.handlePublishEntry, + handleUnpublishEntry: this.handleUnpublishEntry, + handleDeleteEntry: this.handleDeleteEntry, + handleDeleteUnpublishedChanges: this.handleDeleteUnpublishedChanges, + handleDuplicateEntry: this.handleDuplicateEntry, + handleChangeStatus: this.handleChangeStatus, + }, + actions: { + persistEntry: async (collection, entry, opts = {}) => { + const context = this.createHookContext(opts); + const entryDraft = entry || this.props.createEmptyDraft(collection); + return this.props.persistEntry(collection, context, entryDraft); + }, + persistUnpublishedEntry: async (collection, existingUnpublishedEntry, entry, opts = {}) => { + const context = this.createHookContext(opts); + const entryDraft = entry || this.props.createEmptyDraft(collection); + return this.props.persistUnpublishedEntry(collection, existingUnpublishedEntry, context, entryDraft); + }, + publishUnpublishedEntry: async (collection, slug, entry, opts = {}) => { + const context = this.createHookContext(opts); + const entryDraft = entry || this.props.createEmptyDraft(collection); + return this.props.publishUnpublishedEntry( + collection.get('name'), + slug, + context, + entryDraft, + ); + }, + deleteUnpublishedEntry: async (collection, slug) => { + return this.props.deleteUnpublishedEntry(collection, slug); + }, + unpublishPublishedEntry: async (collection, slug, entry, opts = {}) => { + const context = this.createHookContext(opts); + return this.props.unpublishPublishedEntry(collection, slug, context, entry); + }, + deleteEntry: async (collection, slug, entry, opts = {}) => { + const context = this.createHookContext(opts); + return this.props.deleteEntry(collection, slug, context, entry); + }, + }, + }; + if (!context) return defaultContext; + + return Object.assign(defaultContext, context); + }; + handlePersistEntry = async (opts = {}) => { const { createNew = false, duplicate = false, publishStack = false } = opts; const { @@ -237,7 +296,7 @@ export class Editor extends React.Component { entryDraft, } = this.props; - await persistEntry(collection, publishStack); + await persistEntry(collection, this.createHookContext({ publishStack })); // this.deleteBackup(); @@ -279,7 +338,11 @@ export class Editor extends React.Component { return; } - await publishUnpublishedEntry(collection.get('name'), slug, publishStack); + await publishUnpublishedEntry( + collection.get('name'), + slug, + this.createHookContext({ publishStack }), + ); // this.deleteBackup(); @@ -294,7 +357,7 @@ export class Editor extends React.Component { const { unpublishPublishedEntry, collection, slug, t } = this.props; if (!window.confirm(t('editor.editor.onUnpublishing'))) return; - await unpublishPublishedEntry(collection, slug); + await unpublishPublishedEntry(collection, slug, this.createHookContext()); // return navigateToCollection(collection.get('name')); }; @@ -320,13 +383,14 @@ export class Editor extends React.Component { } setTimeout(async () => { - await deleteEntry(collection, slug); + await deleteEntry(collection, slug, this.createHookContext()); // this.deleteBackup(); // return navigateToCollection(collection.get('name')); }, 0); }; - handleDeleteUnpublishedChanges = async () => { + handleDeleteUnpublishedChanges = async (opts = {}) => { + const { force = false } = opts; const { entryDraft, collection, @@ -339,17 +403,21 @@ export class Editor extends React.Component { isDeleteWorkflow, t, } = this.props; - if ( - entryDraft.get('hasChanged') && - !window.confirm( - t('editor.editor.onDeleteUnpublishedChangesWithUnsavedChanges') || isDeleteWorkflow, - ) - ) { - return; - } else if (!window.confirm(t('editor.editor.onDeleteUnpublishedChanges'))) { - return; + + if (!force) { + if ( + entryDraft.get('hasChanged') && + !window.confirm( + t('editor.editor.onDeleteUnpublishedChangesWithUnsavedChanges') || isDeleteWorkflow, + ) + ) { + return; + } else if (!window.confirm(t('editor.editor.onDeleteUnpublishedChanges'))) { + return; + } } + await deleteUnpublishedEntry(collection.get('name'), slug); // this.deleteBackup(); @@ -512,6 +580,7 @@ function mapStateToProps(state, ownProps) { const mapDispatchToProps = { changeDraftField, changeDraftFieldValidation, + getUnpublishedEntries, loadEntry, loadEntries, loadDeployPreview, @@ -520,9 +589,11 @@ const mapDispatchToProps = { // persistLocalBackup, // deleteLocalBackup, createDraftDuplicateFromEntry, + createLocalEmptyDraft, createEmptyDraft, discardDraft, persistEntry, + persistUnpublishedEntry, deleteEntry, updateUnpublishedEntryStatus, publishUnpublishedEntry, @@ -531,6 +602,7 @@ const mapDispatchToProps = { removeAssets, removeDraftEntryMediaFiles, logoutUser, + searchEntries, }; export default connect(mapStateToProps, mapDispatchToProps)(withWorkflow(translate()(Editor))); diff --git a/packages/decap-cms-core/src/components/Editor/EditorControlPane/EditorControl.js b/packages/decap-cms-core/src/components/Editor/EditorControlPane/EditorControl.js index ba79e235cf8b..a577cc1ccad9 100644 --- a/packages/decap-cms-core/src/components/Editor/EditorControlPane/EditorControl.js +++ b/packages/decap-cms-core/src/components/Editor/EditorControlPane/EditorControl.js @@ -12,7 +12,7 @@ import ReactMarkdown from 'react-markdown'; import gfm from 'remark-gfm'; import { List, Map } from 'immutable'; -import { resolveWidget, getEditorComponents } from '../../../lib/registry'; +import { resolveWidget, getEditorComponents, getWidget } from '../../../lib/registry'; import { clearFieldErrors, tryLoadEntry, validateMetaField } from '../../../actions/entries'; import { addAsset, boundGetAsset } from '../../../actions/media'; import { selectIsLoadingAsset } from '../../../reducers/medias'; @@ -70,6 +70,9 @@ const styleStrings = { unused: ` opacity: 0.5; `, + flat: ` + margin-top: 0 !important; + ` }; const ControlContainer = styled.div` @@ -143,7 +146,6 @@ class EditorControl extends React.Component { removeInsertedMedia: PropTypes.func.isRequired, persistMedia: PropTypes.func.isRequired, onValidate: PropTypes.func, - processControlRef: PropTypes.func, controlRef: PropTypes.func, query: PropTypes.func.isRequired, queryHits: PropTypes.object, @@ -205,6 +207,7 @@ class EditorControl extends React.Component { value, entry, collection, + collections, config, field, fieldsMetaData, @@ -219,7 +222,6 @@ class EditorControl extends React.Component { removeInsertedMedia, persistMedia, onValidate, - processControlRef, controlRef, query, queryHits, @@ -270,6 +272,7 @@ class EditorControl extends React.Component { css={css` ${!this.state.use && unused && styleStrings.unused} ${isHidden && styleStrings.hidden}; + ${isFlat && styleStrings.flat} `} > {widgetTitle &&

{widgetTitle}

} @@ -337,6 +340,7 @@ class EditorControl extends React.Component { controlComponent={widget.control} entry={entry} collection={collection} + collections={collections} config={config} field={field} uniqueFieldId={this.uniqueFieldId} @@ -362,7 +366,7 @@ class EditorControl extends React.Component { resolveWidget={resolveWidget} widget={widget} getEditorComponents={getEditorComponents} - ref={processControlRef && partial(processControlRef, field)} + getWidget={getWidget} controlRef={controlRef} editorControl={ConnectedEditorControl} query={query} @@ -439,6 +443,7 @@ function mapStateToProps(state) { config: state.config, entry, collection, + collections: state.collections, isLoadingAsset, loadEntry, validateMetaField: (field, value, t) => validateMetaField(state, collection, field, value, t), diff --git a/packages/decap-cms-core/src/components/Editor/EditorControlPane/EditorControlPane.js b/packages/decap-cms-core/src/components/Editor/EditorControlPane/EditorControlPane.js index a9c030cab4b6..341e96b8d935 100644 --- a/packages/decap-cms-core/src/components/Editor/EditorControlPane/EditorControlPane.js +++ b/packages/decap-cms-core/src/components/Editor/EditorControlPane/EditorControlPane.js @@ -106,18 +106,19 @@ export default class ControlPane extends React.Component { selectedLocale: this.props.locale, }; - componentValidate = {}; + childRefs = {}; - controlRef(field, wrappedControl) { + controlRef = (field, wrappedControl) => { if (!wrappedControl) return; const parentName = field.get('parentName'); const name = field.get('name'); - const validateName = parentName ? `${parentName}.${name}` : name; + this.childRefs[validateName] = wrappedControl; + }; - this.componentValidate[validateName] = - wrappedControl.innerWrappedControl?.validate || wrappedControl.validate; - } + getControlRef = field => wrappedControl => { + this.controlRef(field, wrappedControl); + }; handleLocaleChange = val => { this.setState({ selectedLocale: val }); @@ -166,9 +167,13 @@ export default class ControlPane extends React.Component { const parentName = field.get('parentName'); const name = field.get('name'); - const validateName = parentName ? `${parentName}.${name}` : name; - this.componentValidate[validateName](); + + const control = this.childRefs[validateName]; + const validateFn = control?.innerWrappedControl?.validate ?? control?.validate; + if (validateFn) { + validateFn(); + } }); }; @@ -181,6 +186,14 @@ export default class ControlPane extends React.Component { } }; + focus(path) { + const [fieldName, ...remainingPath] = path.split('.'); + const control = this.childRefs[fieldName]; + if (control?.focus) { + control.focus(remainingPath.join('.')); + } + } + render() { const { collection, entry, fields, fieldsMetaData, fieldsErrors, onChange, onValidate, t } = this.props; @@ -243,8 +256,7 @@ export default class ControlPane extends React.Component { onChange(field, newValue, newMetadata, i18n); }} onValidate={onValidate} - processControlRef={this.controlRef.bind(this)} - controlRef={this.controlRef} + controlRef={this.getControlRef(field)} entry={entry} collection={collection} isDisabled={isDuplicate} diff --git a/packages/decap-cms-core/src/components/Editor/EditorControlPane/Widget.js b/packages/decap-cms-core/src/components/Editor/EditorControlPane/Widget.js index 2c6cc3249b22..7e8980da8423 100644 --- a/packages/decap-cms-core/src/components/Editor/EditorControlPane/Widget.js +++ b/packages/decap-cms-core/src/components/Editor/EditorControlPane/Widget.js @@ -44,6 +44,7 @@ export default class Widget extends Component { fieldsErrors: ImmutablePropTypes.map, onChange: PropTypes.func.isRequired, onValidate: PropTypes.func, + controlRef: PropTypes.func, onOpenMediaLibrary: PropTypes.func.isRequired, onClearMediaControl: PropTypes.func.isRequired, onRemoveMediaControl: PropTypes.func.isRequired, @@ -54,8 +55,8 @@ export default class Widget extends Component { resolveWidget: PropTypes.func.isRequired, widget: PropTypes.object.isRequired, getEditorComponents: PropTypes.func.isRequired, + getWidget: PropTypes.func.isRequired, isFetching: PropTypes.bool, - controlRef: PropTypes.func, query: PropTypes.func.isRequired, clearSearch: PropTypes.func.isRequired, clearFieldErrors: PropTypes.func.isRequired, @@ -114,8 +115,29 @@ export default class Widget extends Component { */ const { shouldComponentUpdate: scu } = this.innerWrappedControl; this.wrappedControlShouldComponentUpdate = scu && scu.bind(this.innerWrappedControl); + + // Call the control ref if provided, passing this Widget instance + if (this.props.controlRef) { + this.props.controlRef(this); + } }; + focus(path) { + // Try widget's custom focus method first + if (this.innerWrappedControl?.focus) { + this.innerWrappedControl.focus(path); + } else { + // Fall back to focusing by ID for simple widgets + const element = document.getElementById(this.props.uniqueFieldId); + element?.focus(); + } + // After focusing, ensure the element is visible + const label = document.querySelector(`label[for="${this.props.uniqueFieldId}"]`); + if (label) { + label.scrollIntoView({ behavior: 'smooth', block: 'nearest' }); + } + } + getValidateValue = () => { let value = this.innerWrappedControl?.getValidateValue?.() || this.props.value; // Convert list input widget value to string for validation test @@ -289,6 +311,7 @@ export default class Widget extends Component { controlComponent, entry, collection, + collections, config, field, value, @@ -315,6 +338,7 @@ export default class Widget extends Component { resolveWidget, widget, getEditorComponents, + getWidget, query, queryHits, clearSearch, @@ -339,6 +363,7 @@ export default class Widget extends Component { return React.createElement(controlComponent, { entry, collection, + collections, config, field, value, @@ -369,6 +394,7 @@ export default class Widget extends Component { resolveWidget, widget, getEditorComponents, + getWidget, getRemarkPlugins, query, queryHits, diff --git a/packages/decap-cms-core/src/components/Editor/EditorInterface.js b/packages/decap-cms-core/src/components/Editor/EditorInterface.js index 041fea5d351b..f2112a5536e0 100644 --- a/packages/decap-cms-core/src/components/Editor/EditorInterface.js +++ b/packages/decap-cms-core/src/components/Editor/EditorInterface.js @@ -162,6 +162,10 @@ class EditorInterface extends Component { i18nVisible: localStorage.getItem(I18N_VISIBLE) !== 'false', }; + handleFieldClick = path => { + this.controlPaneRef?.focus(path); + }; + handleSplitPaneDragStart = () => { this.setState({ showEventBlocker: true }); }; @@ -300,6 +304,7 @@ class EditorInterface extends Component { fields={fields} fieldsMetaData={fieldsMetaData} locale={leftPanelLocale} + onFieldClick={this.handleFieldClick} /> @@ -386,7 +391,7 @@ class EditorInterface extends Component { title={t('editor.editorInterface.togglePreview')} /> )} - {scrollSyncVisible && ( + {scrollSyncVisible && !collection.getIn(['editor', 'visualEditing']) && ( { + const { previewProps, onFieldClick } = this.props; + const visualEditing = previewProps?.collection?.getIn(['editor', 'visualEditing'], false); + + if (!visualEditing) { + return; + } + + try { + const text = e.target.textContent; + const decoded = vercelStegaDecode(text); + if (decoded?.decap) { + if (onFieldClick) { + onFieldClick(decoded.decap); + } + } + } catch (err) { + console.log('Visual editing error:', err); + } + }; + + renderPreview() { const { previewComponent, previewProps } = this.props; + return ( +
+ {isElement(previewComponent) + ? React.cloneElement(previewComponent, previewProps) + : React.createElement(previewComponent, previewProps)} +
+ ); + } + + render() { + const { previewProps } = this.props; + const visualEditing = previewProps?.collection?.getIn(['editor', 'visualEditing'], false); + const showScrollSync = !visualEditing; + return ( - {context => ( - - {isElement(previewComponent) - ? React.cloneElement(previewComponent, previewProps) - : React.createElement(previewComponent, previewProps)} - - )} + {context => { + const preview = this.renderPreview(); + if (showScrollSync) { + return ( + + {preview} + + ); + } + return preview; + }} ); } @@ -29,6 +68,7 @@ class PreviewContent extends React.Component { PreviewContent.propTypes = { previewComponent: PropTypes.func.isRequired, previewProps: PropTypes.object, + onFieldClick: PropTypes.func, }; export default PreviewContent; diff --git a/packages/decap-cms-core/src/components/Editor/EditorPreviewPane/EditorPreviewPane.js b/packages/decap-cms-core/src/components/Editor/EditorPreviewPane/EditorPreviewPane.js index b9feb9887238..39424176ac95 100644 --- a/packages/decap-cms-core/src/components/Editor/EditorPreviewPane/EditorPreviewPane.js +++ b/packages/decap-cms-core/src/components/Editor/EditorPreviewPane/EditorPreviewPane.js @@ -6,6 +6,7 @@ import ImmutablePropTypes from 'react-immutable-proptypes'; import Frame, { FrameContextConsumer } from 'react-frame-component'; import { lengths } from 'decap-cms-ui-default'; import { connect } from 'react-redux'; +import { encodeEntry } from 'decap-cms-lib-util/src/stega'; import { resolveWidget, @@ -92,6 +93,7 @@ export class PreviewPane extends React.Component { if (field.get('meta')) { value = this.props.entry.getIn(['meta', field.get('name')]); } + const nestedFields = field.get('fields'); const singleField = field.get('field'); const metadata = fieldsMetaData && fieldsMetaData.get(field.get('name'), Map()); @@ -167,9 +169,28 @@ export class PreviewPane extends React.Component { const { fields, entry, fieldsMetaData } = this.props; const field = fields.find(f => f.get('name') === name); const nestedFields = field && field.get('fields'); + const variableTypes = field && field.get('types'); const value = entry.getIn(['data', field.get('name')]); const metadata = fieldsMetaData.get(field.get('name'), Map()); + // Variable Type lists + if (List.isList(value) && variableTypes) { + return value.map(val => { + const valueType = variableTypes.find(t => t.get('name') === val.get('type')); + const typeFields = valueType && valueType.get('fields'); + const widgets = + typeFields && + Map( + typeFields.map((f, i) => [ + f.get('name'), +
{this.getWidget(f, val, metadata.get(f.get('name')), this.props)}
, + ]), + ); + return Map({ data: val, widgets }); + }); + } + + // List widgets if (List.isList(value)) { return value.map(val => { const widgets = @@ -226,9 +247,18 @@ export class PreviewPane extends React.Component { this.inferFields(); + const visualEditing = collection.getIn(['editor', 'visualEditing'], false); + + // Only encode entry data if visual editing is enabled + const previewEntry = visualEditing + ? entry.set('data', encodeEntry(entry.get('data'), this.props.fields)) + : entry; + const previewProps = { ...this.props, - widgetFor: this.widgetFor, + entry: previewEntry, + widgetFor: (name, fields, values = previewEntry.get('data'), fieldsMetaData) => + this.widgetFor(name, fields, values, fieldsMetaData), widgetsFor: this.widgetsFor, getCollection: this.getCollection, }; @@ -260,6 +290,7 @@ export class PreviewPane extends React.Component { return ( ); }} @@ -276,6 +307,7 @@ PreviewPane.propTypes = { entry: ImmutablePropTypes.map.isRequired, fieldsMetaData: ImmutablePropTypes.map.isRequired, getAsset: PropTypes.func.isRequired, + onFieldClick: PropTypes.func, }; function mapStateToProps(state) { diff --git a/packages/decap-cms-core/src/components/Editor/EditorToolbar.js b/packages/decap-cms-core/src/components/Editor/EditorToolbar.js index c139a31737d1..13456f6045a0 100644 --- a/packages/decap-cms-core/src/components/Editor/EditorToolbar.js +++ b/packages/decap-cms-core/src/components/Editor/EditorToolbar.js @@ -219,6 +219,13 @@ const StatusButton = styled(DropdownButton)` background-color: ${colorsRaw.tealLight}; color: ${colorsRaw.teal}; + ${props => + props.label === 'processing' && + css` + background-color: ${colors.processingBackground}; + color: ${colors.processingText}; + `} + ${props => props.label === 'stale' && css` @@ -383,13 +390,53 @@ export class EditorToolbar extends React.Component { ); }; + handleStatusChange = (newStatusName) => { + const { + currentStatus, + onChangeStatus, + t + } = this.props; + + if (currentStatus === status.get('PROCESSING')) { + const newStatusLabel = t(`editor.editorToolbar.${newStatusName.toLowerCase()}`); + + if (!window.confirm(t('editor.editor.onProcessingStatusChange', { + newStatus: newStatusLabel + }))) { + return; + } + } + + onChangeStatus(newStatusName); + } + + handleDelete = () => { + const { + currentStatus, + hasUnpublishedChanges, + onDeleteUnpublishedChanges, + onDelete, + t + } = this.props; + if (currentStatus === status.get('PROCESSING')) { + const translationKey = hasUnpublishedChanges + ? 'editor.editor.onProcessingDeleteUnpublishedChanges' + : 'editor.editor.onProcessingDeleteEntry'; + if (!window.confirm(t(translationKey))) { + return; + } + } + return hasUnpublishedChanges ? onDeleteUnpublishedChanges() : onDelete(); + } + renderWorkflowStatusControls = () => { - const { isUpdatingStatus, onChangeStatus, currentStatus, t, useOpenAuthoring } = this.props; + const { isUpdatingStatus, currentStatus, t, useOpenAuthoring } = this.props; const statusToTranslation = { [status.get('DRAFT')]: t('editor.editorToolbar.draft'), [status.get('PENDING_REVIEW')]: t('editor.editorToolbar.inReview'), [status.get('PENDING_PUBLISH')]: t('editor.editorToolbar.ready'), + [status.get('PROCESSING')]: t('editor.editorToolbar.inProcessing'), [status.get('STALE')]: t('editor.editorToolbar.inStale'), }; @@ -406,12 +453,12 @@ export class EditorToolbar extends React.Component { > onChangeStatus('DRAFT')} + onClick={() => this.handleStatusChange('DRAFT')} icon={currentStatus === status.get('DRAFT') ? 'check' : null} /> onChangeStatus('PENDING_REVIEW')} + onClick={() => this.handleStatusChange('PENDING_REVIEW')} icon={currentStatus === status.get('PENDING_REVIEW') ? 'check' : null} /> {useOpenAuthoring ? ( @@ -419,7 +466,7 @@ export class EditorToolbar extends React.Component { ) : ( onChangeStatus('PENDING_PUBLISH')} + onClick={() => this.handleStatusChange('PENDING_PUBLISH')} icon={currentStatus === status.get('PENDING_PUBLISH') ? 'check' : null} /> )} @@ -597,8 +644,6 @@ export class EditorToolbar extends React.Component { renderWorkflowControls = () => { const { onPersist, - onDelete, - onDeleteUnpublishedChanges, // showDelete, hasChanged, hasUnpublishedChanges, @@ -626,7 +671,6 @@ export class EditorToolbar extends React.Component { // (isNewEntry || !isModification) && // t('editor.editorToolbar.deleteUnpublishedEntry')) || // (!hasUnpublishedChanges && !isModification && t('editor.editorToolbar.deletePublishedEntry')); - return [ , currentStatus ? [ - - {this.renderWorkflowStatusControls()} - {currentStatus === status.get('PENDING_PUBLISH') && - this.renderNewEntryWorkflowPublishControls({ canCreate, canPublish })} - , - ] + + {this.renderWorkflowStatusControls()} + {currentStatus === status.get('PENDING_PUBLISH') && + this.renderNewEntryWorkflowPublishControls({ canCreate, canPublish })} + , + ] : !isNewEntry && ( - - {this.renderExistingEntryWorkflowPublishControls({ - canCreate, - canPublish, - canDelete, - })} - - ), + + {this.renderExistingEntryWorkflowPublishControls({ + canCreate, + canPublish, + canDelete, + })} + + ), !hasUnpublishedChanges && !isModification ? null : ( {isDeleting ? t('editor.editorToolbar.discarding') : deleteLabel} diff --git a/packages/decap-cms-core/src/components/Editor/withWorkflow.js b/packages/decap-cms-core/src/components/Editor/withWorkflow.js index 47fb52c0cfb8..1766beefc08a 100644 --- a/packages/decap-cms-core/src/components/Editor/withWorkflow.js +++ b/packages/decap-cms-core/src/components/Editor/withWorkflow.js @@ -26,7 +26,7 @@ function mapStateToProps(state, ownProps) { } function mergeProps(stateProps, dispatchProps, ownProps) { - const { isEditorialWorkflow, unpublishedEntry } = stateProps; + const { isEditorialWorkflow } = stateProps; const { dispatch } = dispatchProps; const returnObj = {}; @@ -35,8 +35,10 @@ function mergeProps(stateProps, dispatchProps, ownProps) { returnObj.loadEntry = (collection, slug) => dispatch(loadUnpublishedEntry(collection, slug)); // Overwrite persistEntry to persistUnpublishedEntry - returnObj.persistEntry = collection => - dispatch(persistUnpublishedEntry(collection, unpublishedEntry)); + returnObj.persistEntry = (collection, context, entryDraft) => { + const { unpublished = stateProps.unpublishedEntry } = context; + return dispatch(persistUnpublishedEntry(collection, unpublished, context, entryDraft)); + } } return { diff --git a/packages/decap-cms-core/src/components/Workflow/WorkflowList.js b/packages/decap-cms-core/src/components/Workflow/WorkflowList.js index 855a79a2a211..87b6b8a9266f 100644 --- a/packages/decap-cms-core/src/components/Workflow/WorkflowList.js +++ b/packages/decap-cms-core/src/components/Workflow/WorkflowList.js @@ -15,7 +15,7 @@ import { selectEntryCollectionTitle } from '../../reducers/collections'; const WorkflowListContainer = styled.div` min-height: 60%; display: grid; - grid-template-columns: 25% 25% 25% 25%; + grid-template-columns: 20% 20% 20% 20% 20%; `; const WorkflowListContainerOpenAuthoring = styled.div` @@ -105,6 +105,13 @@ const ColumnHeader = styled.h2` color: ${colors.statusReadyText}; `} + ${props => + props.name === 'processing' && + css` + background-color: ${colors.processingBackground}; + color: ${colors.processingText}; + `} + ${props => props.name === 'stale' && css` @@ -128,12 +135,14 @@ function getColumnHeaderText(columnName, t) { switch (columnName) { case 'draft': return t('workflow.workflowList.draftHeader'); - case 'stale': - return t('workflow.workflowList.inStaleHeader'); case 'pending_review': return t('workflow.workflowList.inReviewHeader'); case 'pending_publish': return t('workflow.workflowList.readyHeader'); + case 'processing': + return t('workflow.workflowList.inProcessingHeader'); + case 'stale': + return t('workflow.workflowList.inStaleHeader'); } } @@ -152,6 +161,10 @@ class WorkflowList extends React.Component { const slug = dragProps.slug; const collection = dragProps.collection; const oldStatus = dragProps.ownStatus; + if (oldStatus === 'processing') { + window.alert(this.props.t('workflow.workflowList.onProcessingUpdate')) + return; + } if (newStatus === 'stale') { window.alert(this.props.t('workflow.workflowList.onStaleUpdate')); return; @@ -160,6 +173,10 @@ class WorkflowList extends React.Component { }; requestDelete = (collection, slug, ownStatus) => { + if (ownStatus === 'processing') { + window.alert(this.props.t('workflow.workflowList.onProcessingUpdate')) + return; + } if (window.confirm(this.props.t('workflow.workflowList.onDeleteEntry'))) { this.props.handleDelete(collection, slug, ownStatus); } diff --git a/packages/decap-cms-core/src/constants/configSchema.js b/packages/decap-cms-core/src/constants/configSchema.js index 3d0cc81cfda6..34ec75bea5b0 100644 --- a/packages/decap-cms-core/src/constants/configSchema.js +++ b/packages/decap-cms-core/src/constants/configSchema.js @@ -265,6 +265,7 @@ function getConfigSchema() { type: 'object', properties: { depth: { type: 'number', minimum: 1, maximum: 1000 }, + subfolders: { type: 'boolean' }, summary: { type: 'string' }, }, required: ['depth'], diff --git a/packages/decap-cms-core/src/constants/publishModes.ts b/packages/decap-cms-core/src/constants/publishModes.ts index 62be9769ff49..a64fd344ee66 100644 --- a/packages/decap-cms-core/src/constants/publishModes.ts +++ b/packages/decap-cms-core/src/constants/publishModes.ts @@ -8,6 +8,7 @@ export const Statues = { DRAFT: 'draft', PENDING_REVIEW: 'pending_review', PENDING_PUBLISH: 'pending_publish', + PROCESSING: 'processing', STALE: 'stale', }; diff --git a/packages/decap-cms-core/src/lib/registry.js b/packages/decap-cms-core/src/lib/registry.js index 573d8867762c..ef094fe37a57 100644 --- a/packages/decap-cms-core/src/lib/registry.js +++ b/packages/decap-cms-core/src/lib/registry.js @@ -1,6 +1,7 @@ import { Map } from 'immutable'; import { produce } from 'immer'; import { oneLine } from 'common-tags'; +import * as immutable from 'immutable'; import EditorComponent from '../valueObjects/EditorComponent'; @@ -17,10 +18,15 @@ allowedEvents.forEach(e => { eventHandlers[e] = []; }); +const lib = { + immutable, +} + /** * Global Registry Object */ const registry = { + lib, backends: {}, templates: {}, previewStyles: [], @@ -35,6 +41,7 @@ const registry = { }; export default { + getLib, registerPreviewStyle, getPreviewStyles, registerPreviewTemplate, @@ -65,6 +72,10 @@ export default { getCustomFormatsFormatters, }; +export function getLib() { + return registry.lib; +} + /** * Preview Styles * @@ -310,3 +321,4 @@ export function getCustomFormatsFormatters() { export function getFormatter(name) { return registry.formats[name]?.formatter; } + diff --git a/packages/decap-cms-core/src/reducers/entries.ts b/packages/decap-cms-core/src/reducers/entries.ts index 068d486a0e75..9a10e032bb67 100644 --- a/packages/decap-cms-core/src/reducers/entries.ts +++ b/packages/decap-cms-core/src/reducers/entries.ts @@ -230,7 +230,7 @@ function entries( const payload = action.payload as EntryDeletePayload; return state.withMutations(map => { map.deleteIn(['entities', `${payload.collectionName}.${payload.entrySlug}`]); - map.updateIn(['pages', payload.collectionName, 'ids'], (ids: string[]) => + map.updateIn(['pages', payload.collectionName, 'ids'], (ids: string[] = []) => ids.filter(id => id !== payload.entrySlug), ); }); diff --git a/packages/decap-cms-core/src/reducers/entryDraft.js b/packages/decap-cms-core/src/reducers/entryDraft.js index 4c16435eb54c..d85374feab3a 100644 --- a/packages/decap-cms-core/src/reducers/entryDraft.js +++ b/packages/decap-cms-core/src/reducers/entryDraft.js @@ -168,6 +168,7 @@ function entryDraftReducer(state = Map(), action) { case ENTRY_PERSIST_SUCCESS: case UNPUBLISHED_ENTRY_PERSIST_SUCCESS: return state.withMutations(state => { + if (action.payload.entry) state.setIn(['entry', 'data'], action.payload.entry.get('data')); state.deleteIn(['entry', 'isPersisting']); state.set('hasChanged', false); if (!state.getIn(['entry', 'slug'])) { diff --git a/packages/decap-cms-core/src/types/redux.ts b/packages/decap-cms-core/src/types/redux.ts index 07c800a06655..c5309de7ec45 100644 --- a/packages/decap-cms-core/src/types/redux.ts +++ b/packages/decap-cms-core/src/types/redux.ts @@ -550,10 +550,13 @@ export type EntryObject = { slug: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any data: any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + i18n?: any; collection: string; mediaFiles: List; newRecord: boolean; isDeleteWorkflow: boolean; + isCustomEntry?: boolean; author?: string; updatedOn?: string; status: string; @@ -606,7 +609,7 @@ export type CollectionFile = StaticallyTypedRecord<{ export type CollectionFiles = List; -type NestedObject = { depth: number }; +type NestedObject = { depth: number; subfolders?: boolean }; type Nested = StaticallyTypedRecord; diff --git a/packages/decap-cms-lib-util/CHANGELOG.md b/packages/decap-cms-lib-util/CHANGELOG.md index 9bc04cb12103..c29a03a2b3d2 100644 --- a/packages/decap-cms-lib-util/CHANGELOG.md +++ b/packages/decap-cms-lib-util/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.2.0](https://github.com/decaporg/decap-cms/compare/decap-cms-lib-util@3.1.0...decap-cms-lib-util@3.2.0) (2025-01-29) + +### Features + +- visual editing (click-to-edit) ([#7374](https://github.com/decaporg/decap-cms/issues/7374)) ([989c2dd](https://github.com/decaporg/decap-cms/commit/989c2dd6ed80f69b572b8b73c4e37b5106ae04fb)) + # [3.1.0](https://github.com/decaporg/decap-cms/compare/decap-cms-lib-util@3.0.4...decap-cms-lib-util@3.1.0) (2024-08-07) ### Bug Fixes diff --git a/packages/decap-cms-lib-util/README.md b/packages/decap-cms-lib-util/README.md index 4bde999e0ba2..e0926977a1bd 100644 --- a/packages/decap-cms-lib-util/README.md +++ b/packages/decap-cms-lib-util/README.md @@ -18,5 +18,5 @@ Used as backend in [cms-core](https://github.com/decaporg/decap-cms/tree/main/pa - `API` - used for Entry files - `git-lfs` - used for Media files -- and over halpful utilities +- and more helpful utilities diff --git a/packages/decap-cms-lib-util/package.json b/packages/decap-cms-lib-util/package.json index 92ab5ecdffc6..2f9c59073b49 100644 --- a/packages/decap-cms-lib-util/package.json +++ b/packages/decap-cms-lib-util/package.json @@ -1,7 +1,7 @@ { "name": "decap-cms-lib-util", "description": "Shared utilities for Decap CMS.", - "version": "3.1.0", + "version": "3.2.0", "repository": "https://github.com/decaporg/decap-cms/tree/main/packages/decap-cms-lib-util", "bugs": "https://github.com/decaporg/decap-cms/issues", "module": "dist/esm/index.js", diff --git a/packages/decap-cms-lib-util/src/stega.ts b/packages/decap-cms-lib-util/src/stega.ts new file mode 100644 index 000000000000..099b86e6db03 --- /dev/null +++ b/packages/decap-cms-lib-util/src/stega.ts @@ -0,0 +1,134 @@ +import { vercelStegaEncode } from '@vercel/stega'; + +import { isImmutableMap, isImmutableList } from './types'; + +import type { Map as ImmutableMap, List } from 'immutable'; +import type { CmsField } from 'decap-cms-core'; + +/** + * Context passed to encode functions, containing the current state of the encoding process + */ +interface EncodeContext { + fields: CmsField[]; // Available CMS fields at current level + path: string; // Path to current value in object tree + visit: (value: unknown, fields: CmsField[], path: string) => unknown; // Visitor for recursive traversal +} + +/** + * Get the fields that should be used for encoding nested values + */ +function getNestedFields(f?: CmsField): CmsField[] { + if (f) { + if ('types' in f) { + return f.types ?? []; + } + if ('fields' in f) { + return f.fields ?? []; + } + if ('field' in f) { + return f.field ? [f.field] : []; + } + return [f]; + } + return []; +} + +/** + * Encode a string value by appending steganographic data + * For markdown fields, encode each paragraph separately + */ +function encodeString(value: string, { fields, path }: EncodeContext): string { + const stega = vercelStegaEncode({ decap: path }); + const isMarkdown = fields[0]?.widget === 'markdown'; + + if (isMarkdown && value.includes('\n\n')) { + const blocks = value.split(/(\n\n+)/); + return blocks.map(block => (block.trim() ? block + stega : block)).join(''); + } + return value + stega; +} + +/** + * Encode a list of values, handling both simple values and nested objects/lists + * For typed lists, use the type field to determine which fields to use + */ +function encodeList(list: List, ctx: EncodeContext): List { + let newList = list; + for (let i = 0; i < newList.size; i++) { + const item = newList.get(i); + if (isImmutableMap(item)) { + const itemType = item.get('type'); + if (typeof itemType === 'string') { + // For typed items, look up fields based on type + const field = ctx.fields.find(f => f.name === itemType); + const newItem = ctx.visit(item, getNestedFields(field), `${ctx.path}.${i}`); + newList = newList.set(i, newItem); + } else { + // For untyped items, use current fields + const newItem = ctx.visit(item, ctx.fields, `${ctx.path}.${i}`); + newList = newList.set(i, newItem); + } + } else { + // For simple values, use first field if available + const field = ctx.fields[0]; + const newItem = ctx.visit(item, field ? [field] : [], `${ctx.path}.${i}`); + if (newItem !== item) { + newList = newList.set(i, newItem); + } + } + } + return newList; +} + +/** + * Encode a map of values, looking up the appropriate field for each key + * and recursively encoding nested values + */ +function encodeMap( + map: ImmutableMap, + ctx: EncodeContext, +): ImmutableMap { + let newMap = map; + for (const [key, val] of newMap.entrySeq().toArray()) { + const field = ctx.fields.find(f => f.name === key); + if (field) { + const fields = getNestedFields(field); + const newVal = ctx.visit(val, fields, ctx.path ? `${ctx.path}.${key}` : key); + if (newVal !== val) { + newMap = newMap.set(key, newVal); + } + } + } + return newMap; +} + +/** + * Main entry point for encoding steganographic data into entry values + * Uses a visitor pattern with caching to handle recursive structures + */ +export function encodeEntry(value: unknown, fields: List>) { + const plainFields = fields.toJS() as CmsField[]; + const cache = new Map(); + + function visit(value: unknown, fields: CmsField[], path = '') { + const cached = cache.get(path); + if (cached === value) return value; + + const ctx: EncodeContext = { fields, path, visit }; + let result; + if (isImmutableList(value)) { + result = encodeList(value, ctx); + } else if (isImmutableMap(value)) { + result = encodeMap(value, ctx); + } else if (typeof value === 'string') { + result = encodeString(value, ctx); + } else { + result = value; + } + + cache.set(path, result); + return result; + } + + return visit(value, plainFields); +} diff --git a/packages/decap-cms-lib-util/src/types.ts b/packages/decap-cms-lib-util/src/types.ts new file mode 100644 index 000000000000..5caf8822565c --- /dev/null +++ b/packages/decap-cms-lib-util/src/types.ts @@ -0,0 +1,9 @@ +import { Map as ImmutableMap, List } from 'immutable'; + +export function isImmutableMap(value: unknown): value is ImmutableMap { + return ImmutableMap.isMap(value); +} + +export function isImmutableList(value: unknown): value is List { + return List.isList(value); +} diff --git a/packages/decap-cms-locales/src/en/index.js b/packages/decap-cms-locales/src/en/index.js index c75762c44b55..261f09fdf1b3 100644 --- a/packages/decap-cms-locales/src/en/index.js +++ b/packages/decap-cms-locales/src/en/index.js @@ -115,6 +115,9 @@ const en = { 'All changes to this entry will be deleted.\n\n Do you still want to delete?', loadingEntry: 'Loading entry...', confirmLoadBackup: 'A local backup was recovered for this entry, would you like to use it?', + onProcessingStatusChange: "Are you sure you want to change the status to %{newStatus} while the entry is processing?", + onProcessingDeleteUnpublishedChanges: "Are you sure you want to delete unpublished changes while the entry is processing?", + onProcessingDeleteEntry: "Are you sure you want to delete this entry while it is processing?", onStackPublishing: 'Are you sure you want to publish all changes?', onStackClosing: 'Are you sure you want to discard all changes?', }, @@ -153,6 +156,7 @@ const en = { draft: 'Draft', inReview: 'In review', ready: 'Ready', + inProcessing: 'Processing', inStale: 'Stale', publishNow: 'Publish now', stackChange: 'Stack change', @@ -323,6 +327,7 @@ const en = { draftHeader: 'Drafts', inReviewHeader: 'In Review', readyHeader: 'Ready', + inProcessingHeader: 'Processing', inStaleHeader: 'Stale', onStaleUpdate: "Entry can't be manually updated to stale status! Please discard changes insted of using stale status.", diff --git a/packages/decap-cms-ui-default/src/ListItemTopBar.js b/packages/decap-cms-ui-default/src/ListItemTopBar.js index cc09183b6652..dfa1d2d0b346 100644 --- a/packages/decap-cms-ui-default/src/ListItemTopBar.js +++ b/packages/decap-cms-ui-default/src/ListItemTopBar.js @@ -28,6 +28,10 @@ const TopBarButton = styled.button` align-items: center; `; +const TopBarButtonGroups = styled.div` + display: flex; +`; + const TopBarButtonSpan = TopBarButton.withComponent('span'); const DragIconContainer = styled(TopBarButtonSpan)` @@ -46,7 +50,7 @@ function DragHandle({ Wrapper, id }) { } function ListItemTopBar(props) { - const { className, collapsed, onCollapseToggle, onRemove, dragHandle, id } = props; + const { className, collapsed, onCollapseToggle, onDuplicate, onRemove, dragHandle, id } = props; return ( {onCollapseToggle ? ( @@ -55,11 +59,18 @@ function ListItemTopBar(props) { ) : null} {dragHandle ? : null} - {onRemove ? ( - - - - ) : null} + + {onDuplicate ? ( + + + + ) : null} + {onRemove ? ( + + + + ) : null} + ); } diff --git a/packages/decap-cms-ui-default/src/Toggle.js b/packages/decap-cms-ui-default/src/Toggle.js index 46a4d25b9c39..50923f5cd6d7 100644 --- a/packages/decap-cms-ui-default/src/Toggle.js +++ b/packages/decap-cms-ui-default/src/Toggle.js @@ -1,4 +1,4 @@ -import React, { useState } from 'react'; +import React, { useEffect, useState } from 'react'; import PropTypes from 'prop-types'; import styled from '@emotion/styled'; import { css } from '@emotion/react'; @@ -57,6 +57,10 @@ function Toggle({ }) { const [isActive, setIsActive] = useState(active); + useEffect(() => { + setIsActive(active); + }, [active]); + function handleToggle() { setIsActive(prevIsActive => !prevIsActive); if (onChange) { diff --git a/packages/decap-cms-ui-default/src/styles.js b/packages/decap-cms-ui-default/src/styles.js index 684eb78019ea..ae9266248acc 100644 --- a/packages/decap-cms-ui-default/src/styles.js +++ b/packages/decap-cms-ui-default/src/styles.js @@ -42,6 +42,7 @@ const colorsRaw = { greenLight: '#caef6f', brown: '#754e00', yellow: '#ffee9c', + yellowDark: '#ffe150', red: '#ff003b', redDark: '#D60032', redLight: '#fcefea', @@ -59,6 +60,8 @@ const colors = { statusReviewBackground: colorsRaw.yellow, statusReadyText: colorsRaw.green, statusReadyBackground: colorsRaw.greenLight, + processingBackground: colorsRaw.yellowDark, + processingText: colorsRaw.grayDark, staleBackground: colorsRaw.redDark, staleText: colorsRaw.redLight, text: colorsRaw.gray, diff --git a/packages/decap-cms-widget-list/CHANGELOG.md b/packages/decap-cms-widget-list/CHANGELOG.md index a334c95bca10..c886c4c6438a 100644 --- a/packages/decap-cms-widget-list/CHANGELOG.md +++ b/packages/decap-cms-widget-list/CHANGELOG.md @@ -3,6 +3,12 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.3.0](https://github.com/decaporg/decap-cms/compare/decap-cms-widget-list@3.2.2...decap-cms-widget-list@3.3.0) (2025-01-29) + +### Features + +- visual editing (click-to-edit) ([#7374](https://github.com/decaporg/decap-cms/issues/7374)) ([989c2dd](https://github.com/decaporg/decap-cms/commit/989c2dd6ed80f69b572b8b73c4e37b5106ae04fb)) + ## [3.2.2](https://github.com/decaporg/decap-cms/compare/decap-cms-widget-list@3.2.1...decap-cms-widget-list@3.2.2) (2024-08-13) ### Reverts diff --git a/packages/decap-cms-widget-list/package.json b/packages/decap-cms-widget-list/package.json index 5c4860a0bb32..e312aa084726 100644 --- a/packages/decap-cms-widget-list/package.json +++ b/packages/decap-cms-widget-list/package.json @@ -1,7 +1,7 @@ { "name": "decap-cms-widget-list", "description": "Widget for editing lists in Decap CMS.", - "version": "3.2.2", + "version": "3.3.0", "homepage": "https://www.decapcms.org/docs/widgets/#list", "repository": "https://github.com/decaporg/decap-cms/tree/main/packages/decap-cms-widget-list", "bugs": "https://github.com/decaporg/decap-cms/issues", diff --git a/packages/decap-cms-widget-list/src/ListControl.js b/packages/decap-cms-widget-list/src/ListControl.js index 497dcbdd6483..6237fe8a0cf5 100644 --- a/packages/decap-cms-widget-list/src/ListControl.js +++ b/packages/decap-cms-widget-list/src/ListControl.js @@ -6,7 +6,6 @@ import { css, ClassNames } from '@emotion/react'; import { List, Map, fromJS } from 'immutable'; import { partial, isEmpty, uniqueId } from 'lodash'; import { v4 as uuid } from 'uuid'; -import DecapCmsWidgetObject from 'decap-cms-widget-object'; import { DndContext, MouseSensor, @@ -34,8 +33,6 @@ import { getErrorMessageForTypedFieldAndValue, } from './typedListHelpers'; -const ObjectControl = DecapCmsWidgetObject.controlComponent; - const ListItem = styled.div(); const StyledListItemTopBar = styled(ListItemTopBar)` @@ -171,7 +168,7 @@ function LabelComponent({ field, isActive, hasErrors, uniqueFieldId, isFieldOpti } export default class ListControl extends React.Component { - validations = []; + childRefs = {}; static propTypes = { metadata: ImmutablePropTypes.map, @@ -195,8 +192,6 @@ export default class ListControl extends React.Component { resolveWidget: PropTypes.func.isRequired, clearFieldErrors: PropTypes.func.isRequired, fieldsErrors: ImmutablePropTypes.map.isRequired, - isFieldUnused: PropTypes.func, - setFieldUnused: PropTypes.func, entry: ImmutablePropTypes.map.isRequired, t: PropTypes.func, }; @@ -367,16 +362,18 @@ export default class ListControl extends React.Component { processControlRef = ref => { if (!ref) return; const { - validate, props: { validationKey: key }, } = ref; - this.validations.push({ key, validate }); + this.childRefs[key] = ref; + this.props.controlRef?.(this); }; validate = () => { - if (this.getValueType()) { - this.validations.forEach(item => { - item.validate(); + // First validate child widgets if this is a complex list + const hasChildWidgets = this.getValueType() && Object.keys(this.childRefs).length > 0; + if (hasChildWidgets) { + Object.values(this.childRefs).forEach(widget => { + widget?.validate?.(); }); } else { this.props.validate(); @@ -412,7 +409,7 @@ export default class ListControl extends React.Component { */ getObjectValue = idx => this.props.value.get(idx) || Map(); - handleChangeFor(index) { + handleFieldChangeFor(index) { return (f, newValue, newMetadata) => { const { value, metadata, onChange, field } = this.props; const collectionName = field.get('name'); @@ -433,10 +430,55 @@ export default class ListControl extends React.Component { }; } + handleChangeFor(index) { + return (newValue, newMetadata) => { + const { value, metadata, onChange, field } = this.props; + const collectionName = field.get('name'); + const parsedMetadata = { + [collectionName]: Object.assign(metadata ? metadata.toJS() : {}, newMetadata || {}), + }; + onChange(value.set(index, newValue), parsedMetadata); + }; + } + + handleDuplicate = (index, event) => { + event.preventDefault(); + const { value, onChange } = this.props; + + const listValue = value.get(index); + if (!listValue) return + + const { itemsCollapsed } = this.state; + + // Create new arrays with the item inserted at index + 1 + const newItemsCollapsed = [...itemsCollapsed]; + const newKeys = [...this.state.keys]; + + newItemsCollapsed.splice(index + 1, 0, false); // Insert expanded state + newKeys.splice(index + 1, 0, uuid()); // Insert new key + + this.setState({ + itemsCollapsed: newItemsCollapsed, + keys: newKeys + }); + + onChange(value.insert(index + 1, listValue)); + }; + handleRemove = (index, event) => { event.preventDefault(); const { itemsCollapsed } = this.state; - const { value, metadata, onChange, field, clearFieldErrors } = this.props; + const { + value, + metadata, + onChange, + field, + clearFieldErrors, + onValidateObject, + forID, + fieldsErrors, + } = this.props; + const collectionName = field.get('name'); const isSingleField = this.getValueType() === valueTypes.SINGLE; @@ -446,17 +488,41 @@ export default class ListControl extends React.Component { ? { [collectionName]: metadata.removeIn(metadataRemovePath) } : metadata; + // Get the key of the item being removed + const removedKey = this.state.keys[index]; + + // Update state while preserving keys for remaining items + const newKeys = [...this.state.keys]; + newKeys.splice(index, 1); itemsCollapsed.splice(index, 1); - // clear validations - this.validations = []; this.setState({ itemsCollapsed: [...itemsCollapsed], - keys: Array.from({ length: value.size - 1 }, () => uuid()), + keys: newKeys, }); - onChange(value.remove(index), parsedMetadata); - clearFieldErrors(); + // Clear the ref for the removed item + delete this.childRefs[removedKey]; + + const newValue = value.delete(index); + + // Clear errors for the removed item and its children + if (fieldsErrors) { + Object.entries(fieldsErrors.toJS()).forEach(([fieldId, errors]) => { + if (errors.some(err => err.parentIds?.includes(removedKey))) { + clearFieldErrors(fieldId); + } + }); + } + + // If list is empty, mark it as valid + if (newValue.size === 0) { + clearFieldErrors(forID); + onValidateObject(forID, []); + } + + // Update the value last to ensure all error states are cleared + onChange(newValue, parsedMetadata); }; handleItemCollapseToggle = (index, event) => { @@ -532,7 +598,7 @@ export default class ListControl extends React.Component { } onSortEnd = ({ oldIndex, newIndex }) => { - const { value, clearFieldErrors } = this.props; + const { value } = this.props; const { itemsCollapsed, keys } = this.state; // Update value @@ -546,18 +612,13 @@ export default class ListControl extends React.Component { const updatedItemsCollapsed = [...itemsCollapsed]; updatedItemsCollapsed.splice(newIndex, 0, collapsed); - // Reset item to ensure updated state - const updatedKeys = keys.map((key, keyIndex) => { - if (keyIndex === oldIndex || keyIndex === newIndex) { - return uuid(); - } - return key; - }); - this.setState({ itemsCollapsed: updatedItemsCollapsed, keys: updatedKeys }); + // Move keys to maintain relationships + const movedKey = keys[oldIndex]; + const updatedKeys = [...keys]; + updatedKeys.splice(oldIndex, 1); + updatedKeys.splice(newIndex, 0, movedKey); - //clear error fields and remove old validations - clearFieldErrors(); - this.validations = this.validations.filter(item => updatedKeys.includes(item.key)); + this.setState({ itemsCollapsed: updatedItemsCollapsed, keys: updatedKeys }); }; hasError = index => { @@ -569,6 +630,34 @@ export default class ListControl extends React.Component { } }; + focus(path) { + const [index, ...remainingPath] = path.split('.'); + + if (this.state.listCollapsed || this.state.itemsCollapsed[index]) { + const newItemsCollapsed = [...this.state.itemsCollapsed]; + newItemsCollapsed[index] = false; + this.setState( + { + listCollapsed: false, + itemsCollapsed: newItemsCollapsed, + }, + () => { + const key = this.state.keys[index]; + const control = this.childRefs[key]; + if (control?.focus) { + control.focus(remainingPath.join('.')); + } + }, + ); + } else { + const key = this.state.keys[index]; + const control = this.childRefs[key]; + if (control?.focus) { + control.focus(remainingPath.join('.')); + } + } + } + // eslint-disable-next-line react/display-name renderItem = (item, index) => { const { @@ -578,13 +667,12 @@ export default class ListControl extends React.Component { metadata, clearFieldErrors, fieldsErrors, - controlRef, resolveWidget, parentIds, forID, t, - isFieldUnused, - setFieldUnused, + collection, + collections, } = this.props; const { itemsCollapsed, keys } = this.state; @@ -600,6 +688,8 @@ export default class ListControl extends React.Component { } } + const ObjectControl = (this.props.getWidget('object')).control; + return ( @@ -639,7 +730,10 @@ export default class ListControl extends React.Component { })} value={item} field={field} - onChangeObject={this.handleChangeFor(index)} + collection={collection} + collections={collections} + onChange={this.handleChangeFor(index)} + onChangeObject={this.handleFieldChangeFor(index)} editorControl={editorControl} resolveWidget={resolveWidget} metadata={metadata} @@ -647,15 +741,12 @@ export default class ListControl extends React.Component { onValidateObject={onValidateObject} clearFieldErrors={clearFieldErrors} fieldsErrors={fieldsErrors} - ref={this.processControlRef} - controlRef={controlRef} + controlRef={this.processControlRef} validationKey={key} collapsed={collapsed} data-testid={`object-control-${key}`} hasError={hasError} parentIds={[...parentIds, forID, key]} - isFieldUnused={isFieldUnused} - setFieldUnused={setFieldUnused} /> )} @@ -675,7 +766,7 @@ export default class ListControl extends React.Component { > diff --git a/packages/decap-cms-widget-list/src/__tests__/__snapshots__/ListControl.spec.js.snap b/packages/decap-cms-widget-list/src/__tests__/__snapshots__/ListControl.spec.js.snap index d165efdd4770..b5b38ac07c81 100644 --- a/packages/decap-cms-widget-list/src/__tests__/__snapshots__/ListControl.spec.js.snap +++ b/packages/decap-cms-widget-list/src/__tests__/__snapshots__/ListControl.spec.js.snap @@ -724,13 +724,12 @@ exports[`ListControl should remove from list when remove button is clicked 2`] =
diff --git a/packages/decap-cms-widget-markdown/CHANGELOG.md b/packages/decap-cms-widget-markdown/CHANGELOG.md index 245d0cf027f3..56921b948e83 100644 --- a/packages/decap-cms-widget-markdown/CHANGELOG.md +++ b/packages/decap-cms-widget-markdown/CHANGELOG.md @@ -3,6 +3,16 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.3.0](https://github.com/decaporg/decap-cms/compare/decap-cms-widget-markdown@3.2.0...decap-cms-widget-markdown@3.3.0) (2025-01-29) + +### Bug Fixes + +- **markdown:** convert inline CSS from Google Docs to Markdown ([#7351](https://github.com/decaporg/decap-cms/issues/7351)) ([8b8e873](https://github.com/decaporg/decap-cms/commit/8b8e873af9a0749720ec03cadbc4b0d391ad84e1)) + +### Features + +- visual editing (click-to-edit) ([#7374](https://github.com/decaporg/decap-cms/issues/7374)) ([989c2dd](https://github.com/decaporg/decap-cms/commit/989c2dd6ed80f69b572b8b73c4e37b5106ae04fb)) + # [3.2.0](https://github.com/decaporg/decap-cms/compare/decap-cms-widget-markdown@3.1.6...decap-cms-widget-markdown@3.2.0) (2024-11-12) ### Bug Fixes diff --git a/packages/decap-cms-widget-markdown/package.json b/packages/decap-cms-widget-markdown/package.json index b174ffdaeac5..3f382d0e03df 100644 --- a/packages/decap-cms-widget-markdown/package.json +++ b/packages/decap-cms-widget-markdown/package.json @@ -1,7 +1,7 @@ { "name": "decap-cms-widget-markdown", "description": "Widget for editing markdown in Decap CMS.", - "version": "3.2.0", + "version": "3.3.0", "homepage": "https://www.decapcms.org/docs/widgets/#markdown", "repository": "https://github.com/decaporg/decap-cms/tree/main/packages/decap-cms-widget-markdown", "bugs": "https://github.com/decaporg/decap-cms/issues", diff --git a/packages/decap-cms-widget-markdown/src/MarkdownControl/RawEditor.js b/packages/decap-cms-widget-markdown/src/MarkdownControl/RawEditor.js index d9478ddb0a66..6a99b9c8481d 100644 --- a/packages/decap-cms-widget-markdown/src/MarkdownControl/RawEditor.js +++ b/packages/decap-cms-widget-markdown/src/MarkdownControl/RawEditor.js @@ -43,8 +43,9 @@ function RawEditor(props) { useEffect(() => { if (props.pendingFocus) { ReactEditor.focus(editor); + props.pendingFocus(); } - }, []); + }, [props.pendingFocus]); function handleToggleMode() { props.onMode('rich_text'); diff --git a/packages/decap-cms-widget-markdown/src/MarkdownControl/VisualEditor.js b/packages/decap-cms-widget-markdown/src/MarkdownControl/VisualEditor.js index d73fbaa7ff60..860939fbb979 100644 --- a/packages/decap-cms-widget-markdown/src/MarkdownControl/VisualEditor.js +++ b/packages/decap-cms-widget-markdown/src/MarkdownControl/VisualEditor.js @@ -135,8 +135,9 @@ function Editor(props) { useEffect(() => { if (props.pendingFocus) { ReactEditor.focus(editor); + props.pendingFocus(); } - }, []); + }, [props.pendingFocus]); function handleMarkClick(format) { ReactEditor.focus(editor); diff --git a/packages/decap-cms-widget-markdown/src/MarkdownControl/index.js b/packages/decap-cms-widget-markdown/src/MarkdownControl/index.js index d89b199872f5..5831f88a3c2e 100644 --- a/packages/decap-cms-widget-markdown/src/MarkdownControl/index.js +++ b/packages/decap-cms-widget-markdown/src/MarkdownControl/index.js @@ -67,6 +67,10 @@ export default class MarkdownControl extends React.Component { getAllowedModes = () => this.props.field.get('modes', List(['rich_text', 'raw'])).toArray(); + focus() { + this.setState({ pendingFocus: true }); + } + render() { const { onChange, diff --git a/packages/decap-cms-widget-markdown/src/MarkdownControl/plugins/html/withHtml.js b/packages/decap-cms-widget-markdown/src/MarkdownControl/plugins/html/withHtml.js index a7f96cbec3e6..9dc9a5d73af7 100644 --- a/packages/decap-cms-widget-markdown/src/MarkdownControl/plugins/html/withHtml.js +++ b/packages/decap-cms-widget-markdown/src/MarkdownControl/plugins/html/withHtml.js @@ -30,6 +30,11 @@ const TEXT_TAGS = { U: () => ({ underline: true }), }; +const INLINE_STYLES = { + 'font-style': value => (value === 'italic' ? { italic: true } : {}), + 'font-weight': value => (value === 'bold' || parseInt(value, 10) >= 600 ? { bold: true } : {}), +}; + function deserialize(el) { if (el.nodeType === 3) { return el.textContent; @@ -65,6 +70,20 @@ function deserialize(el) { return children.map(child => jsx('text', attrs, child)); } + // Convert inline CSS on span elements generated by Google Docs + if (nodeName === 'SPAN') { + const attrs = {}; + for (let i = 0; i < el.style.length; i++) { + const propertyName = el.style[i]; + if (INLINE_STYLES[propertyName]) { + const propertyValue = el.style.getPropertyValue(propertyName); + const propertyStyle = INLINE_STYLES[propertyName](propertyValue); + Object.assign(attrs, propertyStyle); + } + } + return children.map(child => jsx('text', attrs, child)); + } + return children; } diff --git a/packages/decap-cms-widget-object/CHANGELOG.md b/packages/decap-cms-widget-object/CHANGELOG.md index c7bfc1350685..2ac5456251fa 100644 --- a/packages/decap-cms-widget-object/CHANGELOG.md +++ b/packages/decap-cms-widget-object/CHANGELOG.md @@ -3,6 +3,18 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.3.1](https://github.com/decaporg/decap-cms/compare/decap-cms-widget-object@3.3.0...decap-cms-widget-object@3.3.1) (2025-01-30) + +### Bug Fixes + +- **ObjectControl:** hotfix nested object validation ([#7385](https://github.com/decaporg/decap-cms/issues/7385)) ([3f5461c](https://github.com/decaporg/decap-cms/commit/3f5461c4e854ce3b9a7fb08974e270d54f5fccff)) + +# [3.3.0](https://github.com/decaporg/decap-cms/compare/decap-cms-widget-object@3.2.0...decap-cms-widget-object@3.3.0) (2025-01-29) + +### Features + +- visual editing (click-to-edit) ([#7374](https://github.com/decaporg/decap-cms/issues/7374)) ([989c2dd](https://github.com/decaporg/decap-cms/commit/989c2dd6ed80f69b572b8b73c4e37b5106ae04fb)) + # [3.2.0](https://github.com/decaporg/decap-cms/compare/decap-cms-widget-object@3.1.4...decap-cms-widget-object@3.2.0) (2025-01-15) ### Bug Fixes diff --git a/packages/decap-cms-widget-object/package.json b/packages/decap-cms-widget-object/package.json index 1bfddf240d0a..1b5e6489913d 100644 --- a/packages/decap-cms-widget-object/package.json +++ b/packages/decap-cms-widget-object/package.json @@ -1,7 +1,7 @@ { "name": "decap-cms-widget-object", "description": "Widget for displaying an object of fields for Decap CMS.", - "version": "3.2.0", + "version": "3.3.1", "homepage": "https://www.decapcms.org/docs/widgets/#object", "repository": "https://github.com/decaporg/decap-cms/tree/main/packages/decap-cms-widget-object", "bugs": "https://github.com/decaporg/decap-cms/issues", diff --git a/packages/decap-cms-widget-object/src/ObjectControl.js b/packages/decap-cms-widget-object/src/ObjectControl.js index 2ceaa70f9385..5c29dee3f6a5 100644 --- a/packages/decap-cms-widget-object/src/ObjectControl.js +++ b/packages/decap-cms-widget-object/src/ObjectControl.js @@ -22,7 +22,18 @@ const styleStrings = { }; export default class ObjectControl extends React.Component { - componentValidate = {}; + childRefs = {}; + + processControlRef = ref => { + if (!ref) return; + const parentId = ref.props.parentIds[ref.props.parentIds.length - 1]; + const belongsToDifferentParent = parentId && this.props.forID && parentId !== this.props.forID; + if (!belongsToDifferentParent) { + const name = ref.props.field.get('name'); + this.childRefs[name] = ref; + } + this.props.controlRef?.(this); + }; static propTypes = { onChangeObject: PropTypes.func.isRequired, @@ -80,12 +91,20 @@ export default class ObjectControl extends React.Component { fields = List.isList(fields) ? fields : List([fields]); fields.forEach(field => { const widget = field.get('widget'); + if (widget === 'hidden' || (widget === 'object' && field.has('flat'))) return; + const parentName = field.get('parentName'); const name = field.get('name'); const validateName = parentName ? `${parentName}.${name}` : name; - this.componentValidate[validateName](); + const control = this.childRefs[validateName]; + + if (control?.innerWrappedControl?.validate) { + control.innerWrappedControl.validate(); + } else { + control?.validate?.(); + } }); }; @@ -145,7 +164,6 @@ export default class ObjectControl extends React.Component { metadata, fieldsErrors, editorControl: EditorControl, - controlRef, parentIds, isFieldDuplicate, isFieldHidden, @@ -173,8 +191,7 @@ export default class ObjectControl extends React.Component { fieldsMetaData={metadata} fieldsErrors={fieldsErrors} onValidate={onValidateObject} - processControlRef={controlRef && controlRef.bind(this)} - controlRef={controlRef} + controlRef={this.processControlRef} parentIds={[...parentIds, forID]} isDisabled={isDuplicate} isHidden={isHidden} @@ -190,6 +207,26 @@ export default class ObjectControl extends React.Component { this.setState({ collapsed: !this.state.collapsed }); }; + focus(path) { + if (this.state.collapsed) { + this.setState({ collapsed: false }, () => { + if (path) { + const [fieldName, ...remainingPath] = path.split('.'); + const field = this.childRefs[fieldName]; + if (field?.focus) { + field.focus(remainingPath.join('.')); + } + } + }); + } else if (path) { + const [fieldName, ...remainingPath] = path.split('.'); + const field = this.childRefs[fieldName]; + if (field?.focus) { + field.focus(remainingPath.join('.')); + } + } + } + orderRenderedFields = (renderedFields, field) => { const order = field.get('order').toJS(); if (!order.length) return renderedFields; @@ -229,7 +266,9 @@ export default class ObjectControl extends React.Component { ?.map(field => field.set('parentName', fieldParentName)); const singleField = f.get('field')?.set('parentName', fieldParentName); - return mappedMultiFields.push(...this.renderFields(multiFields, singleField, f)); + const renderedFields = this.renderFields(multiFields, singleField, f); + if (Array.isArray(renderedFields)) return mappedMultiFields.push(...renderedFields); + return mappedMultiFields.push(renderedFields); } return mappedMultiFields.push(this.controlFor(f, idx)); }); diff --git a/packages/decap-cms-widget-relation/src/RelationControl.js b/packages/decap-cms-widget-relation/src/RelationControl.js index c17deca0a536..c9e5be261451 100644 --- a/packages/decap-cms-widget-relation/src/RelationControl.js +++ b/packages/decap-cms-widget-relation/src/RelationControl.js @@ -227,15 +227,12 @@ export default class RelationControl extends React.Component { return ( this.props.value !== nextProps.value || this.props.hasActiveStyle !== nextProps.hasActiveStyle || - this.props.queryHits !== nextProps.queryHits + this.props.queryHits !== nextProps.queryHits || + this.props.field.get('collection') !== nextProps.field.get('collection') ); } - async componentDidMount() { - this.mounted = true; - // if the field has a previous value perform an initial search based on the value field - // this is required since each search is limited by optionsLength so the selected value - // might not show up on the search + async loadInitialOptions() { const { forID, field, value, query, onChange } = this.props; const collection = field.get('collection'); const file = field.get('file'); @@ -272,6 +269,17 @@ export default class RelationControl extends React.Component { } } + async componentDidMount() { + this.mounted = true; + await this.loadInitialOptions(); + } + + async componentDidUpdate(prevProps) { + if (this.props.field.get('collection') !== prevProps.field.get('collection')) { + await this.loadInitialOptions(); + } + } + componentWillUnmount() { this.mounted = false; } @@ -424,7 +432,7 @@ export default class RelationControl extends React.Component { value={selectedValue} inputId={forID} cacheOptions - defaultOptions + defaultOptions={options?.length ? options : true} loadOptions={this.loadOptions} onChange={this.handleChange} className={classNameWrapper} diff --git a/packages/decap-cms-widget-string/src/StringControl.js b/packages/decap-cms-widget-string/src/StringControl.js index 339e9338058f..01910fc36174 100644 --- a/packages/decap-cms-widget-string/src/StringControl.js +++ b/packages/decap-cms-widget-string/src/StringControl.js @@ -29,9 +29,11 @@ export default class StringControl extends React.Component { // The input element ref _el = null; - shouldComponentUpdate(nextProps, nextState) { + shouldComponentUpdate(nextProps, nextState = {}) { return Boolean( - nextState && (this.state.value !== nextState.value || nextProps.value !== nextState.value), + this.props.classNameWrapper !== nextProps.classNameWrapper || + this.state.value !== nextState.value || + nextProps.value !== nextState.value ); } diff --git a/packages/decap-cms/CHANGELOG.md b/packages/decap-cms/CHANGELOG.md index b8a3511b2dc8..3b1df21c6d28 100644 --- a/packages/decap-cms/CHANGELOG.md +++ b/packages/decap-cms/CHANGELOG.md @@ -3,6 +3,22 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +## [3.6.3](https://github.com/decaporg/decap-cms/compare/decap-cms@3.6.2...decap-cms@3.6.3) (2025-05-15) + +**Note:** Version bump only for package decap-cms + +## [3.6.2](https://github.com/decaporg/decap-cms/compare/decap-cms@3.6.1...decap-cms@3.6.2) (2025-02-13) + +**Note:** Version bump only for package decap-cms + +## [3.6.1](https://github.com/decaporg/decap-cms/compare/decap-cms@3.6.0...decap-cms@3.6.1) (2025-01-30) + +**Note:** Version bump only for package decap-cms + +# [3.6.0](https://github.com/decaporg/decap-cms/compare/decap-cms@3.5.0...decap-cms@3.6.0) (2025-01-29) + +**Note:** Version bump only for package decap-cms + # [3.5.0](https://github.com/decaporg/decap-cms/compare/decap-cms@3.4.0...decap-cms@3.5.0) (2025-01-15) ### Bug Fixes diff --git a/packages/decap-cms/package.json b/packages/decap-cms/package.json index 3b46f8be8dc9..e7ce740992c0 100644 --- a/packages/decap-cms/package.json +++ b/packages/decap-cms/package.json @@ -1,7 +1,7 @@ { "name": "decap-cms", "description": "An extensible, open source, Git-based, React CMS for static sites.", - "version": "3.5.0", + "version": "3.6.3", "homepage": "https://www.decapcms.org", "repository": "https://github.com/decaporg/decap-cms", "bugs": "https://github.com/decaporg/decap-cms/issues", @@ -22,7 +22,7 @@ "dependencies": { "codemirror": "^5.46.0", "create-react-class": "^15.7.0", - "decap-cms-app": "^3.5.0", + "decap-cms-app": "^3.6.3", "decap-cms-media-library-cloudinary": "^3.0.3", "decap-cms-media-library-uploadcare": "^3.0.2", "file-loader": "^6.2.0", diff --git a/packages/decap-server/CHANGELOG.md b/packages/decap-server/CHANGELOG.md index 3cadf6e587a8..8715efd9cbc2 100644 --- a/packages/decap-server/CHANGELOG.md +++ b/packages/decap-server/CHANGELOG.md @@ -3,6 +3,10 @@ All notable changes to this project will be documented in this file. See [Conventional Commits](https://conventionalcommits.org) for commit guidelines. +# [3.2.0](https://github.com/decaporg/decap-cms/compare/decap-server@3.1.2...decap-server@3.2.0) (2025-01-29) + +**Note:** Version bump only for package decap-server + ## [3.1.2](https://github.com/decaporg/decap-cms/compare/decap-server@3.1.1...decap-server@3.1.2) (2024-08-13) ### Reverts diff --git a/packages/decap-server/package.json b/packages/decap-server/package.json index e6bb8bb8a828..61b582d03e4b 100644 --- a/packages/decap-server/package.json +++ b/packages/decap-server/package.json @@ -1,7 +1,7 @@ { "name": "decap-server", "description": "Proxy server to be used with Decap CMS proxy backend", - "version": "3.1.2", + "version": "3.2.0", "repository": "https://github.com/decaporg/decap-cms/tree/main/packages/decap-server", "bugs": "https://github.com/decaporg/decap-cms/issues", "license": "MIT", @@ -39,7 +39,7 @@ "@types/morgan": "^1.7.37", "@types/node": "^16.0.0", "@types/vfile-message": "^2.0.0", - "decap-cms-lib-util": "^3.1.0", + "decap-cms-lib-util": "^3.2.0", "jest": "^27.0.0", "nodemon": "^2.0.2", "ts-jest": "^27.0.0",