refactor: remove ImmutableJS from applyDefaults function (#4940)

This commit is contained in:
Vladislav Shkodin
2021-02-10 17:52:02 +02:00
committed by GitHub
parent 35cb9b6844
commit 521896cd66
2 changed files with 585 additions and 639 deletions

View File

@ -1,4 +1,3 @@
import { fromJS } from 'immutable';
import { stripIndent } from 'common-tags'; import { stripIndent } from 'common-tags';
import { import {
parseConfig, parseConfig,
@ -96,95 +95,83 @@ describe('config', () => {
describe('applyDefaults', () => { describe('applyDefaults', () => {
describe('publish_mode', () => { describe('publish_mode', () => {
it('should set publish_mode if not set', () => { it('should set publish_mode if not set', () => {
const config = fromJS({ const config = {
foo: 'bar', foo: 'bar',
media_folder: 'path/to/media', media_folder: 'path/to/media',
public_folder: '/path/to/media', public_folder: '/path/to/media',
collections: [], collections: [],
}); };
expect(applyDefaults(config).get('publish_mode')).toEqual('simple'); expect(applyDefaults(config).publish_mode).toEqual('simple');
}); });
it('should set publish_mode from config', () => { it('should set publish_mode from config', () => {
const config = fromJS({ const config = {
foo: 'bar', foo: 'bar',
publish_mode: 'complex', publish_mode: 'complex',
media_folder: 'path/to/media', media_folder: 'path/to/media',
public_folder: '/path/to/media', public_folder: '/path/to/media',
collections: [], collections: [],
}); };
expect(applyDefaults(config).get('publish_mode')).toEqual('complex'); expect(applyDefaults(config).publish_mode).toEqual('complex');
}); });
}); });
describe('public_folder', () => { describe('public_folder', () => {
it('should set public_folder based on media_folder if not set', () => { it('should set public_folder based on media_folder if not set', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
foo: 'bar', foo: 'bar',
media_folder: 'path/to/media', media_folder: 'path/to/media',
collections: [], collections: [],
}), }).public_folder,
).get('public_folder'),
).toEqual('/path/to/media'); ).toEqual('/path/to/media');
}); });
it('should not overwrite public_folder if set', () => { it('should not overwrite public_folder if set', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
foo: 'bar', foo: 'bar',
media_folder: 'path/to/media', media_folder: 'path/to/media',
public_folder: '/publib/path', public_folder: '/publib/path',
collections: [], collections: [],
}), }).public_folder,
).get('public_folder'),
).toEqual('/publib/path'); ).toEqual('/publib/path');
expect( expect(
applyDefaults( applyDefaults({
fromJS({
foo: 'bar', foo: 'bar',
media_folder: 'path/to/media', media_folder: 'path/to/media',
public_folder: '', public_folder: '',
collections: [], collections: [],
}), }).public_folder,
).get('public_folder'),
).toEqual(''); ).toEqual('');
}); });
}); });
describe('slug', () => { describe('slug', () => {
it('should set default slug config if not set', () => { it('should set default slug config if not set', () => {
expect(applyDefaults(fromJS({ collections: [] })).get('slug')).toEqual( expect(applyDefaults({ collections: [] }).slug).toEqual({
fromJS({ encoding: 'unicode', clean_accents: false, sanitize_replacement: '-' }), encoding: 'unicode',
); clean_accents: false,
sanitize_replacement: '-',
});
}); });
it('should not overwrite slug encoding if set', () => { it('should not overwrite slug encoding if set', () => {
expect( expect(
applyDefaults(fromJS({ collections: [], slug: { encoding: 'ascii' } })).getIn([ applyDefaults({ collections: [], slug: { encoding: 'ascii' } }).slug.encoding,
'slug',
'encoding',
]),
).toEqual('ascii'); ).toEqual('ascii');
}); });
it('should not overwrite slug clean_accents if set', () => { it('should not overwrite slug clean_accents if set', () => {
expect( expect(
applyDefaults(fromJS({ collections: [], slug: { clean_accents: true } })).getIn([ applyDefaults({ collections: [], slug: { clean_accents: true } }).slug.clean_accents,
'slug',
'clean_accents',
]),
).toEqual(true); ).toEqual(true);
}); });
it('should not overwrite slug sanitize_replacement if set', () => { it('should not overwrite slug sanitize_replacement if set', () => {
expect( expect(
applyDefaults(fromJS({ collections: [], slug: { sanitize_replacement: '_' } })).getIn([ applyDefaults({ collections: [], slug: { sanitize_replacement: '_' } }).slug
'slug', .sanitize_replacement,
'sanitize_replacement',
]),
).toEqual('_'); ).toEqual('_');
}); });
}); });
@ -192,31 +179,26 @@ describe('config', () => {
describe('collections', () => { describe('collections', () => {
it('should strip leading slashes from collection folder', () => { it('should strip leading slashes from collection folder', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
collections: [{ folder: '/foo', fields: [{ name: 'title', widget: 'string' }] }], collections: [{ folder: '/foo', fields: [{ name: 'title', widget: 'string' }] }],
}), }).collections[0].folder,
).getIn(['collections', 0, 'folder']),
).toEqual('foo'); ).toEqual('foo');
}); });
it('should strip leading slashes from collection files', () => { it('should strip leading slashes from collection files', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
collections: [ collections: [
{ files: [{ file: '/foo', fields: [{ name: 'title', widget: 'string' }] }] }, { files: [{ file: '/foo', fields: [{ name: 'title', widget: 'string' }] }] },
], ],
}), }).collections[0].files[0].file,
).getIn(['collections', 0, 'files', 0, 'file']),
).toEqual('foo'); ).toEqual('foo');
}); });
describe('public_folder and media_folder', () => { describe('public_folder and media_folder', () => {
it('should set collection public_folder based on media_folder if not set', () => { it('should set collection public_folder based on media_folder if not set', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
collections: [ collections: [
{ {
folder: 'foo', folder: 'foo',
@ -224,15 +206,13 @@ describe('config', () => {
fields: [{ name: 'title', widget: 'string' }], fields: [{ name: 'title', widget: 'string' }],
}, },
], ],
}), }).collections[0].public_folder,
).getIn(['collections', 0, 'public_folder']),
).toEqual('static/images/docs'); ).toEqual('static/images/docs');
}); });
it('should not overwrite collection public_folder if set', () => { it('should not overwrite collection public_folder if set', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
collections: [ collections: [
{ {
folder: 'foo', folder: 'foo',
@ -241,14 +221,12 @@ describe('config', () => {
fields: [{ name: 'title', widget: 'string' }], fields: [{ name: 'title', widget: 'string' }],
}, },
], ],
}), }).collections[0].public_folder,
).getIn(['collections', 0, 'public_folder']),
).toEqual('images/docs'); ).toEqual('images/docs');
}); });
it("should set collection media_folder and public_folder to an empty string when collection path exists, but collection media_folder doesn't", () => { it("should set collection media_folder and public_folder to an empty string when collection path exists, but collection media_folder doesn't", () => {
const result = applyDefaults( const result = applyDefaults({
fromJS({
collections: [ collections: [
{ {
folder: 'foo', folder: 'foo',
@ -256,16 +234,14 @@ describe('config', () => {
fields: [{ name: 'title', widget: 'string' }], fields: [{ name: 'title', widget: 'string' }],
}, },
], ],
}), });
); expect(result.collections[0].media_folder).toEqual('');
expect(result.getIn(['collections', 0, 'media_folder'])).toEqual(''); expect(result.collections[0].public_folder).toEqual('');
expect(result.getIn(['collections', 0, 'public_folder'])).toEqual('');
}); });
it('should set file public_folder based on media_folder if not set', () => { it('should set file public_folder based on media_folder if not set', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
collections: [ collections: [
{ {
files: [ files: [
@ -277,15 +253,13 @@ describe('config', () => {
], ],
}, },
], ],
}), }).collections[0].files[0].public_folder,
).getIn(['collections', 0, 'files', 0, 'public_folder']),
).toEqual('static/images/docs'); ).toEqual('static/images/docs');
}); });
it('should not overwrite file public_folder if set', () => { it('should not overwrite file public_folder if set', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
collections: [ collections: [
{ {
files: [ files: [
@ -298,14 +272,12 @@ describe('config', () => {
], ],
}, },
], ],
}), }).collections[0].files[0].public_folder,
).getIn(['collections', 0, 'files', 0, 'public_folder']),
).toEqual('images/docs'); ).toEqual('images/docs');
}); });
it('should set nested field public_folder based on media_folder if not set', () => { it('should set nested field public_folder based on media_folder if not set', () => {
const config = applyDefaults( const config = applyDefaults({
fromJS({
collections: [ collections: [
{ {
folder: 'foo', folder: 'foo',
@ -333,19 +305,17 @@ describe('config', () => {
], ],
}, },
], ],
}), });
); expect(config.collections[0].fields[0].public_folder).toEqual(
expect(config.getIn(['collections', 0, 'fields', 0, 'public_folder'])).toEqual(
'collection/static/images/docs', 'collection/static/images/docs',
); );
expect( expect(config.collections[1].files[0].fields[0].public_folder).toEqual(
config.getIn(['collections', 1, 'files', 0, 'fields', 0, 'public_folder']), 'file/static/images/docs',
).toEqual('file/static/images/docs'); );
}); });
it('should not overwrite nested field public_folder if set', () => { it('should not overwrite nested field public_folder if set', () => {
const config = applyDefaults( const config = applyDefaults({
fromJS({
collections: [ collections: [
{ {
folder: 'foo', folder: 'foo',
@ -374,22 +344,18 @@ describe('config', () => {
], ],
}, },
], ],
}), });
expect(config.collections[0].fields[0].public_folder).toEqual('collection/public_folder');
expect(config.collections[1].files[0].fields[0].public_folder).toEqual(
'file/public_folder',
); );
expect(config.getIn(['collections', 0, 'fields', 0, 'public_folder'])).toEqual(
'collection/public_folder',
);
expect(
config.getIn(['collections', 1, 'files', 0, 'fields', 0, 'public_folder']),
).toEqual('file/public_folder');
}); });
}); });
describe('publish', () => { describe('publish', () => {
it('should set publish to true if not set', () => { it('should set publish to true if not set', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
collections: [ collections: [
{ {
folder: 'foo', folder: 'foo',
@ -397,15 +363,13 @@ describe('config', () => {
fields: [{ name: 'title', widget: 'string' }], fields: [{ name: 'title', widget: 'string' }],
}, },
], ],
}), }).collections[0].publish,
).getIn(['collections', 0, 'publish']),
).toEqual(true); ).toEqual(true);
}); });
it('should not override existing publish config', () => { it('should not override existing publish config', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
collections: [ collections: [
{ {
folder: 'foo', folder: 'foo',
@ -414,16 +378,14 @@ describe('config', () => {
fields: [{ name: 'title', widget: 'string' }], fields: [{ name: 'title', widget: 'string' }],
}, },
], ],
}), }).collections[0].publish,
).getIn(['collections', 0, 'publish']),
).toEqual(false); ).toEqual(false);
}); });
}); });
describe('editor preview', () => { describe('editor preview', () => {
it('should set editor preview honoring global config before and specific config after', () => { it('should set editor preview honoring global config before and specific config after', () => {
const config = applyDefaults( const config = applyDefaults({
fromJS({
editor: { editor: {
preview: false, preview: false,
}, },
@ -440,11 +402,10 @@ describe('config', () => {
folder: 'bar', folder: 'bar',
}, },
], ],
}), });
);
expect(config.getIn(['collections', 0, 'editor', 'preview'])).toEqual(false); expect(config.collections[0].editor.preview).toEqual(false);
expect(config.getIn(['collections', 1, 'editor', 'preview'])).toEqual(true); expect(config.collections[1].editor.preview).toEqual(true);
}); });
}); });
}); });
@ -452,7 +413,6 @@ describe('config', () => {
test('should convert camel case to snake case', () => { test('should convert camel case to snake case', () => {
expect( expect(
applyDefaults( applyDefaults(
fromJS(
normalizeConfig({ normalizeConfig({
collections: [ collections: [
{ {
@ -498,15 +458,14 @@ describe('config', () => {
], ],
}), }),
), ),
).toJS(),
).toEqual({ ).toEqual({
public_folder: '/',
publish_mode: 'simple',
slug: { clean_accents: false, encoding: 'unicode', sanitize_replacement: '-' },
collections: [ collections: [
{ {
sortable_fields: ['title'], sortable_fields: ['title'],
folder: 'src', folder: 'src',
type: 'folder_based_collection',
view_filters: [],
view_groups: [],
identifier_field: 'datetime', identifier_field: 'datetime',
fields: [ fields: [
{ {
@ -525,10 +484,7 @@ describe('config', () => {
valueType: 'float', valueType: 'float',
}, },
], ],
meta: {},
publish: true, publish: true,
view_filters: [],
view_groups: [],
}, },
{ {
sortable_fields: [], sortable_fields: [],
@ -556,19 +512,22 @@ describe('config', () => {
], ],
}, },
], ],
publish: true, type: 'file_based_collection',
view_filters: [], view_filters: [],
view_groups: [], view_groups: [],
publish: true,
}, },
], ],
public_folder: '/',
publish_mode: 'simple',
slug: { clean_accents: false, encoding: 'unicode', sanitize_replacement: '-' },
}); });
}); });
describe('i18n', () => { describe('i18n', () => {
it('should set root i18n on collection when collection i18n is set to true', () => { it('should set root i18n on collection when collection i18n is set to true', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -576,31 +535,25 @@ describe('config', () => {
collections: [ collections: [
{ folder: 'foo', i18n: true, fields: [{ name: 'title', widget: 'string' }] }, { folder: 'foo', i18n: true, fields: [{ name: 'title', widget: 'string' }] },
], ],
}), }).collections[0].i18n,
)
.getIn(['collections', 0, 'i18n'])
.toJS(),
).toEqual({ structure: 'multiple_folders', locales: ['en', 'de'], default_locale: 'en' }); ).toEqual({ structure: 'multiple_folders', locales: ['en', 'de'], default_locale: 'en' });
}); });
it('should not set root i18n on collection when collection i18n is not set', () => { it('should not set root i18n on collection when collection i18n is not set', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
}, },
collections: [{ folder: 'foo', fields: [{ name: 'title', widget: 'string' }] }], collections: [{ folder: 'foo', fields: [{ name: 'title', widget: 'string' }] }],
}), }).collections[0].i18n,
).getIn(['collections', 0, 'i18n']),
).toBeUndefined(); ).toBeUndefined();
}); });
it('should not set root i18n on collection when collection i18n is set to false', () => { it('should not set root i18n on collection when collection i18n is set to false', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -608,15 +561,13 @@ describe('config', () => {
collections: [ collections: [
{ folder: 'foo', i18n: false, fields: [{ name: 'title', widget: 'string' }] }, { folder: 'foo', i18n: false, fields: [{ name: 'title', widget: 'string' }] },
], ],
}), }).collections[0].i18n,
).getIn(['collections', 0, 'i18n']),
).toBeUndefined(); ).toBeUndefined();
}); });
it('should merge root i18n on collection when collection i18n is set to an object', () => { it('should merge root i18n on collection when collection i18n is set to an object', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -629,17 +580,13 @@ describe('config', () => {
fields: [{ name: 'title', widget: 'string' }], fields: [{ name: 'title', widget: 'string' }],
}, },
], ],
}), }).collections[0].i18n,
)
.getIn(['collections', 0, 'i18n'])
.toJS(),
).toEqual({ structure: 'multiple_folders', locales: ['en', 'fr'], default_locale: 'fr' }); ).toEqual({ structure: 'multiple_folders', locales: ['en', 'fr'], default_locale: 'fr' });
}); });
it('should throw when i18n structure is not single_file on files collection', () => { it('should throw when i18n structure is not single_file on files collection', () => {
expect(() => expect(() =>
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -658,14 +605,12 @@ describe('config', () => {
}, },
], ],
}), }),
),
).toThrow('i18n configuration for files collections is limited to single_file structure'); ).toThrow('i18n configuration for files collections is limited to single_file structure');
}); });
it('should throw when i18n structure is set to multiple_folders and contains a single file collection', () => { it('should throw when i18n structure is set to multiple_folders and contains a single file collection', () => {
expect(() => expect(() =>
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -679,14 +624,12 @@ describe('config', () => {
}, },
], ],
}), }),
),
).toThrow('i18n configuration for files collections is limited to single_file structure'); ).toThrow('i18n configuration for files collections is limited to single_file structure');
}); });
it('should throw when i18n structure is set to multiple_files and contains a single file collection', () => { it('should throw when i18n structure is set to multiple_files and contains a single file collection', () => {
expect(() => expect(() =>
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_files', structure: 'multiple_files',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -700,14 +643,12 @@ describe('config', () => {
}, },
], ],
}), }),
),
).toThrow('i18n configuration for files collections is limited to single_file structure'); ).toThrow('i18n configuration for files collections is limited to single_file structure');
}); });
it('should set i18n value to translate on field when i18n=true for field in files collection', () => { it('should set i18n value to translate on field when i18n=true for field in files collection', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -727,15 +668,13 @@ describe('config', () => {
}, },
}, },
], ],
}), }).collections[0].files[0].fields[0].i18n,
).getIn(['collections', 0, 'files', 0, 'fields', 0, 'i18n']),
).toEqual('translate'); ).toEqual('translate');
}); });
it('should set i18n value to translate on field when i18n=true for field', () => { it('should set i18n value to translate on field when i18n=true for field', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -747,15 +686,13 @@ describe('config', () => {
fields: [{ name: 'title', widget: 'string', i18n: true }], fields: [{ name: 'title', widget: 'string', i18n: true }],
}, },
], ],
}), }).collections[0].fields[0].i18n,
).getIn(['collections', 0, 'fields', 0, 'i18n']),
).toEqual('translate'); ).toEqual('translate');
}); });
it('should set i18n value to none on field when i18n=false for field', () => { it('should set i18n value to none on field when i18n=false for field', () => {
expect( expect(
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -767,15 +704,13 @@ describe('config', () => {
fields: [{ name: 'title', widget: 'string', i18n: false }], fields: [{ name: 'title', widget: 'string', i18n: false }],
}, },
], ],
}), }).collections[0].fields[0].i18n,
).getIn(['collections', 0, 'fields', 0, 'i18n']),
).toEqual('none'); ).toEqual('none');
}); });
it('should throw is default locale is missing from root i18n config', () => { it('should throw is default locale is missing from root i18n config', () => {
expect(() => expect(() =>
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -788,14 +723,12 @@ describe('config', () => {
}, },
], ],
}), }),
),
).toThrow("i18n locales 'en, de' are missing the default locale fr"); ).toThrow("i18n locales 'en, de' are missing the default locale fr");
}); });
it('should throw is default locale is missing from collection i18n config', () => { it('should throw is default locale is missing from collection i18n config', () => {
expect(() => expect(() =>
applyDefaults( applyDefaults({
fromJS({
i18n: { i18n: {
structure: 'multiple_folders', structure: 'multiple_folders',
locales: ['en', 'de'], locales: ['en', 'de'],
@ -810,7 +743,6 @@ describe('config', () => {
}, },
], ],
}), }),
),
).toThrow("i18n locales 'en, de' are missing the default locale fr"); ).toThrow("i18n locales 'en, de' are missing the default locale fr");
}); });
}); });

