Skip to content

Commit

Permalink
update file and collections to modules
Browse files Browse the repository at this point in the history
  • Loading branch information
chrisdiana committed Dec 5, 2018
1 parent a845c97 commit c0ef7c9
Show file tree
Hide file tree
Showing 9 changed files with 985 additions and 268 deletions.
773 changes: 730 additions & 43 deletions dist/cms.js

Large diffs are not rendered by default.

2 changes: 2 additions & 0 deletions examples/js/config.js
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ var config = {
layout: { list: 'page-list', single: 'page' },
},
],

debug: true,
};

// Initialize CMS.js
Expand Down
23 changes: 13 additions & 10 deletions src/file.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,17 @@
import { get, extend, formatDate, Markdown, renderLayout } from './utils';

/**
* Represents a file.
* @constructor
* @param {string} url - The URL of the file.
* @param {string} type - The type of file (i.e. posts, pages).
* @param {object} layout - The layout templates of the file.
*/
var File = function(url, type, layout) {
var File = function(url, type, layout, config) {
this.url = url;
this.type = type;
this.layout = layout;
this.config = config;
this.html = false;
this.content;
this.name;
Expand Down Expand Up @@ -53,7 +56,7 @@ File.prototype = {
* Overrides post attributes if front matter is available.
*/
parseFrontMatter: function() {
var yaml = this.content.split(config.frontMatterSeperator)[1];
var yaml = this.content.split(this.config.frontMatterSeperator)[1];
if (yaml) {
var attributes = {};
yaml.split(/\n/g).forEach(function(attributeStr) {
Expand All @@ -72,7 +75,7 @@ File.prototype = {
* an array by splitting the string by commas.
*/
setListAttributes: function() {
config.listAttributes.forEach(function(attribute) {
this.config.listAttributes.forEach(function(attribute) {
if (this.hasOwnProperty(attribute) && this[attribute]) {
this[attribute] = this[attribute].split(',').map(function(item) {
return item.trim();
Expand All @@ -88,7 +91,7 @@ File.prototype = {
setFilename: function() {
this.name = this.url.substr(this.url.lastIndexOf('/'))
.replace('/', '')
.replace(config.extension, '');
.replace(this.config.extension, '');
},

/**
Expand All @@ -107,7 +110,7 @@ File.prototype = {
* in the front matter.
*/
setDate: function() {
var dateRegEx = new RegExp(config.dateParser);
var dateRegEx = new RegExp(this.config.dateParser);
if (this.date) {
this.datetime = new Date(this.date);
this.date = formatDate(this.date);
Expand All @@ -126,14 +129,14 @@ File.prototype = {
*/
setBody: function() {
var html = this.content
.split(config.frontMatterSeperator)
.split(this.config.frontMatterSeperator)
.splice(2)
.join(config.frontMatterSeperator);
.join(this.config.frontMatterSeperator);
if (this.html) {
this.body = html;
} else {
if (config.markdownEngine) {
this.body = config.markdownEngine(html);
if (this.config.markdownEngine) {
this.body = this.config.markdownEngine(html);
} else {
var md = new Markdown();
this.body = md.render(html);
Expand Down Expand Up @@ -162,7 +165,7 @@ File.prototype = {
* @async
*/
render: function() {
return renderLayout(this.layout, this);
return renderLayout(this.layout, this.config, this);
},
};

Expand Down
19 changes: 12 additions & 7 deletions src/filecollection.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,17 @@
import { messages as msg, createMessageContainer, handleMessage } from './messages';
import { get, isValidFile, renderLayout } from './utils';
import File from './file';

/**
* Represents a file collection.
* @constructor
* @param {string} type - The type of file collection (i.e. posts, pages).
* @param {object} layout - The layouts of the file collection type.
*/
var FileCollection = function(type, layout) {
var FileCollection = function(type, layout, config) {
this.type = type;
this.layout = layout;
this.config = config;
this.files = [];
this[type] = this.files;
};
Expand Down Expand Up @@ -58,7 +63,7 @@ FileCollection.prototype = {
var fileElements;

// Github Mode
if (config.mode === 'GITHUB') {
if (this.config.mode === 'GITHUB') {
fileElements = JSON.parse(data);
}
// Server Mode
Expand All @@ -79,13 +84,13 @@ FileCollection.prototype = {
* @param {function} callback - Callback function
*/
getFiles: function(callback) {
get(this.getFileListUrl(this.type, config), function(success, error) {
get(this.getFileListUrl(this.type, this.config), function(success, error) {
if (error) callback(success, error);
// find the file elements that are valid files, exclude others
this.getFileElements(success).forEach(function(file) {
var fileUrl = this.getFileUrl(file, config.mode);
if (isValidFile(fileUrl, config.extension)) {
this.files.push(new File(fileUrl, this.type, this.layout.single));
var fileUrl = this.getFileUrl(file, this.config.mode);
if (isValidFile(fileUrl, this.config.extension)) {
this.files.push(new File(fileUrl, this.type, this.layout.single, this.config));
}
}.bind(this));
callback(success, error);
Expand Down Expand Up @@ -171,7 +176,7 @@ FileCollection.prototype = {
* @returns {string} Rendered layout
*/
render: function() {
return renderLayout(this.layout.list, this);
return renderLayout(this.layout.list, this.config, this);
},
};

Expand Down
205 changes: 205 additions & 0 deletions src/instance.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@

import defaults from './defaults';
import { messages as msg, createMessageContainer, handleMessage } from './messages';
import { getFunctionName,
getParameterByName,
getPathsWithoutParameters,
renderLayout,
setContainer } from './utils';
import FileCollection from './filecollection';


let ready = false;
let options;
const routes = {};
const collections = {};
const filteredCollections = {};

function Instance (options) {

/**
* Register plugins.
* @method
* @description
* Set up plugins based on user configuration.
*/
function registerPlugins(config) {
config.plugins.forEach(function(plugin) {
var name = getFunctionName(plugin);
if (!this[name]) {
this[name] = plugin;
}
});
}

/**
* Router
* @method
* @description
* Sets up router for file collections to render collections
* and files based on URL hash.
*/
function router() {
var paths = getPathsWithoutParameters();

var type = paths[0];
var filename = paths[1];
var collection = collections[type];

var query = getParameterByName('query') || '';
var tag = getParameterByName('tag') || '';

routes[type] = function() {
// Default view
if (!type) {
window.location = ['#', config.defaultView].join('/');
}
// List and single views
else {
if (filename) {
// Single view
var permalink = ['#', type, filename.trim()].join('/');
collection.getFileByPermalink(permalink).render();
} else if (collection) {
// List view
if (query) {
// Check for queries
collection.search('title', query);
} else if (tag) {
// Check for tags
collection.getByTag(tag);
} else {
// Reset search
collection.resetSearch();
}
collection.render();
} else {
// Error view
renderLayout(config.errorLayout, config, {});
}
}
// onroute event
config.onroute();
};
return routes[type]();
};

/**
* Initialize file collections
* @method
* @async
*/
function initFileCollections(config, callback) {
var promises = [];
var types = [];

// setup collections and routes
config.types.forEach((type) => {
collections[type.name] = new FileCollection(type.name, type.layout, config);
types.push(type.name);
});

// init collections
types.forEach((type, i) => {
collections[type].init(() => {
promises.push(i);
// reverse order to display newest posts first for post types
if (type.indexOf('post') === 0) {
collections[type][type].reverse();
}
// Execute after all content is loaded
if (types.length == promises.length) {
callback();
}
});
});
};

/**
* Init
* @method
* @description
* Initializes the application based on the configuration. Sets up up config object,
* hash change event listener for router, and loads the content.
*/
function init() {
// set config
config = Object.assign({}, defaults, options);

// create message container element if debug mode is enabled
if (config.debug) {
createMessageContainer(config.messageClassName);
}

if (config.elementId) {
// setup container
config.container = document.getElementById(config.elementId);

// check for hash changes
window.addEventListener('hashchange', router);

if (config.container) {
// setup file collections
initFileCollections(config, () => {
// start router by manually triggering hash change
window.dispatchEvent(new HashChangeEvent('hashchange'));
// register plugins and run onload events
ready = true;
// TODO: registerPlugins();
config.onload();
});
} else {
handleMessage(config.debug, msg['ELEMENT_ID_ERROR']);
}
} else {
handleMessage(config.debug, msg['ELEMENT_ID_ERROR']);
}
}

// Initialize
init();

return {

ready,
routes,
collections,
filteredCollections,

/**
* Sort method for file collections.
* @method
* @param {string} type - Type of file collection.
* @param {function} sort - Sorting function.
*/
sort(type, sort) {
if (this.ready) {
this.collections[type][type].sort(sort);
this.collections[type].render();
} else {
handleMessage(msg['NOT_READY_WARNING']);
}
},

/**
* Search method for file collections.
* @method
* @param {string} type - Type of file collection.
* @param {string} attribute - File attribute to search.
* @param {string} search - Search query.
*/
search(type, attribute, search) {
if (this.ready) {
this.collections[type].search(attribute, search);
this.collections[type].render();
} else {
handleMessage(msg['NOT_READY_WARNING']);
}
},

}

}


export default Instance;
Loading

0 comments on commit c0ef7c9

Please sign in to comment.