static-cms/src/formats/formats.js

84 lines
2.5 KiB
JavaScript
Raw Normal View History

import { List } from 'immutable';
import yamlFormatter from './yaml';
import tomlFormatter from './toml';
import jsonFormatter from './json';
import { FrontmatterInfer, frontmatterJSON, frontmatterTOML, frontmatterYAML } from './frontmatter';
export const frontmatterFormats = ['yaml-frontmatter','toml-frontmatter','json-frontmatter']
export const supportedFormats = [
'yml',
'yaml',
'toml',
'json',
'frontmatter',
'json-frontmatter',
'toml-frontmatter',
'yaml-frontmatter',
];
export const formatToExtension = format => ({
yml: 'yml',
yaml: 'yml',
toml: 'toml',
json: 'json',
frontmatter: 'md',
'json-frontmatter': 'md',
'toml-frontmatter': 'md',
'yaml-frontmatter': 'md',
}[format]);
2016-09-11 23:08:18 +02:00
export function formatByExtension(extension) {
2016-09-13 14:53:50 +02:00
return {
2016-10-27 15:33:15 +02:00
yml: yamlFormatter,
yaml: yamlFormatter,
toml: tomlFormatter,
2016-10-27 15:33:15 +02:00
json: jsonFormatter,
md: FrontmatterInfer,
markdown: FrontmatterInfer,
html: FrontmatterInfer,
}[extension];
2016-09-13 14:53:50 +02:00
}
function formatByName(name, customDelimiter) {
2016-09-13 14:53:50 +02:00
return {
yml: yamlFormatter,
2016-10-27 15:33:15 +02:00
yaml: yamlFormatter,
toml: tomlFormatter,
2017-11-18 08:17:49 -07:00
json: jsonFormatter,
frontmatter: FrontmatterInfer,
'json-frontmatter': frontmatterJSON(customDelimiter),
'toml-frontmatter': frontmatterTOML(customDelimiter),
'yaml-frontmatter': frontmatterYAML(customDelimiter),
}[name];
2016-09-13 14:53:50 +02:00
}
2016-09-06 13:04:17 -03:00
export function resolveFormat(collectionOrEntity, entry) {
// Check for custom delimiter
const frontmatter_delimiter = collectionOrEntity.get('frontmatter_delimiter');
const customDelimiter = List.isList(frontmatter_delimiter) ? frontmatter_delimiter.toArray() : frontmatter_delimiter;
// If the format is specified in the collection, use that format.
const formatSpecification = collectionOrEntity.get('format');
if (formatSpecification) {
return formatByName(formatSpecification, customDelimiter);
2016-09-11 23:08:18 +02:00
}
// If a file already exists, infer the format from its file extension.
const filePath = entry && entry.path;
if (filePath) {
const fileExtension = filePath.split('.').pop();
return formatByExtension(fileExtension);
}
// If creating a new file, and an `extension` is specified in the
// collection config, infer the format from that extension.
const extension = collectionOrEntity.get('extension');
if (extension) {
return formatByExtension(extension);
}
// If no format is specified and it cannot be inferred, return the default.
return formatByName('frontmatter', customDelimiter);
}