View File

@ -1,13 +1,15 @@
import yaml from 'yaml'; import yaml from 'yaml';
import { Map, fromJS } from 'immutable'; import { fromJS } from 'immutable';
import deepmerge from 'deepmerge'; import deepmerge from 'deepmerge';
import { produce } from 'immer';
import { trimStart, trim, get, isPlainObject, isEmpty } from 'lodash'; import { trimStart, trim, get, isPlainObject, isEmpty } from 'lodash';
import { SIMPLE as SIMPLE_PUBLISH_MODE } from '../constants/publishModes'; import { SIMPLE as SIMPLE_PUBLISH_MODE } from '../constants/publishModes';
import { validateConfig } from '../constants/configSchema'; import { validateConfig } from '../constants/configSchema';
import { selectDefaultSortableFields, traverseFields } from '../reducers/collections'; import { selectDefaultSortableFields } from '../reducers/collections';
import { getIntegrations, selectIntegration } from '../reducers/integrations'; import { getIntegrations, selectIntegration } from '../reducers/integrations';
import { resolveBackend } from '../backend'; import { resolveBackend } from '../backend';
import { I18N, I18N_FIELD, I18N_STRUCTURE } from '../lib/i18n'; import { I18N, I18N_FIELD, I18N_STRUCTURE } from '../lib/i18n';
import { FILES, FOLDER } from '../constants/collectionTypes';
export const CONFIG_REQUEST = 'CONFIG_REQUEST'; export const CONFIG_REQUEST = 'CONFIG_REQUEST';
export const CONFIG_SUCCESS = 'CONFIG_SUCCESS'; export const CONFIG_SUCCESS = 'CONFIG_SUCCESS';
@ -40,11 +42,11 @@ function getConfigUrl() {
return 'config.yml'; return 'config.yml';
} }
function setDefaultPublicFolder(map) { function setDefaultPublicFolderForField(field) {
if (map.has('media_folder') && !map.has('public_folder')) { if ('media_folder' in field && !field.public_folder) {
map = map.set('public_folder', map.get('media_folder')); return { ...field, public_folder: field.media_folder };
} }
return map; return field;
} }
// Mapping between existing camelCase and its snake_case counterpart // Mapping between existing camelCase and its snake_case counterpart
@ -74,57 +76,42 @@ function setSnakeCaseConfig(field) {
} }
function setI18nField(field) { function setI18nField(field) {
if (field.get(I18N) === true) { if (field[I18N] === true) {
field = field.set(I18N, I18N_FIELD.TRANSLATE); return { ...field, [I18N]: I18N_FIELD.TRANSLATE };
} else if (field.get(I18N) === false || !field.has(I18N)) { } else if (field[I18N] === false || !field[I18N]) {
field = field.set(I18N, I18N_FIELD.NONE); return { ...field, [I18N]: I18N_FIELD.NONE };
} }
return field; return field;
} }
function setI18nDefaults(defaultI18n, collectionOrFile) { function getI18nDefaults(collectionOrFileI18n, defaultI18n) {
if (defaultI18n && collectionOrFile.has(I18N)) { if (typeof collectionOrFileI18n === 'boolean') {
const collectionOrFileI18n = collectionOrFile.get(I18N); return defaultI18n;
if (collectionOrFileI18n === true) {
collectionOrFile = collectionOrFile.set(I18N, defaultI18n);
} else if (collectionOrFileI18n === false) {
collectionOrFile = collectionOrFile.delete(I18N);
} else { } else {
const locales = collectionOrFileI18n.get('locales', defaultI18n.get('locales')); const locales = collectionOrFileI18n.locales || defaultI18n.locales;
const defaultLocale = collectionOrFileI18n.get( const defaultLocale = collectionOrFileI18n.default_locale || locales[0];
'default_locale', const mergedI18n = deepmerge(defaultI18n, collectionOrFileI18n);
collectionOrFileI18n.has('locales') ? locales.first() : defaultI18n.get('default_locale'), mergedI18n.locales = locales;
); mergedI18n.default_locale = defaultLocale;
collectionOrFile = collectionOrFile.set(I18N, defaultI18n.merge(collectionOrFileI18n)); throwOnMissingDefaultLocale(mergedI18n);
collectionOrFile = collectionOrFile.setIn([I18N, 'locales'], locales); return mergedI18n;
collectionOrFile = collectionOrFile.setIn([I18N, 'default_locale'], defaultLocale); }
}
throwOnMissingDefaultLocale(collectionOrFile.get(I18N)); function setI18nDefaultsForFields(collectionOrFileFields, hasI18n) {
} if (hasI18n) {
return traverseFieldsJS(collectionOrFileFields, setI18nField);
if (collectionOrFileI18n !== false) {
// set default values for i18n fields
if (collectionOrFile.has('fields')) {
collectionOrFile = collectionOrFile.set(
'fields',
traverseFields(collectionOrFile.get('fields'), setI18nField),
);
}
}
} else { } else {
collectionOrFile = collectionOrFile.delete(I18N); return traverseFieldsJS(collectionOrFileFields, field => {
if (collectionOrFile.has('fields')) { const newField = { ...field };
collectionOrFile = collectionOrFile.set( delete newField[I18N];
'fields', return newField;
traverseFields(collectionOrFile.get('fields'), field => field.delete(I18N)), });
);
} }
}
return collectionOrFile;
} }
function throwOnInvalidFileCollectionStructure(i18n) { function throwOnInvalidFileCollectionStructure(i18n) {
if (i18n && i18n.get('structure') !== I18N_STRUCTURE.SINGLE_FILE) { if (i18n && i18n.structure !== I18N_STRUCTURE.SINGLE_FILE) {
throw new Error( throw new Error(
`i18n configuration for files collections is limited to ${I18N_STRUCTURE.SINGLE_FILE} structure`, `i18n configuration for files collections is limited to ${I18N_STRUCTURE.SINGLE_FILE} structure`,
); );
@ -132,35 +119,19 @@ function throwOnInvalidFileCollectionStructure(i18n) {
} }
function throwOnMissingDefaultLocale(i18n) { function throwOnMissingDefaultLocale(i18n) {
if (i18n && !i18n.get('locales').includes(i18n.get('default_locale'))) { if (i18n && i18n.default_locale && !i18n.locales.includes(i18n.default_locale)) {
throw new Error( throw new Error(
`i18n locales '${i18n.get('locales').join(', ')}' are missing the default locale ${i18n.get( `i18n locales '${i18n.locales.join(', ')}' are missing the default locale ${
'default_locale', i18n.default_locale
)}`, }`,
); );
} }
} }
function setViewPatternsDefaults(key, collection) {
if (!collection.has(key)) {
collection = collection.set(key, fromJS([]));
} else {
collection = collection.set(
key,
collection.get(key).map(v => v.set('id', `${v.get('field')}__${v.get('pattern')}`)),
);
}
return collection;
}
const defaults = {
publish_mode: SIMPLE_PUBLISH_MODE,
};
function hasIntegration(config, collection) { function hasIntegration(config, collection) {
const integrations = getIntegrations(config); // TODO remove fromJS when Immutable is removed from the integrations state slice
const integration = selectIntegration(integrations, collection.get('name'), 'listEntries'); const integrations = getIntegrations(fromJS(config));
const integration = selectIntegration(integrations, collection.name, 'listEntries');
return !!integration; return !!integration;
} }
@ -199,120 +170,163 @@ export function normalizeConfig(config) {
return { ...config, collections: normalizedCollections }; return { ...config, collections: normalizedCollections };
} }
export function applyDefaults(config) { export function applyDefaults(originalConfig) {
return Map(defaults) return produce(originalConfig, config => {
.mergeDeep(config) config.publish_mode = config.publish_mode || SIMPLE_PUBLISH_MODE;
.withMutations(map => { config.slug = config.slug || {};
config.collections = config.collections || [];
// Use `site_url` as default `display_url`. // Use `site_url` as default `display_url`.
if (!map.get('display_url') && map.get('site_url')) { if (!config.display_url && config.site_url) {
map.set('display_url', map.get('site_url')); config.display_url = config.site_url;
} }
// Use media_folder as default public_folder. // Use media_folder as default public_folder.
const defaultPublicFolder = `/${trimStart(map.get('media_folder'), '/')}`; const defaultPublicFolder = `/${trimStart(config.media_folder, '/')}`;
if (!map.has('public_folder')) { if (!('public_folder' in config)) {
map.set('public_folder', defaultPublicFolder); config.public_folder = defaultPublicFolder;
} }
// default values for the slug config // default values for the slug config
if (!map.getIn(['slug', 'encoding'])) { if (!('encoding' in config.slug)) {
map.setIn(['slug', 'encoding'], 'unicode'); config.slug.encoding = 'unicode';
} }
if (!map.getIn(['slug', 'clean_accents'])) { if (!('clean_accents' in config.slug)) {
map.setIn(['slug', 'clean_accents'], false); config.slug.clean_accents = false;
} }
if (!map.getIn(['slug', 'sanitize_replacement'])) { if (!('sanitize_replacement' in config.slug)) {
map.setIn(['slug', 'sanitize_replacement'], '-'); config.slug.sanitize_replacement = '-';
}
const i18n = config[I18N];
const hasI18n = Boolean(i18n);
if (hasI18n) {
i18n.default_locale = i18n.default_locale || i18n.locales[0];
} }
let i18n = config.get(I18N);
i18n = i18n?.set('default_locale', i18n.get('default_locale', i18n.get('locales').first()));
throwOnMissingDefaultLocale(i18n); throwOnMissingDefaultLocale(i18n);
// Strip leading slash from collection folders and files const backend = resolveBackend(config);
map.set(
'collections', for (const collection of config.collections) {
map.get('collections').map(collection => { if (!('publish' in collection)) {
if (!collection.has('publish')) { collection.publish = true;
collection = collection.set('publish', true);
} }
collection = setI18nDefaults(i18n, collection); const collectionHasI18n = Boolean(collection[I18N]);
if (hasI18n && collectionHasI18n) {
const folder = collection.get('folder'); collection[I18N] = getI18nDefaults(collection[I18N], i18n);
if (folder) {
if (collection.has('path') && !collection.has('media_folder')) {
// default value for media folder when using the path config
collection = collection.set('media_folder', '');
}
collection = setDefaultPublicFolder(collection);
collection = collection.set(
'fields',
traverseFields(collection.get('fields'), setDefaultPublicFolder),
);
collection = collection.set('folder', trim(folder, '/'));
if (collection.has('meta')) {
const fields = collection.get('fields');
const metaFields = [];
collection.get('meta').forEach((value, key) => {
const field = value.withMutations(map => {
map.set('name', key);
map.set('meta', true);
map.set('required', true);
});
metaFields.push(field);
});
collection = collection.set('fields', fromJS([]).concat(metaFields, fields));
} else { } else {
collection = collection.set('meta', Map()); delete collection[I18N];
}
if (collection.fields) {
collection.fields = setI18nDefaultsForFields(collection.fields, collectionHasI18n);
}
const { folder, files, view_filters, view_groups, meta } = collection;
if (folder) {
collection.type = FOLDER;
if (collection.path && !collection.media_folder) {
// default value for media folder when using the path config
collection.media_folder = '';
}
if ('media_folder' in collection && !collection.public_folder) {
collection.public_folder = collection.media_folder;
}
if (collection.fields) {
collection.fields = traverseFieldsJS(collection.fields, setDefaultPublicFolderForField);
}
collection.folder = trim(folder, '/');
if (meta && meta.path) {
const metaField = {
name: 'path',
meta: true,
required: true,
...meta.path,
};
collection.fields = [metaField, ...(collection.fields || [])];
} }
} }
const files = collection.get('files');
if (files) { if (files) {
const collectionI18n = collection.get(I18N); collection.type = FILES;
// after we invoked setI18nDefaults,
// i18n property can't be boolean anymore
const collectionI18n = collection[I18N];
throwOnInvalidFileCollectionStructure(collectionI18n); throwOnInvalidFileCollectionStructure(collectionI18n);
collection = collection.delete('nested'); delete collection.nested;
collection = collection.delete('meta'); delete collection.meta;
collection = collection.set(
'files', for (const file of files) {
files.map(file => { file.file = trimStart(file.file, '/');
file = file.set('file', trimStart(file.get('file'), '/'));
file = setDefaultPublicFolder(file); if ('media_folder' in file && !file.public_folder) {
file = file.set( file.public_folder = file.media_folder;
'fields',
traverseFields(file.get('fields'), setDefaultPublicFolder),
);
file = setI18nDefaults(collectionI18n, file);
throwOnInvalidFileCollectionStructure(file.get(I18N));
return file;
}),
);
} }
if (!collection.has('sortable_fields')) { if (file.fields) {
const backend = resolveBackend(config); file.fields = traverseFieldsJS(file.fields, setDefaultPublicFolderForField);
const defaultSortable = selectDefaultSortableFields( }
collection,
const fileHasI18n = Boolean(file[I18N]);
if (fileHasI18n) {
if (collectionI18n) {
file[I18N] = getI18nDefaults(file[I18N], collectionI18n);
}
} else {
delete file[I18N];
}
if (file.fields) {
file.fields = setI18nDefaultsForFields(file.fields, fileHasI18n);
}
// after we invoked setI18nDefaults,
// i18n property can't be boolean anymore
const fileI18n = file[I18N];
throwOnInvalidFileCollectionStructure(fileI18n);
}
}
if (!collection.sortable_fields) {
collection.sortable_fields = selectDefaultSortableFields(
// TODO remove fromJS when Immutable is removed from the collections state slice
fromJS(collection),
backend, backend,
hasIntegration(map, collection), hasIntegration(config, collection),
); );
collection = collection.set('sortable_fields', fromJS(defaultSortable));
} }
collection = setViewPatternsDefaults('view_filters', collection); collection.view_filters = (view_filters || []).map(filter => {
collection = setViewPatternsDefaults('view_groups', collection); return {
...filter,
id: `${filter.field}__${filter.pattern}`,
};
});
if (map.hasIn(['editor', 'preview']) && !collection.has('editor')) { collection.view_groups = (view_groups || []).map(group => {
collection = collection.setIn(['editor', 'preview'], map.getIn(['editor', 'preview'])); return {
...group,
id: `${group.field}__${group.pattern}`,
};
});
if (config.editor && !collection.editor) {
collection.editor = { preview: config.editor.preview };
}
} }
return collection;
}),
);
}); });
} }
@ -446,9 +460,9 @@ export function loadConfig(manualConfig = {}, onLoad) {
const withLocalBackend = await handleLocalBackend(mergedConfig); const withLocalBackend = await handleLocalBackend(mergedConfig);
const normalizedConfig = normalizeConfig(withLocalBackend); const normalizedConfig = normalizeConfig(withLocalBackend);
const config = applyDefaults(fromJS(normalizedConfig)); const config = applyDefaults(normalizedConfig);
dispatch(configLoaded(config)); dispatch(configLoaded(fromJS(config)));
if (typeof onLoad === 'function') { if (typeof onLoad === 'function') {
onLoad(); onLoad();