LT-253: Creating dynamic form components

This commit is contained in:
Bruno Alves de Faria authored and Erik Ziegler committed 2016-07-22 11:12:04 +02:00
1 parent 88f737644f
commit cb875b1913
72 files changed
+1169 -126

No files matched your search

@@ -0,0 +1,49 @@
import { OHIF } from 'meteor/ohif:core';
/*
* Base component to template instances of all dynamic components
*/
class Component {
// Set up the component
constructor(templateInstance) {
// Store the component in the current view
templateInstance.view._component = this;
// Create an object to register section's content
templateInstance.sections = {};
// Store the template instance in the component
this.templateInstance = templateInstance;
// Store the component's registered sub-components
this.registeredItems = new Set();
}
// Self register the component in its first parent component
registerSelf() {
const parent = OHIF.blaze.getParentComponent(this.templateInstance.view);
if (parent) {
// Store this component's parent in a property
this.parent = parent;
// Add this component in its parent's registered items list
parent.registeredItems.add(this);
}
}
// Self unregister the component in its first parent component
unregisterSelf() {
const parent = OHIF.blaze.getParentComponent(this.templateInstance.view);
if (parent) {
// Remove the parent property from this component
delete this.parent;
// Remove this component from its parent's registered items list
parent.registeredItems.delete(this);
}
}
}
OHIF.Component = Component;
@@ -0,0 +1,26 @@
// Core files
import './component.js';
import './mixin.js';
import './template.js';
// Mixins
import './mixins/component.js';
import './mixins/form.js';
import './mixins/formItem.js';
import './mixins/group.js';
import './mixins/groupRadio.js';
import './mixins/input.js';
import './mixins/schemaData.js';
import './mixins/select.js';
import './mixins/select2.js';
// Templates
import './templates/custom.html';
import './templates/div.html';
import './templates/form.html';
import './templates/input.html';
import './templates/select.html';
// wrappers
import './wrappers/label.html';
import './wrappers/title.html';
+126
View File
@@ -0,0 +1,126 @@
import { OHIF } from 'meteor/ohif:core';
import { _ } from 'meteor/underscore';
// Create an object to store all the application mixins
OHIF.mixins = {};
// Class to manage new mixins and its dependencies
class Mixin {
// Create the mixin instance
constructor({ dependencies, composition }) {
// Store the mixin dependencies
this.dependencies = dependencies || '';
// Store the mixin composition
this.composition = composition;
}
// Initialize the mixin applying all its composition functions
init(template, data, applied, behaviors) {
const dependenciesArray = this.dependencies.split(' ');
_.each(dependenciesArray, dependency => {
// Go to next dependency if the current dependency string is blank
if (!dependency) {
return;
}
// Get the dependent mixin to be initizalized
const mixin = Mixin.getMixin(dependency);
// Initizalize the mixin dependencies recursively
mixin.init(template, data, applied, behaviors);
});
// Apply the mixin's composition behaviors to the template
this.apply(template, data, applied, behaviors);
}
// Add the mixin's composition behaviors to the template
apply(template, data, applied, behaviors) {
// Ignore if the mixin was already applied to the template
if (_.contains(applied, this)) {
return;
}
// Store the mixin's composition
const composition = this.composition;
// Iterate over each behavior
_.each(behaviors, behavior => {
// Execute something only after all the mixins are done
let functionName = behavior;
if (functionName === 'onMixins') {
functionName = 'onRendered';
}
if (behavior === 'onData' && composition[behavior]) {
// If it's just data manipulation, call it immediately
composition[behavior](data);
} else if (composition[behavior]) {
// Register the behavior in the template
template[functionName](composition[behavior]);
}
});
// Set the current mixin's state as applied
applied.push(this);
}
// Initialize all data manipulation mixins
static initData(data) {
// Split the mixins by space
const mixinsArray = data.mixins.split(' ');
_.each(mixinsArray, mixinName => {
// Ignore blank strings
if (!mixinName) {
return;
}
// Get the current mixin
const mixin = Mixin.getMixin(mixinName);
// Initialize the data manipulation composition
mixin.init(null, data, [], ['onData']);
});
}
// Initialize all the template's mixins
static initAll(template, data) {
// Split the mixins by space
const mixinsArray = data.mixins.split(' ');
_.each(mixinsArray, mixinName => {
// Ignore blank strings
if (!mixinName) {
return;
}
// Get the current mixin
const mixin = Mixin.getMixin(mixinName);
// Initialize blaze default compositions
mixin.init(template, data, [], ['onCreated', 'onRendered', 'onDestroyed', 'events', 'helpers']);
// Execute some behaviors after all mixins are applied
mixin.init(template, data, [], ['onMixins']);
});
}
// Get a mixin by name
static getMixin(mixinName) {
// Get the mixin from mixins object
const mixin = OHIF.mixins[mixinName];
// Throw an error if the mixin does not exists
if (!mixin) {
throw new Error(`Mixin ${mixinName} not found.`);
}
// Return the found mixin
return mixin;
}
}
// Store the Mixin class inside the shared OHIF object
OHIF.Mixin = Mixin;
@@ -0,0 +1,16 @@
import { OHIF } from 'meteor/ohif:core';
import { Template } from 'meteor/templating';
/*
* component: create the base structure to aplly specific component mixins
*/
OHIF.mixins.component = new OHIF.Mixin({
composition: {
onCreated() {
const instance = Template.instance();
// Declare a property that will be shared among all dependent mixins
instance.component = new OHIF.Component(this);
}
}
});
@@ -0,0 +1,50 @@
import { OHIF } from 'meteor/ohif:core';
import { Template } from 'meteor/templating';
/*
* form: controls a form and its registered inputs
*/
OHIF.mixins.form = new OHIF.Mixin({
dependencies: 'group',
composition: {
onCreated() {
const instance = Template.instance();
const component = instance.component;
// Define the form's data schema
const schema = instance.data.schema;
component.schema = schema && schema.newContext();
// Check if the form data is valid in its schema
component.validate = () => {
// Assume validation result as true
let result = true;
// Return true if there's no data schema defined
if (!component.schema) {
return result;
}
// Iterate over each registered form item and validate it
component.registeredItems.forEach(child => {
const key = child.templateInstance.data.key;
// Change result to false if any form item is invalid
if (key && !child.validate()) {
result = false;
}
});
// Return the validation result
return result;
};
},
onRendered() {
const instance = Template.instance();
const component = instance.component;
// Set the component main and style elements
component.$style = component.$element = instance.$('form').first();
}
}
});
@@ -0,0 +1,154 @@
import { OHIF } from 'meteor/ohif:core';
import { Template } from 'meteor/templating';
import { _ } from 'meteor/underscore';
import { $ } from 'meteor/jquery';
/*
* formItem: create a generic controller for form items
* It may be used to manage all components that belong to forms
*/
OHIF.mixins.formItem = new OHIF.Mixin({
dependencies: 'component',
composition: {
onCreated() {
const instance = Template.instance();
const component = instance.component;
// Register the component in the parent component
component.registerSelf();
// Declare the component elements that will be manipulated
component.$element = $();
component.$style = $();
component.$wrapper = $();
// Get or set the component's value using jQuery's val method
component.value = value => {
const isGet = _.isUndefined(value);
if (isGet) {
return component.$element.val();
}
component.$element.val(value).trigger('change');
};
// Disable or enable the component
component.disable = isDisable => {
component.$element.prop('disabled', !!isDisable);
};
// Set or unset component's readonly property
component.readonly = isReadonly => {
component.$element.prop('readonly', !!isReadonly);
};
// Show or hide the component
component.show = isShow => {
const method = isShow ? 'show' : 'hide';
component.$wrapper[method]();
};
// Add or remove a state from the component
component.state = (state, flag) => {
component.$wrapper.toggleClass(`state-${state}`, !!flag);
};
// Set the component in error state and display the error message
component.error = errorMessage => {
// Set the component error state
component.state('error', errorMessage);
// Set or remove the error message
if (errorMessage) {
component.$element.trigger('errorin');
component.$wrapper.attr('data-error', errorMessage);
} else {
component.$element.trigger('errorout');
component.$wrapper.removeAttr('data-error', errorMessage);
}
};
// Check if the component value is valid in its form's schema
component.validate = () => {
// Get the component's form
const form = component.parent;
// Get the form's data schema
const schema = form && form.schema;
// Get the current component's key
const key = instance.data.key;
// Return true if validation is not needed
if (!key || !schema || !component.$wrapper.is(':visible')) {
return true;
}
// Create the data document for validation
const document = {
[key]: component.value()
};
// Check if the document validation failed
if (!schema.validateOne(document, key)) {
// Set the component in error state and display the message
component.error(schema.keyErrorMessage(key));
// Return false for validation
return false;
}
// Remove the component error state and message
component.error(false);
// Return true for validation
return true;
};
},
onRendered() {
const instance = Template.instance();
const component = instance.component;
// Set the element to be controlled
component.$element = instance.$(':input:first');
// Set the element to be styled
component.$style = component.$element;
// Set the most outer wrapper element
component.$wrapper = instance.wrapper.$('*').first();
},
onDestroyed() {
const instance = Template.instance();
// Register the component in the parent component
instance.component.unregisterSelf();
},
onMixins() {
const instance = Template.instance();
const component = instance.component;
// Set the component in jQuery data after all mixins are rendered
component.$element.data('component', component);
},
events: {
// TODO: [design] remove log, show error box/hint over the wrapper
errorin(event, instance) {
console.log('ERROR when validating component', instance.component);
},
// TODO: [design] hide error box/hint
errorout(event, instance) {
}
}
}
});
@@ -0,0 +1,50 @@
import { OHIF } from 'meteor/ohif:core';
import { Template } from 'meteor/templating';
import { _ } from 'meteor/underscore';
/*
* group: controls a group and its registered items
*/
OHIF.mixins.group = new OHIF.Mixin({
dependencies: 'formItem',
composition: {
onCreated() {
const instance = Template.instance();
const component = instance.component;
// Get or set the child components values
component.value = value => {
const isGet = _.isUndefined(value);
if (isGet) {
const result = {};
component.registeredItems.forEach(child => {
const key = child.templateInstance.data.key;
if (key) {
result[key] = child.value();
}
});
return result;
}
const groupValue = typeof value === 'object' ? value : {};
component.registeredItems.forEach(child => {
const key = child.templateInstance.data.key;
const childValue = _.isUndefined(groupValue[key]) ? null : groupValue[key];
child.value(childValue);
});
component.$element.trigger('change');
};
// Disable or enable the component
component.disable = isDisable => {
component.registeredItems.forEach(child => child.disable(isDisable));
};
// Set or unset component's readonly property
component.readonly = isReadonly => {
component.registeredItems.forEach(child => child.readonly(isReadonly));
};
}
}
});
@@ -0,0 +1,30 @@
import { OHIF } from 'meteor/ohif:core';
import { Template } from 'meteor/templating';
import { _ } from 'meteor/underscore';
/*
* groupRadio: controls all the radio inputs inside the group
*/
OHIF.mixins.groupRadio = new OHIF.Mixin({
dependencies: 'group',
composition: {
onCreated() {
const instance = Template.instance();
const component = instance.component;
// Get the selected radio's value or select a radio based on value
component.value = value => {
const isGet = _.isUndefined(value);
const $elements = $();
component.registeredItems.forEach(child => $elements.add(child.$element));
if (isGet) {
return $elements.filter(':checked').val();
}
$elements.filter(`[value='${value}']`).prop('checked', true).trigger('change');
};
}
}
});
@@ -0,0 +1,18 @@
import { OHIF } from 'meteor/ohif:core';
import { Template } from 'meteor/templating';
/*
* input: controls a basic input
*/
OHIF.mixins.input = new OHIF.Mixin({
dependencies: 'formItem',
composition: {
onRendered() {
const instance = Template.instance();
const component = instance.component;
// Set the element to be controlled
component.$element = instance.$('input:first');
}
}
});
@@ -0,0 +1,46 @@
import { OHIF } from 'meteor/ohif:core';
import { Blaze } from 'meteor/blaze';
import { Template } from 'meteor/templating';
import { _ } from 'meteor/underscore';
/*
* schemaData: change the component data based on its form's schema data
*/
OHIF.mixins.schemaData = new OHIF.Mixin({
dependencies: 'formItem',
composition: {
onData() {
const data = Template.currentData();
const parent = OHIF.blaze.getParentComponent(Blaze.currentView);
// Get the parent component schema
const schema = parent && parent.schema;
// Get the current component's key
const key = data.key;
// Stop here if there's no key or schema defined
if (!key || !schema) {
return;
}
// Get the current schema data using component's key
const currentSchema = schema._schema[key];
// Stop here if there's no schema data for current key
if (!currentSchema) {
return;
}
// Use schema's label if it was not defined
if (!data.label) {
data.label = new ReactiveVar(currentSchema.label);
}
// TODO: [design] convert allowedValues to items and find a way to get key/value pairs
}
}
});
@@ -0,0 +1,18 @@
import { OHIF } from 'meteor/ohif:core';
import { Template } from 'meteor/templating';
/*
* input: controls a basic select
*/
OHIF.mixins.select = new OHIF.Mixin({
dependencies: 'formItem',
composition: {
onRendered() {
const instance = Template.instance();
const component = instance.component;
// Set the element to be controlled
component.$element = instance.$('select:first');
}
}
});
@@ -0,0 +1,18 @@
import { OHIF } from 'meteor/ohif:core';
import { Template } from 'meteor/templating';
/*
* input: controls a select2 component
*/
OHIF.mixins.select2 = new OHIF.Mixin({
dependencies: 'select',
composition: {
onRendered() {
const instance = Template.instance();
const component = instance.component;
// Set the element to be controlled
component.$element = instance.$('select:first');
}
}
});
@@ -0,0 +1,106 @@
import { OHIF } from 'meteor/ohif:core';
import { _ } from 'meteor/underscore';
// Create a new custom template for the base component
Template.baseComponent = new Template('baseComponent', () => {});
// Inject some custom behaviors in the view's construction function
Template.baseComponent.constructView = function(contentFunc, elseFunc) {
// Get the data passed to the template
const data = Template.currentData();
// Check the base template. If it's not informed set as the custom base
data.base || (data.base = 'baseCustom');
// Get the base template object
const baseTemplate = Template[data.base];
// Throw an error if the base template does not exists
if (!baseTemplate) {
throw new Error(`Template ${data.base} not found.`);
}
// Declare the template object and name it as base name + 'Component'
const template = OHIF.blaze.cloneTemplate(baseTemplate, data.base + 'Component');
// Extract the render function from the base template
template.renderFunction = baseTemplate.renderFunction;
// Check for the mixins. If it's not informed set the lowest level mixin
const mixins = data.mixins || 'component';
// Init the data manipulation mixins
OHIF.Mixin.initData(data);
// Create and fill a list of wrappers that will enclose the component
const wrappers = [];
if (data.wrappers) {
const wrappersList = data.wrappers.split(' ');
_.each(wrappersList, wrapper => wrapper && wrappers.push(wrapper));
}
// Declare a variable to store the wrapper instances that will be rendered
const wrapperInstances = [];
// Declare the content function to render the component
let contentFunction = () => {
// Create the most inner content function
const innerContentFunction = () => {
// Assign properties to all wrappers after template's creation
template.onCreated(() => {
const instance = Template.instance();
// Assign the template most outer wrapper
instance.wrapper = wrapperInstances[0] || instance;
// Iterate over all wrappers and assign the component to them
wrapperInstances.forEach(wrappeInstance => {
wrappeInstance.component = instance.component;
});
});
// Return the view instance
return template.constructView(contentFunc, elseFunc);
};
// Apply the mixins to the component
OHIF.Mixin.initAll(template, data);
// Return the recursive function for wrappers
return Blaze.With(data, innerContentFunction);
};
let wrapper;
while (wrapper = wrappers.shift()) {
// Get the wrapper template
const wrapperTemplate = Template[wrapper];
// Throw an error if the wrapper template does not exists
if (!wrapperTemplate) {
throw new Error(`Template ${data.base} not found.`);
}
// Clone the wrapper template to avoid assigning duplicated handlers
const currentTemplate = OHIF.blaze.cloneTemplate(wrapperTemplate);
// Store the child content function to render it inside the wrapper
const childContentFunction = contentFunction;
// Create a function that will enable the recursion for wrappers
const enclosingContentFunction = () => {
// Add the current wrapper's instance to the wrapper instances list
currentTemplate.onCreated(() => wrapperInstances.push(Template.instance()));
// Return the wrapper view instance with its child as content
return currentTemplate.constructView(childContentFunction, elseFunc);
};
// Replace the content function enclosing it recursively
contentFunction = () => {
return Blaze.With(data, enclosingContentFunction);
};
}
return contentFunction(contentFunc, elseFunc);
};
@@ -0,0 +1,3 @@
<template name="baseCustom">
{{>UI.contentBlock}}
</template>
@@ -0,0 +1,9 @@
<template name="baseDiv">
<div
id="{{this.id}}"
class="{{this.class}}"
{{this.tagAttributes}}
>
{{>UI.contentBlock}}
</div>
</template>
@@ -0,0 +1,16 @@
<template name="baseForm">
<form
id="{{this.id}}"
class="{{this.class}}"
name="{{this.name}}"
action="{{this.action}}"
method="{{this.method}}"
autocomplete="{{this.autocomplete}}"
enctype="{{this.enctype}}"
novalidate="{{this.novalidate}}"
target="{{this.target}}"
{{this.tagAttributes}}
>
{{>UI.contentBlock}}
</form>
</template>
@@ -0,0 +1,11 @@
<template name="baseInput">
<input
type="{{choose this.type 'text'}}"
id="{{this.id}}"
class="{{this.class}}"
name="{{this.name}}"
value="{{reactive this.value}}"
{{this.tagAttributes}}
>
{{>UI.contentBlock}}
</template>
@@ -0,0 +1,16 @@
<template name="baseSelect">
<select
id="{{this.id}}"
class="{{this.class}}"
name="{{this.name}}"
{{this.tagAttributes}}
>
{{>UI.contentBlock}}
{{#each item in (reactive this.items)}}
<option
value="{{item.value}}"
selected="{{#if eq item.value (reactive this.value)}}selected{{/if}}"
>{{item.label}}</option>
{{/each}}
</select>
</template>
@@ -0,0 +1,11 @@
<template name="wrapperLabel">
<label class="wrapperLabel {{this.labelClass}}">
{{#if this.labelAfter}}
{{>UI.contentBlock}}
{{/if}}
<span class="wrapperLabelText">{{reactive this.label}}</span>
{{#unless this.labelAfter}}
{{>UI.contentBlock}}
{{/unless}}
</label>
</template>
@@ -0,0 +1,11 @@
<template name="wrapperTitle">
<div class="wrapperTitle {{this.labelClass}}">
{{#if this.labelAfter}}
{{>UI.contentBlock}}
{{/if}}
<span class="wrapperTitleText">{{reactive this.label}}</span>
{{#unless this.labelAfter}}
{{>UI.contentBlock}}
{{/unless}}
</div>
</template>