cryptpad/www/form/inner.js

2547 lines
100 KiB
JavaScript
Raw Normal View History

2021-05-20 08:43:29 +00:00
define([
'jquery',
'json.sortify',
'/bower_components/chainpad-crypto/crypto.js',
'/common/sframe-app-framework.js',
'/common/toolbar.js',
'/bower_components/nthen/index.js',
'/common/sframe-common.js',
'/common/common-util.js',
'/common/common-hash.js',
'/common/common-interface.js',
'/common/common-ui-elements.js',
'/common/clipboard.js',
'/common/inner/common-mediatag.js',
'/common/hyperscript.js',
'/customize/messages.js',
'/customize/application_config.js',
2021-05-31 16:23:25 +00:00
'/common/diffMarked.js',
'/common/sframe-common-codemirror.js',
'cm/lib/codemirror',
2021-05-20 08:43:29 +00:00
'/common/inner/share.js',
'/common/inner/access.js',
'/common/inner/properties.js',
2021-05-26 15:02:34 +00:00
'/lib/datepicker/flatpickr.js',
2021-05-21 15:40:41 +00:00
'/bower_components/sortablejs/Sortable.min.js',
2021-05-31 16:23:25 +00:00
'cm/addon/display/placeholder',
'cm/mode/markdown/markdown',
'css!cm/lib/codemirror.css',
'css!/bower_components/codemirror/lib/codemirror.css',
'css!/bower_components/codemirror/addon/dialog/dialog.css',
'css!/bower_components/codemirror/addon/fold/foldgutter.css',
2021-05-26 15:02:34 +00:00
'css!/lib/datepicker/flatpickr.min.css',
2021-05-20 08:43:29 +00:00
'css!/bower_components/components-font-awesome/css/font-awesome.min.css',
'less!/form/app-form.less',
], function (
$,
2021-05-25 13:15:51 +00:00
Sortify,
2021-05-20 08:43:29 +00:00
Crypto,
Framework,
Toolbar,
nThen,
SFCommon,
Util,
Hash,
UI,
UIElements,
Clipboard,
MT,
h,
Messages,
AppConfig,
2021-05-31 16:23:25 +00:00
DiffMd,
SFCodeMirror,
CMeditor,
2021-05-21 15:40:41 +00:00
Share, Access, Properties,
2021-05-26 15:02:34 +00:00
Flatpickr,
2021-05-21 15:40:41 +00:00
Sortable
2021-05-20 08:43:29 +00:00
)
{
var APP = window.APP = {
};
2021-05-28 12:04:24 +00:00
var is24h = false;
var dateFormat = "Y-m-d H:i";
var timeFormat = "H:i";
2021-05-28 12:04:24 +00:00
try {
is24h = !new Intl.DateTimeFormat(navigator.language, { hour: 'numeric' }).format(0).match(/AM/);
} catch (e) {}
is24h = false;
if (!is24h) {
dateFormat = "Y-m-d h:i K";
timeFormat = "h:i K";
}
2021-05-28 12:04:24 +00:00
2021-05-20 08:43:29 +00:00
Messages.button_newform = "New Form"; // XXX
Messages.form_invalid = "Invalid form";
2021-06-03 15:29:03 +00:00
Messages.form_editBlock = "Edit";
2021-05-27 15:46:46 +00:00
Messages.form_editMax = "Max selectable options";
Messages.form_editMaxLength = "Maximum characters";
2021-05-28 12:04:24 +00:00
Messages.form_editType = "Options type";
Messages.form_poll_text = "Text";
Messages.form_poll_day = "Day";
Messages.form_poll_time = "Time";
2021-05-20 08:43:29 +00:00
Messages.form_textType = "Text type";
Messages.form_text_text = "Text";
Messages.form_text_url = "URL";
Messages.form_text_email = "Email";
Messages.form_text_number = "Number";
2021-05-20 08:43:29 +00:00
Messages.form_default = "Your question here?";
Messages.form_type_input = "Text"; // XXX
Messages.form_type_textarea = "Textarea"; // XXX
2021-05-20 08:43:29 +00:00
Messages.form_type_radio = "Radio"; // XXX
2021-05-27 15:46:46 +00:00
Messages.form_type_multiradio = "Multiline Radio"; // XXX
Messages.form_type_checkbox = "Checkbox"; // XXX
Messages.form_type_multicheck = "Multiline Checkbox"; // XXX
2021-05-28 12:04:24 +00:00
Messages.form_type_poll = "Poll"; // XXX
2021-05-20 08:43:29 +00:00
2021-05-31 16:23:25 +00:00
Messages.form_type_md = "Description"; // XXX
2021-06-01 15:45:04 +00:00
Messages.form_type_page = "Page break"; // XXX
2021-05-31 16:23:25 +00:00
2021-06-04 08:49:08 +00:00
Messages.form_description_default = "Your text here";
2021-05-20 08:43:29 +00:00
Messages.form_duplicates = "Duplicate entries have been removed";
2021-05-27 15:46:46 +00:00
Messages.form_maxOptions = "{0} answer(s) max";
2021-05-20 08:43:29 +00:00
2021-05-21 11:39:33 +00:00
Messages.form_submit = "Submit";
Messages.form_update = "Update";
2021-05-20 11:54:20 +00:00
Messages.form_reset = "Reset";
Messages.form_sent = "Sent";
2021-06-03 15:29:03 +00:00
Messages.form_delete = "Delete";
2021-05-20 11:54:20 +00:00
2021-05-20 14:20:15 +00:00
Messages.form_cantFindAnswers = "Unable to retrieve your existing answers for this form.";
Messages.form_answered = "You already answered this form";
2021-05-20 14:20:15 +00:00
2021-06-03 15:29:03 +00:00
Messages.form_results = "Responses";
Messages.form_editor = "Editor";
Messages.form_form = "Form";
2021-05-21 11:39:33 +00:00
Messages.form_viewResults = "Go to responses";
Messages.form_viewCreator = "Go to form creator";
2021-06-02 13:37:16 +00:00
Messages.form_showIndividual = "Show individual answers";
Messages.form_showSummary = "Show summary";
Messages.form_answerAnonymous = "Anonymous answer on <em>{0}</em>";
Messages.form_viewButton = "View";
Messages.form_backButton = "Back";
Messages.form_answerName = "Answer from {0} on <em>{1}</em>";
Messages.form_answerWarning = "Unconfirmed identity";
2021-05-20 11:54:20 +00:00
2021-05-21 11:39:33 +00:00
Messages.form_notAnswered = "And <b>{0}</b> empty answers";
2021-05-20 08:43:29 +00:00
2021-06-03 15:29:03 +00:00
Messages.form_makePublic = "Publish results";
Messages.form_makePublicWarning = "Are you sure you want to make the results of this form public? This can't be undone.";
Messages.form_isPublic = "Results are public";
Messages.form_isPrivate = "Results are private";
2021-05-26 15:02:34 +00:00
Messages.form_open = "Open";
Messages.form_setEnd = "Set closing date";
Messages.form_removeEnd = "Remove closing date";
Messages.form_isOpen = "This form is open";
Messages.form_isClosed = "This form was closed on {0}";
Messages.form_willClose = "This form will close on {0}";
2021-06-03 15:29:03 +00:00
Messages.form_anonymous = "Anonymous answers";
Messages.form_anonymous_on = "Allowed";
Messages.form_anonymous_off = "Blocked";
2021-05-31 15:19:14 +00:00
Messages.form_anonymous_blocked = "Anonymous responses are blocked for this form. You must log in or register to submit answers.";
2021-05-27 15:46:46 +00:00
Messages.form_defaultOption = "Option {0}";
Messages.form_defaultItem = "Item {0}";
Messages.form_newOption = "New option";
Messages.form_newItem = "New item";
Messages.form_add_option = "Add option";
Messages.form_add_item = "Add item";
Messages.form_addMultiple = "Add all";
Messages.form_clear = "Clear";
2021-05-27 15:46:46 +00:00
2021-06-01 15:45:04 +00:00
Messages.form_page_prev = "Previous";
Messages.form_page = "Page {0}/{1}";
Messages.form_page_next = "Next";
2021-05-31 15:19:14 +00:00
Messages.form_anonymousBox = "Answer anonymously";
2021-05-27 15:46:46 +00:00
var MAX_OPTIONS = 15; // XXX
2021-05-27 15:46:46 +00:00
var MAX_ITEMS = 10; // XXX
var saveAndCancelOptions = function (getRes, cb) {
// Cancel changes
var cancelBlock = h('button.btn.btn-secondary', Messages.cancel);
$(cancelBlock).click(function () { cb(); });
// Save changes
var saveBlock = h('button.btn.btn-primary', [
h('i.fa.fa-floppy-o'),
h('span', Messages.settings_save)
]);
$(saveBlock).click(function () {
$(saveBlock).attr('disabled', 'disabled');
cb(getRes());
});
return h('div', [cancelBlock, saveBlock]);
};
var editTextOptions = function (opts, setCursorGetter, cb, tmp) {
if (tmp && tmp.content && Sortify(opts) === Sortify(tmp.old)) {
opts = tmp.content;
}
var maxLength, getLengthVal;
if (opts.maxLength) {
var lengthInput = h('input', {
type:"number",
value: opts.maxLength,
min: 100,
max: 5000
});
maxLength = h('div.cp-form-edit-max-options', [
h('span', Messages.form_editMaxLength),
lengthInput
]);
getLengthVal = function () {
var val = Number($(lengthInput).val()) || 1000;
if (val < 100) { val = 1; }
if (val > 5000) { val = 5000; }
return val;
};
var $l = $(lengthInput).on('input', Util.throttle(function () {
$l.val(getLengthVal());
}, 500));
}
var type, typeSelect;
if (opts.type) {
var options = ['text', 'number', 'url', 'email'].map(function (t) {
return {
tag: 'a',
attributes: {
'class': 'cp-form-type-value',
'data-value': t,
'href': '#',
},
content: Messages['form_text_'+t]
};
});
var dropdownConfig = {
text: '', // Button initial text
options: options, // Entries displayed in the menu
//left: true, // Open to the left of the button
//container: $(type),
isSelect: true,
caretDown: true,
buttonCls: 'btn btn-secondary'
};
typeSelect = UIElements.createDropdown(dropdownConfig);
typeSelect.setValue(opts.type);
type = h('div.cp-form-edit-type', [
h('span', Messages.form_textType),
typeSelect[0]
]);
}
setCursorGetter(function () {
return {
old: (tmp && tmp.old) || opts,
content: {
maxLength: getLengthVal ? getLengthVal() : undefined,
type: typeSelect ? typeSelect.getValue() : undefined
}
};
});
var getSaveRes = function () {
return {
maxLength: getLengthVal ? getLengthVal() : undefined,
type: typeSelect ? typeSelect.getValue() : undefined
};
};
var saveAndCancel = saveAndCancelOptions(getSaveRes, cb);
return [
maxLength,
type,
saveAndCancel
];
};
2021-05-25 13:15:51 +00:00
var editOptions = function (v, setCursorGetter, cb, tmp) {
2021-05-20 11:54:20 +00:00
var add = h('button.btn.btn-secondary', [
h('i.fa.fa-plus'),
2021-05-27 15:46:46 +00:00
h('span', Messages.form_add_option)
]);
var addItem = h('button.btn.btn-secondary', [
h('i.fa.fa-plus'),
h('span', Messages.form_add_item)
2021-05-20 11:54:20 +00:00
]);
2021-05-25 13:15:51 +00:00
var cursor;
if (tmp && tmp.content && Sortify(v) === Sortify(tmp.old)) {
2021-05-27 15:46:46 +00:00
v = tmp.content;
2021-05-25 13:15:51 +00:00
cursor = tmp.cursor;
}
2021-05-27 15:46:46 +00:00
var maxOptions, maxInput;
if (typeof(v.max) === "number") {
maxInput = h('input', {
type:"number",
value: v.max,
min: 1,
max: v.values.length
2021-05-28 12:13:16 +00:00
});
2021-05-27 15:46:46 +00:00
maxOptions = h('div.cp-form-edit-max-options', [
h('span', Messages.form_editMax),
maxInput
]);
}
2021-05-28 12:04:24 +00:00
var type, typeSelect;
if (v.type) {
var options = ['text', 'day', 'time'].map(function (t) {
return {
tag: 'a',
attributes: {
'class': 'cp-form-type-value',
'data-value': t,
'href': '#',
},
content: Messages['form_poll_'+t]
};
});
var dropdownConfig = {
text: '', // Button initial text
options: options, // Entries displayed in the menu
//left: true, // Open to the left of the button
//container: $(type),
isSelect: true,
caretDown: true,
buttonCls: 'btn btn-secondary'
};
typeSelect = UIElements.createDropdown(dropdownConfig);
typeSelect.setValue(v.type);
type = h('div.cp-form-edit-type', [
h('span', Messages.form_editType),
typeSelect[0]
]);
}
2021-05-20 11:54:20 +00:00
// Show existing options
2021-05-28 12:13:16 +00:00
var $add, $addItem;
var addMultiple;
2021-05-27 15:46:46 +00:00
var getOption = function (val, isItem, uid) {
2021-05-20 11:54:20 +00:00
var input = h('input', {value:val});
2021-05-27 15:46:46 +00:00
if (uid) { $(input).data('uid', uid); }
2021-05-25 13:15:51 +00:00
2021-05-28 12:04:24 +00:00
// If the input is a date, initialize flatpickr
if (v.type && v.type !== 'text') {
if (v.type === 'time') {
Flatpickr(input, {
enableTime: true,
time_24hr: is24h,
dateFormat: dateFormat,
defaultDate: val ? new Date(val) : undefined
2021-05-28 12:04:24 +00:00
});
} else if (v.type === 'day') {
/*Flatpickr(input, {
defaultDate: val ? new Date(val) : undefined
});*/
}
2021-05-27 15:46:46 +00:00
}
2021-05-28 12:04:24 +00:00
// if this element was active before the remote change, restore cursor
2021-05-27 15:46:46 +00:00
var setCursor = function () {
2021-05-28 13:35:53 +00:00
if (v.type && v.type !== 'text') { return; }
2021-05-25 13:15:51 +00:00
input.selectionStart = cursor.start || 0;
input.selectionEnd = cursor.end || 0;
setTimeout(function () { input.focus(); });
2021-05-27 15:46:46 +00:00
};
if (isItem) {
if (cursor && cursor.uid === uid && cursor.item) { setCursor(); }
} else {
if (cursor && cursor.el === val && !cursor.item) { setCursor(); }
2021-05-25 13:15:51 +00:00
}
2021-05-20 11:54:20 +00:00
var del = h('button.btn.btn-danger', h('i.fa.fa-times'));
2021-05-31 13:32:04 +00:00
var el = h('div.cp-form-edit-block-input', [
h('span.cp-form-handle', [
h('i.fa.fa-ellipsis-v'),
h('i.fa.fa-ellipsis-v'),
]),
input,
del
]);
2021-05-27 15:46:46 +00:00
$(del).click(function () {
$(el).remove();
// We've just deleted an item/option so we should be under the MAX limit and
// we can show the "add" button again
if (isItem && $addItem) { $addItem.show(); }
if (!isItem && $add) {
$add.show();
if (v.type === "time") { $(addMultiple).show(); }
}
2021-05-27 15:46:46 +00:00
});
2021-05-20 11:54:20 +00:00
return el;
};
2021-05-27 15:46:46 +00:00
var inputs = v.values.map(function (val) { return getOption(val, false); });
2021-05-20 11:54:20 +00:00
inputs.push(add);
2021-05-27 15:46:46 +00:00
2021-05-20 11:54:20 +00:00
var container = h('div.cp-form-edit-block', inputs);
2021-05-28 12:04:24 +00:00
var $container = $(container);
2021-05-20 11:54:20 +00:00
2021-05-31 13:32:04 +00:00
Sortable.create(container, {
direction: "vertical",
handle: ".cp-form-handle",
draggable: ".cp-form-edit-block-input",
2021-06-03 15:29:03 +00:00
forceFallback: true,
2021-05-31 13:32:04 +00:00
});
2021-05-27 15:46:46 +00:00
var containerItems;
if (v.items) {
var inputsItems = v.items.map(function (itemData) {
return getOption(itemData.v, true, itemData.uid);
});
inputsItems.push(addItem);
containerItems = h('div.cp-form-edit-block', inputsItems);
2021-05-31 13:32:04 +00:00
Sortable.create(containerItems, {
direction: "vertical",
handle: ".cp-form-handle",
draggable: ".cp-form-edit-block-input",
2021-06-03 15:29:03 +00:00
forceFallback: true,
2021-05-31 13:32:04 +00:00
});
2021-05-27 15:46:46 +00:00
}
// Calendar...
var calendarView;
if (v.type) {
var calendarInput = h('input');
calendarView = h('div', calendarInput);
var calendarDefault = v.type === "day" ? v.values.map(function (time) {
if (!time) { return; }
var d = new Date(time);
if (!isNaN(d)) { return d; }
}).filter(Boolean) : undefined;
Flatpickr(calendarInput, {
mode: 'multiple',
inline: true,
defaultDate: calendarDefault,
appendTo: calendarView
});
}
2021-06-03 15:29:03 +00:00
// Calendar time
if (v.type) {
var multipleInput = h('input');
var multipleClearButton = h('button.btn', Messages.form_clear);
var addMultipleButton = h('button.btn', [
h('i.fa.fa-plus'),
h('span', Messages.form_addMultiple)
]);
addMultiple = h('div', { style: "display: none;" }, [
multipleInput,
addMultipleButton,
multipleClearButton
]);
var multiplePickr = Flatpickr(multipleInput, {
mode: 'multiple',
enableTime: true,
dateFormat: dateFormat,
});
$(multipleClearButton).click(function () {
multiplePickr.clear();
});
$(addMultipleButton).click(function () {
multiplePickr.selectedDates.some(function (date) {
$add.before(getOption(date, false));
var l = $container.find('input').length;
$(maxInput).attr('max', l);
if (l >= MAX_OPTIONS) {
$add.hide();
$(addMultiple).hide();
return true;
}
});
multiplePickr.clear();
});
}
var refreshView = function () {
if (!v.type) { return; }
var $calendar = $(calendarView);
if (v.type !== "day") {
$calendar.hide();
$container.show();
var l = $container.find('input').length;
if (v.type === "time" && l < MAX_OPTIONS) {
$(addMultiple).show();
} else {
$(addMultiple).hide();
}
} else {
$calendar.show();
$container.hide();
}
};
refreshView();
2021-05-28 12:04:24 +00:00
// Doodle type change: empty current values and change input types?
if (typeSelect) {
typeSelect.onChange.reg(function (prettyVal, val) {
v.type = val;
refreshView();
if (val !== "text") {
$container.find('.cp-form-edit-block-input').remove();
return;
}
2021-05-28 12:04:24 +00:00
$container.find('input').each(function (i, input) {
if (input._flatpickr) {
input._flatpickr.destroy();
delete input._flatpickr;
}
});
});
}
2021-05-27 15:46:46 +00:00
// "Add option" button handler
$add = $(add).click(function () {
2021-05-28 12:22:06 +00:00
var txt = v.type ? '' : Messages.form_newOption;
2021-05-28 12:23:02 +00:00
$add.before(getOption(txt, false));
2021-05-28 12:04:24 +00:00
var l = $container.find('input').length;
$(maxInput).attr('max', l);
if (l >= MAX_OPTIONS) { $add.hide(); }
2021-05-27 15:46:46 +00:00
});
2021-05-27 15:46:46 +00:00
// If multiline block, handle "Add item" button
$addItem = $(addItem).click(function () {
$addItem.before(getOption(Messages.form_newItem, true, Util.uid()));
if ($(containerItems).find('input').length >= MAX_ITEMS) { $addItem.hide(); }
2021-05-20 11:54:20 +00:00
});
2021-05-28 12:04:24 +00:00
if ($container.find('input').length >= MAX_OPTIONS) { $add.hide(); }
2021-05-27 15:46:46 +00:00
if ($(containerItems).find('input').length >= MAX_ITEMS) { $addItem.hide(); }
2021-05-20 11:54:20 +00:00
2021-05-25 13:15:51 +00:00
// Set cursor getter (to handle remote changes to the form)
setCursorGetter(function () {
var values = [];
var active = document.activeElement;
var cursor = {};
2021-05-28 12:04:24 +00:00
$container.find('input').each(function (i, el) {
if (el === active && !el._flatpickr) {
2021-05-25 13:15:51 +00:00
cursor.el= $(el).val();
cursor.start = el.selectionStart;
cursor.end = el.selectionEnd;
}
values.push($(el).val());
});
if (v.type === "day") {
var dayPickr = $(calendarView).find('input')[0]._flatpickr;
values = dayPickr.selectedDates.map(function (date) {
return +date;
});
}
2021-05-27 15:46:46 +00:00
var _content = {values: values};
if (maxInput) {
_content.max = Number($(maxInput).val()) || 1;
}
2021-05-28 12:04:24 +00:00
if (typeSelect) {
_content.type = typeSelect.getValue();
}
2021-05-27 15:46:46 +00:00
if (v.items) {
var items = [];
$(containerItems).find('input').each(function (i, el) {
if (el === active) {
cursor.item = true;
cursor.uid= $(el).data('uid');
cursor.start = el.selectionStart;
cursor.end = el.selectionEnd;
}
items.push({
uid: $(el).data('uid'),
v: $(el).val()
});
});
_content.items = items;
}
2021-05-25 13:15:51 +00:00
return {
2021-05-27 15:46:46 +00:00
old: (tmp && tmp.old) || v,
content: _content,
2021-05-25 13:15:51 +00:00
cursor: cursor
};
});
var getSaveRes = function () {
2021-05-27 15:46:46 +00:00
// Get values
2021-05-20 11:54:20 +00:00
var values = [];
var duplicates = false;
if (v.type === "day") {
var dayPickr = $(calendarView).find('input')[0]._flatpickr;
values = dayPickr.selectedDates.map(function (date) {
return +date;
});
} else {
$container.find('input').each(function (i, el) {
var val = $(el).val().trim();
2021-06-01 11:54:04 +00:00
if (v.type === "day" || v.type === "time") {
var f = el._flatpickr;
if (f && f.selectedDates && f.selectedDates.length) {
val = +f.selectedDates[0];
}
}
if (values.indexOf(val) === -1) { values.push(val); }
else { duplicates = true; }
});
}
if (!values.length) {
return void UI.warn(Messages.error); // XXX error message: no values
}
2021-05-27 15:46:46 +00:00
var res = { values: values };
// If multiline block, get items
if (v.items) {
var items = [];
$(containerItems).find('input').each(function (i, el) {
var val = $(el).val().trim();
var uid = $(el).data('uid');
if (!items.some(function (i) { return i.uid === uid; })) {
items.push({
uid: $(el).data('uid'),
v: val
});
}
else { duplicates = true; }
});
res.items = items;
}
// Show duplicates warning
2021-05-20 11:54:20 +00:00
if (duplicates) {
UI.warn(Messages.form_duplicates);
}
2021-05-27 15:46:46 +00:00
// If checkboxes, get the maximum number of values the users can select
if (maxInput) {
var maxVal = Number($(maxInput).val());
if (isNaN(maxVal)) { maxVal = values.length; }
res.max = maxVal;
}
2021-05-28 12:04:24 +00:00
if (typeSelect) {
res.type = typeSelect.getValue();
}
return res;
};
var saveAndCancel = saveAndCancelOptions(getSaveRes, cb);
2021-05-20 11:54:20 +00:00
return [
2021-05-28 12:04:24 +00:00
type,
2021-05-27 15:46:46 +00:00
maxOptions,
calendarView,
2021-05-27 15:46:46 +00:00
h('div.cp-form-edit-options-block', [containerItems, container]),
addMultiple,
saveAndCancel
2021-05-20 11:54:20 +00:00
];
};
2021-05-28 12:04:24 +00:00
var makePollTable = function (answers, opts) {
// Sort date values
if (opts.type !== "text") {
opts.values.sort(function (a, b) {
return +new Date(a) - +new Date(b);
});
}
2021-05-28 12:04:24 +00:00
// Create first line with options
2021-05-28 12:13:16 +00:00
var els = opts.values.map(function (data) {
2021-05-28 12:04:24 +00:00
if (opts.type === "day") {
var _date = new Date(data);
data = _date.toLocaleDateString();
}
if (opts.type === "time") {
var _dateT = new Date(data);
data = Flatpickr.formatDate(_dateT, timeFormat);
}
2021-05-28 12:04:24 +00:00
return h('div.cp-poll-cell.cp-form-poll-option', data);
});
// Insert axis switch button
2021-06-03 15:29:03 +00:00
var switchAxis = h('button.btn.btn-default', [
2021-05-28 12:04:24 +00:00
h('i.fa.fa-exchange'),
]);
els.unshift(h('div.cp-poll-cell.cp-poll-switch', switchAxis));
var lines = [h('div', els)];
// Add an initial row to "time" values containing the days
if (opts.type === "time") {
var days = [h('div.cp-poll-cell')];
var _days = {};
opts.values.forEach(function (d) {
var date = new Date(d);
var day = date.toLocaleDateString();
_days[day] = _days[day] || 0;
_days[day]++;
});
Object.keys(_days).forEach(function (day) {
days.push(h('div.cp-poll-cell.cp-poll-time-day', {
style: 'flex-grow:'+(_days[day]-1)+';'
}, day));
});
lines.unshift(h('div', days));
}
2021-05-28 12:04:24 +00:00
// Add answers
if (Array.isArray(answers)) {
answers.forEach(function (answer) {
if (!answer.name || !answer.values) { return; }
var _name = answer.name;
var values = answer.values || {};
var els = opts.values.map(function (data) {
var res = values[data] || 0;
var v = (Number(res) === 1) ? h('i.fa.fa-check.cp-yes') : undefined;
var cell = h('div.cp-poll-cell.cp-form-poll-answer', {
'data-value': res
}, v);
return cell;
});
els.unshift(h('div.cp-poll-cell.cp-poll-answer-name', _name));
lines.push(h('div', els));
});
}
var $s = $(switchAxis).click(function () {
$s.closest('.cp-form-type-poll').toggleClass('cp-form-poll-switch');
});
return lines;
};
2021-05-21 11:39:33 +00:00
var getEmpty = function (empty) {
if (empty) {
return UI.setHTML(h('div.cp-form-results-type-text-empty'), Messages._getKey('form_notAnswered', [empty]));
}
};
2021-05-27 15:46:46 +00:00
var findItem = function (items, uid) {
if (!Array.isArray(items)) { return; }
var res;
items.some(function (item) {
if (item.uid === uid) {
res = item.v;
return true;
}
});
return res;
};
2021-05-28 12:13:16 +00:00
var getBlockAnswers = function (answers, uid, filterCurve) {
return Object.keys(answers || {}).map(function (user) {
if (filterCurve && user === filterCurve) { return; }
try {
return answers[user].msg[uid];
} catch (e) { console.error(e); }
}).filter(Boolean);
};
2021-05-31 16:23:25 +00:00
var STATIC_TYPES = {
md: {
defaultOpts: {
2021-06-04 08:49:08 +00:00
text: Messages.form_description_default
2021-05-31 16:23:25 +00:00
},
get: function (opts) {
if (!opts) { opts = STATIC_TYPES.md.defaultOpts; }
var tag = h('div', {
id: 'form'+Util.uid()
}, opts.text);
var $tag = $(tag);
DiffMd.apply(DiffMd.render(opts.text || ''), $tag, APP.common);
2021-06-03 15:29:03 +00:00
var cursorGetter;
2021-05-31 16:23:25 +00:00
return {
tag: tag,
edit: function (cb, tmp) {
2021-05-31 16:23:25 +00:00
var t = h('textarea');
var block = h('div.cp-form-edit-options-block', [t]);
var cm = SFCodeMirror.create("gfm", CMeditor, t);
var editor = cm.editor;
editor.setOption('lineNumbers', true);
editor.setOption('lineWrapping', true);
editor.setOption('styleActiveLine', true);
editor.setOption('readOnly', false);
var text = opts.text;
var cursor;
if (tmp && tmp.content && tmp.old.text === text) {
text = tmp.content.text;
cursor = tmp.cursor;
}
2021-05-31 16:23:25 +00:00
setTimeout(function () {
editor.setValue(text);
if (cursor) {
if (Sortify(cursor.start) === Sortify(cursor.end)) {
editor.setCursor(cursor.start);
} else {
editor.setSelection(cursor.start, cursor.end);
}
}
2021-05-31 16:23:25 +00:00
editor.refresh();
editor.save();
editor.focus();
});
if (APP.common) {
var markdownTb = APP.common.createMarkdownToolbar(editor, {
embed: function (mt) {
editor.focus();
editor.replaceSelection($(mt)[0].outerHTML);
}
});
2021-05-31 16:23:25 +00:00
$(block).prepend(markdownTb.toolbar);
$(markdownTb.toolbar).show();
cm.configureTheme(APP.common, function () {});
}
// Cancel changes
var cancelBlock = h('button.btn.btn-secondary', Messages.cancel);
2021-06-03 15:44:59 +00:00
$(cancelBlock).click(function () {
cb();
});
2021-05-31 16:23:25 +00:00
// Save changes
var saveBlock = h('button.btn.btn-primary', [
h('i.fa.fa-floppy-o'),
h('span', Messages.settings_save)
]);
var getContent = function () {
return {
text: editor.getValue()
};
};
2021-05-31 16:23:25 +00:00
$(saveBlock).click(function () {
$(saveBlock).attr('disabled', 'disabled');
cb(getContent());
2021-05-31 16:23:25 +00:00
});
cursorGetter = function () {
if (document.activeElement && block.contains(document.activeElement)) {
cursor = {
start: editor.getCursor('from'),
end: editor.getCursor('to')
2021-06-03 15:29:03 +00:00
};
}
return {
old: opts,
content: getContent(),
cursor: cursor
};
};
2021-05-31 16:23:25 +00:00
return [
block,
h('div', [cancelBlock, saveBlock])
];
},
getCursor: function () { return cursorGetter(); },
};
},
2021-06-01 15:45:04 +00:00
printResults: function () { return; },
2021-06-04 09:14:13 +00:00
icon: h('i.cptools.cptools-form-paragraph')
2021-05-31 16:23:25 +00:00
},
2021-06-01 15:45:04 +00:00
page: {
get: function () {
var tag = h('div.cp-form-page-break-edit', [
2021-06-04 09:14:13 +00:00
h('i.cptools.cptools-form-page-break'),
2021-06-01 15:45:04 +00:00
h('span', Messages.form_type_page)
]);
return {
tag: tag,
pageBreak: true
};
},
printResults: function () { return; },
2021-06-04 09:14:13 +00:00
icon: h('i.cptools.cptools-form-page-break')
2021-06-01 15:45:04 +00:00
},
2021-05-31 16:23:25 +00:00
};
2021-05-20 08:43:29 +00:00
var TYPES = {
input: {
defaultOpts: {
type: 'text'
},
get: function (opts, a, n, evOnChange) {
if (!opts) { opts = TYPES.input.defaultOpts; }
var tag = h('input', {
type: opts.type
});
2021-05-20 08:43:29 +00:00
var $tag = $(tag);
$tag.on('change keypress', Util.throttle(function () {
evOnChange.fire();
}, 500));
var cursorGetter;
var setCursorGetter = function (f) { cursorGetter = f; };
2021-05-20 08:43:29 +00:00
return {
tag: tag,
getValue: function () {
var invalid = $tag.is(':invalid');
if (invalid) { return; } // XXX invalid answers are ignored?
return $tag.val();
},
2021-05-20 14:20:15 +00:00
setValue: function (val) { $tag.val(val); },
edit: function (cb, tmp) {
var v = Util.clone(opts);
return editTextOptions(v, setCursorGetter, cb, tmp);
},
getCursor: function () { return cursorGetter(); },
2021-05-20 11:54:20 +00:00
reset: function () { $tag.val(''); }
2021-05-20 08:43:29 +00:00
};
},
2021-05-21 11:39:33 +00:00
printResults: function (answers, uid) {
var results = [];
var empty = 0;
Object.keys(answers).forEach(function (author) {
var obj = answers[author];
var answer = obj.msg[uid];
if (!answer || !answer.trim()) { return empty++; }
results.push(h('div.cp-form-results-type-text-data', answer));
});
results.push(getEmpty(empty));
return h('div.cp-form-results-type-text', results);
},
2021-06-04 09:14:13 +00:00
icon: h('i.cptools.cptools-form-text')
2021-05-20 08:43:29 +00:00
},
textarea: {
defaultOpts: {
maxLength: 1000
},
get: function (opts, a, n, evOnChange) {
if (!opts) { opts = TYPES.textarea.defaultOpts; }
var tag = h('textarea', {maxlength: opts.maxLength});
var $tag = $(tag);
$tag.on('change keypress', Util.throttle(function () {
evOnChange.fire();
}, 500));
var cursorGetter;
var setCursorGetter = function (f) { cursorGetter = f; };
return {
tag: tag,
getValue: function () { return $tag.val(); },
setValue: function (val) { $tag.val(val); },
edit: function (cb, tmp) {
var v = Util.clone(opts);
return editTextOptions(v, setCursorGetter, cb, tmp);
},
getCursor: function () { return cursorGetter(); },
reset: function () { $tag.val(''); }
};
},
printResults: function (answers, uid) {
var results = [];
var empty = 0;
Object.keys(answers).forEach(function (author) {
var obj = answers[author];
var answer = obj.msg[uid];
if (!answer || !answer.trim()) { return empty++; }
results.push(h('div.cp-form-results-type-textarea-data', answer));
});
results.push(getEmpty(empty));
return h('div.cp-form-results-type-text', results);
},
icon: h('i.fa.fa-font')
},
2021-05-20 08:43:29 +00:00
radio: {
defaultOpts: {
2021-05-27 15:46:46 +00:00
values: [1,2].map(function (i) {
return Messages._getKey('form_defaultOption', [i]);
})
2021-05-20 08:43:29 +00:00
},
get: function (opts, a, n, evOnChange) {
2021-05-20 08:43:29 +00:00
if (!opts) { opts = TYPES.radio.defaultOpts; }
2021-05-27 15:46:46 +00:00
if (!Array.isArray(opts.values)) { return; }
2021-05-20 08:43:29 +00:00
var name = Util.uid();
var els = opts.values.map(function (data, i) {
2021-05-20 14:20:15 +00:00
var radio = UI.createRadio(name, 'cp-form-'+name+'-'+i,
data, false, { mark: { tabindex:1 } });
$(radio).find('input').data('val', data);
return radio;
2021-05-20 08:43:29 +00:00
});
2021-05-21 15:40:41 +00:00
var tag = h('div.radio-group.cp-form-type-radio', els);
2021-05-25 13:15:51 +00:00
var cursorGetter;
var setCursorGetter = function (f) { cursorGetter = f; };
$(tag).find('input[type="radio"]').on('change', function () {
evOnChange.fire();
});
2021-05-20 08:43:29 +00:00
return {
tag: tag,
getValue: function () {
var res;
2021-05-28 12:13:16 +00:00
els.some(function (el) {
2021-05-27 15:46:46 +00:00
var $i = $(el).find('input');
if (Util.isChecked($i)) {
res = $i.data('val');
return true;
2021-05-20 08:43:29 +00:00
}
});
return res;
},
2021-05-20 11:54:20 +00:00
reset: function () { $(tag).find('input').removeAttr('checked'); },
2021-05-25 13:15:51 +00:00
edit: function (cb, tmp) {
2021-05-27 15:46:46 +00:00
var v = Util.clone(opts);
2021-05-25 13:15:51 +00:00
return editOptions(v, setCursorGetter, cb, tmp);
2021-05-20 14:20:15 +00:00
},
2021-05-25 13:15:51 +00:00
getCursor: function () { return cursorGetter(); },
2021-05-20 14:20:15 +00:00
setValue: function (val) {
this.reset();
els.some(function (el) {
var $el = $(el).find('input');
if ($el.data('val') === val) {
$el.prop('checked', true);
return true;
}
});
2021-05-20 08:43:29 +00:00
}
};
},
2021-05-21 11:39:33 +00:00
printResults: function (answers, uid) {
var results = [];
var empty = 0;
var count = {};
Object.keys(answers).forEach(function (author) {
var obj = answers[author];
var answer = obj.msg[uid];
if (!answer || !answer.trim()) { return empty++; }
count[answer] = count[answer] || 0;
count[answer]++;
});
Object.keys(count).forEach(function (value) {
results.push(h('div.cp-form-results-type-radio-data', [
h('span.cp-value', value),
h('span.cp-count', count[value])
]));
});
results.push(getEmpty(empty));
return h('div.cp-form-results-type-radio', results);
},
2021-06-04 09:14:13 +00:00
icon: h('i.cptools.cptools-form-list-radio')
2021-05-27 15:46:46 +00:00
},
multiradio: {
defaultOpts: {
items: [1,2].map(function (i) {
return {
uid: Util.uid(),
v: Messages._getKey('form_defaultItem', [i])
};
}),
values: [1,2].map(function (i) {
return Messages._getKey('form_defaultOption', [i]);
})
},
get: function (opts, a, n, evOnChange) {
2021-05-27 15:46:46 +00:00
if (!opts) { opts = TYPES.multiradio.defaultOpts; }
if (!Array.isArray(opts.items) || !Array.isArray(opts.values)) { return; }
var lines = opts.items.map(function (itemData) {
var name = itemData.uid;
var item = itemData.v;
var els = opts.values.map(function (data, i) {
var radio = UI.createRadio(name, 'cp-form-'+name+'-'+i,
'', false, { mark: { tabindex:1 } });
$(radio).find('input').data('uid', name);
$(radio).find('input').data('val', data);
return radio;
});
els.unshift(h('div.cp-form-multiradio-item', item));
return h('div.radio-group', {'data-uid':name}, els);
});
var header = opts.values.map(function (v) { return h('span', v); });
header.unshift(h('span'));
lines.unshift(h('div.cp-form-multiradio-header', header));
var tag = h('div.radio-group.cp-form-type-multiradio', lines);
var cursorGetter;
var setCursorGetter = function (f) { cursorGetter = f; };
$(tag).find('input[type="radio"]').on('change', function () {
evOnChange.fire();
});
2021-05-27 15:46:46 +00:00
return {
tag: tag,
getValue: function () {
var res = {};
var l = lines.slice(1);
2021-05-28 12:13:16 +00:00
l.forEach(function (el) {
2021-05-27 15:46:46 +00:00
var $el = $(el);
var uid = $el.attr('data-uid');
2021-05-28 12:13:16 +00:00
$el.find('input').each(function (i, input) {
2021-05-27 15:46:46 +00:00
var $i = $(input);
if (res[uid]) { return; }
if (Util.isChecked($i)) { res[uid] = $i.data('val'); }
});
});
return res;
},
reset: function () { $(tag).find('input').removeAttr('checked'); },
edit: function (cb, tmp) {
var v = Util.clone(opts);
return editOptions(v, setCursorGetter, cb, tmp);
},
getCursor: function () { return cursorGetter(); },
setValue: function (val) {
this.reset();
Object.keys(val || {}).forEach(function (uid) {
$(tag).find('[name="'+uid+'"]').each(function (i, el) {
if ($(el).data('val') !== val[uid]) { return; }
$(el).prop('checked', true);
});
});
}
};
},
printResults: function (answers, uid, form) {
var structure = form[uid];
if (!structure) { return; }
var results = [];
var empty = 0;
var count = {};
Object.keys(answers).forEach(function (author) {
var obj = answers[author];
var answer = obj.msg[uid];
if (!answer || !Object.keys(answer).length) { return empty++; }
//count[answer] = count[answer] || {};
Object.keys(answer).forEach(function (q_uid) {
var c = count[q_uid] = count[q_uid] || {};
var res = answer[q_uid];
if (!res || !res.trim()) { return; }
c[res] = c[res] || 0;
c[res]++;
});
});
Object.keys(count).forEach(function (q_uid) {
2021-06-01 16:37:29 +00:00
var opts = structure.opts || TYPES.multiradio.defaultOpts;
var q = findItem(opts.items, q_uid);
2021-05-27 15:46:46 +00:00
var c = count[q_uid];
var values = Object.keys(c).map(function (res) {
return h('div.cp-form-results-type-radio-data', [
h('span.cp-value', res),
h('span.cp-count', c[res])
]);
});
results.push(h('div.cp-form-results-type-multiradio-data', [
h('span.cp-mr-q', q),
h('span.cp-mr-value', values)
]));
});
results.push(getEmpty(empty));
return h('div.cp-form-results-type-radio', results);
},
2021-06-04 09:14:13 +00:00
icon: h('i.cptools.cptools-form-grid-radio')
2021-05-27 15:46:46 +00:00
},
checkbox: {
defaultOpts: {
max: 3,
values: [1, 2, 3].map(function (i) {
return Messages._getKey('form_defaultOption', [i]);
})
},
get: function (opts, a, n, evOnChange) {
2021-05-27 15:46:46 +00:00
if (!opts) { opts = TYPES.checkbox.defaultOpts; }
if (!Array.isArray(opts.values)) { return; }
var name = Util.uid();
var els = opts.values.map(function (data, i) {
var cbox = UI.createCheckbox('cp-form-'+name+'-'+i,
data, false, { mark: { tabindex:1 } });
$(cbox).find('input').data('val', data);
return cbox;
});
var tag = h('div', [
h('div.cp-form-max-options', Messages._getKey('form_maxOptions', [opts.max])),
h('div.radio-group.cp-form-type-checkbox', els)
]);
var $tag = $(tag);
$tag.find('input').on('change', function () {
var selected = $tag.find('input:checked').length;
if (selected >= opts.max) {
$tag.find('input:not(:checked)').attr('disabled', 'disabled');
} else {
$tag.find('input').removeAttr('disabled');
}
evOnChange.fire();
2021-05-27 15:46:46 +00:00
});
var cursorGetter;
var setCursorGetter = function (f) { cursorGetter = f; };
return {
tag: tag,
getValue: function () {
var res = [];
2021-05-28 12:13:16 +00:00
els.forEach(function (el) {
2021-05-27 15:46:46 +00:00
var $i = $(el).find('input');
if (Util.isChecked($i)) {
res.push($i.data('val'));
}
});
return res;
},
reset: function () { $(tag).find('input').removeAttr('checked'); },
edit: function (cb, tmp) {
var v = Util.clone(opts);
return editOptions(v, setCursorGetter, cb, tmp);
},
getCursor: function () { return cursorGetter(); },
setValue: function (val) {
this.reset();
if (!Array.isArray(val)) { return; }
els.forEach(function (el) {
var $el = $(el).find('input');
if (val.indexOf($el.data('val')) !== -1) {
$el.prop('checked', true);
}
});
}
};
},
printResults: function (answers, uid) {
var results = [];
var empty = 0;
var count = {};
Object.keys(answers).forEach(function (author) {
var obj = answers[author];
var answer = obj.msg[uid];
if (!Array.isArray(answer) || !answer.length) { return empty++; }
answer.forEach(function (val) {
count[val] = count[val] || 0;
count[val]++;
});
});
Object.keys(count).forEach(function (value) {
results.push(h('div.cp-form-results-type-radio-data', [
h('span.cp-value', value),
h('span.cp-count', count[value])
]));
});
results.push(getEmpty(empty));
return h('div.cp-form-results-type-radio', results);
},
2021-06-04 09:14:13 +00:00
icon: h('i.cptools.cptools-form-list-check')
2021-05-27 15:46:46 +00:00
},
multicheck: {
defaultOpts: {
max: 3,
items: [1,2].map(function (i) {
return {
uid: Util.uid(),
v: Messages._getKey('form_defaultItem', [i])
};
}),
values: [1,2,3].map(function (i) {
return Messages._getKey('form_defaultOption', [i]);
})
},
get: function (opts, a, n, evOnChange) {
2021-05-27 15:46:46 +00:00
if (!opts) { opts = TYPES.multicheck.defaultOpts; }
if (!Array.isArray(opts.items) || !Array.isArray(opts.values)) { return; }
var lines = opts.items.map(function (itemData) {
var name = itemData.uid;
var item = itemData.v;
var els = opts.values.map(function (data, i) {
var cbox = UI.createCheckbox('cp-form-'+name+'-'+i,
'', false, { mark: { tabindex:1 } });
$(cbox).find('input').data('uid', name);
$(cbox).find('input').data('val', data);
return cbox;
});
els.unshift(h('div.cp-form-multiradio-item', item));
return h('div.radio-group', {'data-uid':name}, els);
});
lines.forEach(function (l) {
$(l).find('input').on('change', function () {
var selected = $(l).find('input:checked').length;
if (selected >= opts.max) {
$(l).find('input:not(:checked)').attr('disabled', 'disabled');
} else {
$(l).find('input').removeAttr('disabled');
}
evOnChange.fire();
2021-05-27 15:46:46 +00:00
});
});
var header = opts.values.map(function (v) { return h('span', v); });
header.unshift(h('span'));
lines.unshift(h('div.cp-form-multiradio-header', header));
var tag = h('div.radio-group.cp-form-type-multiradio', lines);
var cursorGetter;
var setCursorGetter = function (f) { cursorGetter = f; };
return {
tag: tag,
getValue: function () {
var res = {};
var l = lines.slice(1);
2021-05-28 12:13:16 +00:00
l.forEach(function (el) {
2021-05-27 15:46:46 +00:00
var $el = $(el);
var uid = $el.attr('data-uid');
res[uid] = [];
2021-05-28 12:13:16 +00:00
$el.find('input').each(function (i, input) {
2021-05-27 15:46:46 +00:00
var $i = $(input);
if (Util.isChecked($i)) { res[uid].push($i.data('val')); }
});
});
return res;
},
reset: function () { $(tag).find('input').removeAttr('checked'); },
edit: function (cb, tmp) {
var v = Util.clone(opts);
return editOptions(v, setCursorGetter, cb, tmp);
},
getCursor: function () { return cursorGetter(); },
setValue: function (val) {
this.reset();
Object.keys(val || {}).forEach(function (uid) {
if (!Array.isArray(val[uid])) { return; }
$(tag).find('[data-uid="'+uid+'"] input').each(function (i, el) {
if (val[uid].indexOf($(el).data('val')) === -1) { return; }
$(el).prop('checked', true);
});
});
}
};
},
printResults: function (answers, uid, form) {
var structure = form[uid];
if (!structure) { return; }
var results = [];
var empty = 0;
var count = {};
Object.keys(answers).forEach(function (author) {
var obj = answers[author];
var answer = obj.msg[uid];
if (!answer || !Object.keys(answer).length) { return empty++; }
Object.keys(answer).forEach(function (q_uid) {
var c = count[q_uid] = count[q_uid] || {};
var res = answer[q_uid];
if (!Array.isArray(res) || !res.length) { return; }
res.forEach(function (v) {
c[v] = c[v] || 0;
c[v]++;
});
});
});
Object.keys(count).forEach(function (q_uid) {
var q = findItem(structure.opts.items, q_uid);
var c = count[q_uid];
var values = Object.keys(c).map(function (res) {
return h('div.cp-form-results-type-radio-data', [
h('span.cp-value', res),
h('span.cp-count', c[res])
]);
});
results.push(h('div.cp-form-results-type-multiradio-data', [
h('span.cp-mr-q', q),
h('span.cp-mr-value', values)
]));
});
results.push(getEmpty(empty));
return h('div.cp-form-results-type-radio', results);
},
2021-06-04 09:14:13 +00:00
icon: h('i.cptools.cptools-form-grid-check')
2021-05-27 15:46:46 +00:00
},
2021-05-28 12:04:24 +00:00
poll: {
defaultOpts: {
type: 'text', // Text or Days or Time
values: [1, 2, 3].map(function (i) {
return Messages._getKey('form_defaultOption', [i]);
})
},
get: function (opts, answers, username, evOnChange) {
2021-05-28 12:04:24 +00:00
if (!opts) { opts = TYPES.poll.defaultOpts; }
if (!Array.isArray(opts.values)) { return; }
var lines = makePollTable(answers, opts);
// Add form
2021-05-28 12:13:16 +00:00
var addLine = opts.values.map(function (data) {
2021-05-28 12:04:24 +00:00
var cell = h('div.cp-poll-cell.cp-form-poll-choice', [
h('i.fa.fa-times.cp-no'),
h('i.fa.fa-check.cp-yes'),
h('i.fa.fa-question.cp-maybe'),
]);
var $c = $(cell);
$c.data('option', data);
var val = 0;
$c.attr('data-value', val);
$c.click(function () {
val = (val+1)%3;
$c.attr('data-value', val);
evOnChange.fire();
2021-05-28 12:04:24 +00:00
});
cell._setValue = function (v) {
val = v;
$c.attr('data-value', val);
};
return cell;
});
// Name input
2021-05-31 15:19:14 +00:00
var nameInput = h('input', { value: username || Messages.anonymous });
2021-05-28 12:04:24 +00:00
addLine.unshift(h('div.cp-poll-cell', nameInput));
lines.push(h('div', addLine));
var tag = h('div.cp-form-type-poll', lines);
var $tag = $(tag);
var cursorGetter;
var setCursorGetter = function (f) { cursorGetter = f; };
return {
tag: tag,
getValue: function () {
var res = {};
var name = $(nameInput).val().trim() || Messages.anonymous;
$tag.find('.cp-form-poll-choice').each(function (i, el) {
var $el = $(el);
res[$el.data('option')] = $el.attr('data-value');
});
return {
name: name,
values: res
};
},
reset: function () {
$tag.find('.cp-form-poll-choice').attr('data-value', 0);
},
edit: function (cb, tmp) {
var v = Util.clone(opts);
return editOptions(v, setCursorGetter, cb, tmp);
},
getCursor: function () { return cursorGetter(); },
setValue: function (res) {
this.reset();
if (!res || !res.values || !res.name) { return; }
var val = res.values;
$(nameInput).val(res.name);
$tag.find('.cp-form-poll-choice').each(function (i, el) {
if (!el._setValue) { return; }
var $el = $(el);
el._setValue(val[$el.data('option')] || 0);
});
}
};
},
printResults: function (answers, uid, form) {
var _answers = getBlockAnswers(answers, uid);
var lines = makePollTable(_answers, form[uid].opts);
return h('div.cp-form-type-poll', lines);
},
2021-06-04 09:14:13 +00:00
icon: h('i.cptools.cptools-form-poll')
2021-05-28 12:04:24 +00:00
},
sort: {
defaultOpts: {
values: [1,2].map(function (i) {
return Messages._getKey('form_defaultOption', [i]);
})
},
get: function (opts, a, n, evOnChange) {
if (!opts) { opts = TYPES.radio.defaultOpts; }
if (!Array.isArray(opts.values)) { return; }
var map = {};
var invMap = {};
var els = opts.values.map(function (data, i) {
var uid = Util.uid();
map[uid] = data;
invMap[data] = uid;
var div = h('div.cp-form-type-sort', {'data-id': uid}, [
h('span.cp-form-handle', [
h('i.fa.fa-ellipsis-v'),
h('i.fa.fa-ellipsis-v'),
]),
h('span.cp-form-sort-order', (i+1)),
h('span', data)
]);
$(div).data('val', data);
return div;
});
var tag = h('div.cp-form-type-sort-container', els);
var $tag = $(tag);
var reorder = function () {
$tag.find('.cp-form-type-sort').each(function (i, el) {
$(el).find('.cp-form-sort-order').text(i+1);
});
};
var cursorGetter;
var setCursorGetter = function (f) { cursorGetter = f; };
var sortable = Sortable.create(tag, {
direction: "vertical",
draggable: ".cp-form-type-sort",
forceFallback: true,
store: {
set: function () {
evOnChange.fire();
reorder();
}
}
});
$(tag).find('input[type="radio"]').on('change', function () {
evOnChange.fire();
});
return {
tag: tag,
getValue: function () {
return sortable.toArray().map(function (id) {
return map[id];
});
},
reset: function () {
var toSort = (opts.values).map(function (val) {
return invMap[val];
});
sortable.sort(toSort);
reorder();
},
edit: function (cb, tmp) {
var v = Util.clone(opts);
return editOptions(v, setCursorGetter, cb, tmp);
},
getCursor: function () { return cursorGetter(); },
setValue: function (val) {
var toSort = (val || []).map(function (val) {
return invMap[val];
});
sortable.sort(toSort);
reorder();
}
};
},
printResults: function (answers, uid, form) {
var opts = form[uid].opts || TYPES.radio.defaultOpts;
var l = (opts.values || []).length;
var results = [];
var empty = 0;
var count = {};
Object.keys(answers).forEach(function (author) {
var obj = answers[author];
var answer = obj.msg[uid];
if (!Array.isArray(answer) || !answer.length) { return empty++; }
answer.forEach(function (el, i) {
var score = l - i;
count[el] = (count[el] || 0) + score;
});
});
var sorted = Object.keys(count).sort(function (a, b) {
return count[b] - count[a];
});
sorted.forEach(function (value) {
results.push(h('div.cp-form-results-type-radio-data', [
h('span.cp-value', value),
h('span.cp-count', count[value])
]));
});
results.push(getEmpty(empty));
return h('div.cp-form-results-type-radio', results);
},
icon: h('i.fa.fa-list-ul')
},
2021-05-20 08:43:29 +00:00
};
var renderResults = function (content, answers) {
var $container = $('div.cp-form-creator-results').empty();
2021-06-02 13:37:16 +00:00
var controls = h('div.cp-form-creator-results-controls');
var $controls = $(controls).appendTo($container);
var results = h('div.cp-form-creator-results-content');
var $results = $(results).appendTo($container);
var summary = true;
var form = content.form;
2021-06-02 13:37:16 +00:00
var switchMode = h('button.btn.btn-primary', Messages.form_showIndividual);
$controls.hide().append(switchMode);
2021-06-02 13:37:16 +00:00
var show = function (answers, header) {
var elements = content.order.map(function (uid) {
var block = form[uid];
var type = block.type;
var model = TYPES[type];
if (!model || !model.printResults) { return; }
var print = model.printResults(answers, uid, form);
var q = h('div.cp-form-block-question', block.q || Messages.form_default);
return h('div.cp-form-block', [
h('div.cp-form-block-type', [
TYPES[type].icon.cloneNode(),
h('span', Messages['form_type_'+type])
]),
q,
h('div.cp-form-block-content', print),
]);
});
$results.empty().append(elements);
if (header) { $results.prepend(header); }
};
show(answers);
if (APP.isEditor || APP.isAuditor) { $controls.show(); }
2021-06-02 13:37:16 +00:00
var $s = $(switchMode).click(function () {
$results.empty();
if (!summary) {
$s.text(Messages.form_showIndividual);
summary = true;
show(answers);
return;
}
summary = false;
$s.text(Messages.form_showSummary);
var origin, priv;
if (APP.common) {
var metadataMgr = APP.common.getMetadataMgr();
priv = metadataMgr.getPrivateData();
origin = priv.origin;
}
var getHref = function (hash) {
if (APP.common) {
return origin + Hash.hashToHref(hash, 'profile');
}
return '#';
};
var els = Object.keys(answers).map(function (curve) {
var obj = answers[curve];
var answer = obj.msg;
var date = new Date(obj.time).toLocaleString();
var text, warning, badge;
if (!answer._userdata || !answer._userdata.name) {
text = Messages._getKey('form_answerAnonymous', [date]);
} else {
var ud = answer._userdata;
var user;
if (ud.profile) {
if (priv && priv.friends[curve]) {
badge = h('span.cp-form-friend', [
h('i.fa.fa-address-book'),
Messages._getKey('isContact', [ud.name || Messages.anonymous])
]);
}
user = h('a', {
href: getHref(ud.profile) // Only used visually
}, Util.fixHTML(ud.name || Messages.anonymous));
2021-06-03 15:29:03 +00:00
if (curve !== ud.curvePublic) {
2021-06-02 13:37:16 +00:00
warning = h('span.cp-form-warning', Messages.form_answerWarning);
}
} else {
user = h('b', Util.fixHTML(ud.name || Messages.anonymous));
}
text = Messages._getKey('form_answerName', [user.outerHTML, date]);
}
var span = UI.setHTML(h('span'), text);
var viewButton = h('button.btn.btn-secondary.small', Messages.form_viewButton);
var div = h('div.cp-form-individual', [span, viewButton, warning, badge]);
$(viewButton).click(function () {
var res = {};
res[curve] = obj;
var back = h('button.btn.btn-secondary.small', Messages.form_backButton);
$(back).click(function () {
summary = true;
$s.click();
});
var header = h('div.cp-form-individual', [
span.cloneNode(true),
back
]);
show(res, header);
});
$(div).find('a').click(function (e) {
e.preventDefault();
APP.common.openURL(Hash.hashToHref(ud.profile, 'profile'));
});
return div;
});
$results.append(els);
});
};
2021-06-03 15:29:03 +00:00
var addResultsButton = function (framework, content) {
var $res = $(h('button.cp-toolbar-appmenu', [
h('i.fa.fa-bar-chart'),
h('span.cp-button-name', Messages.form_results)
]));
$res.click(function () {
$res.attr('disabled', 'disabled');
var sframeChan = framework._.sfCommon.getSframeChannel();
sframeChan.query("Q_FORM_FETCH_ANSWERS", content.answers, function (err, obj) {
var answers = obj && obj.results;
if (answers) { APP.answers = answers; }
$res.removeAttr('disabled');
$('body').addClass('cp-app-form-results');
renderResults(content, answers);
$res.remove();
var $editor = $(h('button.cp-toolbar-appmenu', [
h('i.fa.fa-pencil'),
h('span.cp-button-name', APP.isEditor ? Messages.form_editor : Messages.form_form)
]));
$editor.click(function () {
$('body').removeClass('cp-app-form-results');
$editor.remove();
addResultsButton(framework, content);
});
framework._.toolbar.$bottomL.append($editor);
});
});
framework._.toolbar.$bottomL.append($res);
};
2021-05-25 13:15:51 +00:00
var getFormResults = function () {
if (!Array.isArray(APP.formBlocks)) { return; }
var results = {};
APP.formBlocks.forEach(function (data) {
2021-05-31 16:23:25 +00:00
if (!data.getValue) { return; }
2021-05-25 13:15:51 +00:00
results[data.uid] = data.getValue();
});
return results;
};
2021-05-21 11:39:33 +00:00
var makeFormControls = function (framework, content, update) {
2021-05-31 15:19:14 +00:00
var loggedIn = framework._.sfCommon.isLoggedIn();
2021-06-02 13:37:16 +00:00
var metadataMgr = framework._.cpNfInner.metadataMgr;
2021-05-31 15:19:14 +00:00
if (!loggedIn && !content.answers.anonymous) { return; }
var cbox;
2021-06-02 13:37:16 +00:00
cbox = UI.createCheckbox('cp-form-anonymous',
2021-06-02 13:40:07 +00:00
Messages.form_anonymousBox, true, { mark: { tabindex:1 } });
2021-05-31 15:19:14 +00:00
if (loggedIn) {
2021-06-01 16:37:29 +00:00
if (!content.answers.anonymous || APP.cantAnon) {
2021-06-02 13:40:07 +00:00
$(cbox).hide().find('input').attr('disabled', 'disabled').prop('checked', false);
2021-05-31 15:19:14 +00:00
}
}
2021-05-26 15:02:34 +00:00
var send = h('button.cp-open.btn.btn-primary', update ? Messages.form_update : Messages.form_submit);
var reset = h('button.cp-open.btn.btn-danger-alt', Messages.form_reset);
2021-05-20 11:54:20 +00:00
$(reset).click(function () {
if (!Array.isArray(APP.formBlocks)) { return; }
APP.formBlocks.forEach(function (data) {
if (typeof(data.reset) === "function") { data.reset(); }
});
});
var $send = $(send).click(function () {
$send.attr('disabled', 'disabled');
2021-05-25 13:15:51 +00:00
var results = getFormResults();
if (!results) { return; }
2021-05-31 15:19:14 +00:00
2021-06-02 13:37:16 +00:00
var user = metadataMgr.getUserData();
if (!Util.isChecked($(cbox).find('input'))) {
results._userdata = loggedIn ? {
avatar: user.avatar,
name: user.name,
notifications: user.notifications,
curvePublic: user.curvePublic,
profile: user.profile
} : { name: user.name };
}
2021-05-20 11:54:20 +00:00
var sframeChan = framework._.sfCommon.getSframeChannel();
sframeChan.query('Q_FORM_SUBMIT', {
mailbox: content.answers,
2021-05-31 15:19:14 +00:00
results: results,
anonymous: !loggedIn || Util.isChecked($(cbox).find('input'))
2021-05-20 11:54:20 +00:00
}, function (err, data) {
2021-05-21 11:39:33 +00:00
$send.attr('disabled', 'disabled');
2021-05-20 11:54:20 +00:00
if (err || (data && data.error)) {
if (data.error === "EANSWERED") {
return void UI.warn(Messages.form_answered);
}
2021-05-20 11:54:20 +00:00
console.error(err || data.error);
return void UI.warn(Messages.error);
}
2021-06-03 15:29:03 +00:00
if (!update) {
// Add results button
addResultsButton(framework, content);
}
2021-05-27 15:46:46 +00:00
$send.removeAttr('disabled');
2021-05-20 11:54:20 +00:00
UI.alert(Messages.form_sent);
2021-05-21 11:39:33 +00:00
$send.text(Messages.form_update);
2021-05-20 11:54:20 +00:00
});
});
2021-05-26 15:02:34 +00:00
if (APP.isClosed) {
send = undefined;
reset = undefined;
}
2021-05-31 15:19:14 +00:00
return h('div.cp-form-send-container', [
cbox ? h('div', cbox) : undefined,
2021-06-03 15:29:03 +00:00
send, reset
2021-05-31 15:19:14 +00:00
]);
2021-05-20 08:43:29 +00:00
};
2021-05-25 13:15:51 +00:00
var updateForm = function (framework, content, editable, answers, temp) {
2021-05-20 08:43:29 +00:00
var $container = $('div.cp-form-creator-content');
2021-05-25 13:15:51 +00:00
if (!$container.length) { return; } // Not ready
2021-05-20 08:43:29 +00:00
var form = content.form;
2021-05-20 11:54:20 +00:00
APP.formBlocks = [];
var evOnChange = Util.mkEvent();
if (!APP.isEditor) {
var _answers = Util.clone(answers || {});
delete _answers._proof;
delete _answers._userdata;
evOnChange.reg(function () {
var results = getFormResults();
if (!answers || Sortify(_answers) !== Sortify(results)) {
window.onbeforeunload = function () {
return true;
};
} else {
window.onbeforeunload = undefined;
}
});
}
2021-06-02 16:50:36 +00:00
var getFormCreator = function (uid) {
2021-06-03 15:29:03 +00:00
if (!APP.isEditor) { return; }
2021-06-02 16:50:36 +00:00
var full = !uid;
var idx = content.order.indexOf(uid);
var addControl = function (type) {
var btn = h('button.btn.btn-default', {
2021-06-02 16:50:36 +00:00
title: full ? undefined : Messages['form_type_'+type]
}, [
(TYPES[type] || STATIC_TYPES[type]).icon.cloneNode(),
full ? h('span', Messages['form_type_'+type]) : undefined
]);
$(btn).click(function () {
var uid = Util.uid();
content.form[uid] = {
//q: Messages.form_default,
//opts: opts
type: type,
};
if (full) {
content.order.push(uid);
} else {
content.order.splice(idx, 0, uid);
}
framework.localChange();
updateForm(framework, content, true);
});
return btn;
};
var controls = Object.keys(TYPES).map(addControl);
var staticControls = Object.keys(STATIC_TYPES).map(addControl);
var buttons = h('div.cp-form-creator-control-inline', [
h('div.cp-form-creator-types', controls),
h('div.cp-form-creator-types', staticControls)
]);
2021-06-04 13:38:45 +00:00
var add = h('div', [h('i.fa.fa-plus')]);
2021-06-02 16:50:36 +00:00
if (!full) {
add = h('button.btn.cp-form-creator-inline-add', {
title: Messages.tag_add
}, [
h('i.fa.fa-plus.add-open'),
h('i.fa.fa-times.add-close')
]);
var $b = $(buttons).hide();
$(add).click(function () {
$b.toggle();
$(add).toggleClass('displayed');
});
}
2021-06-03 15:29:03 +00:00
var inlineCls = full ? '-full' : '-inline';
2021-06-02 16:50:36 +00:00
return h('div.cp-form-creator-add'+inlineCls, [
h('div', add),
buttons
]);
};
var updateAddInline = function () {
$container.find('.cp-form-creator-add-inline').remove();
$container.find('.cp-form-block').each(function (i, el) {
var $el = $(el);
var uid = $el.attr('data-id');
$el.before(getFormCreator(uid));
});
};
var elements = [];
2021-06-03 15:29:03 +00:00
content.order.forEach(function (uid) {
2021-05-20 08:43:29 +00:00
var block = form[uid];
var type = block.type;
2021-05-31 16:23:25 +00:00
var model = TYPES[type] || STATIC_TYPES[type];
var isStatic = Boolean(STATIC_TYPES[type]);
2021-05-20 08:43:29 +00:00
if (!model) { return; }
2021-05-20 11:54:20 +00:00
2021-05-28 12:04:24 +00:00
var _answers, name;
if (type === 'poll') {
var metadataMgr = framework._.cpNfInner.metadataMgr;
var user = metadataMgr.getUserData();
// If we are a participant, our results shouldn't be in the table but in the
// editable part: remove them from _answers
_answers = getBlockAnswers(APP.answers, uid, !editable && user.curvePublic);
name = user.name;
}
var data = model.get(block.opts, _answers, name, evOnChange);
2021-05-27 15:46:46 +00:00
if (!data) { return; }
2021-05-20 11:54:20 +00:00
data.uid = uid;
2021-05-31 16:23:25 +00:00
if (answers && answers[uid] && data.setValue) { data.setValue(answers[uid]); }
2021-05-20 11:54:20 +00:00
2021-06-01 15:45:04 +00:00
if (data.pageBreak && !editable) {
2021-06-02 16:50:36 +00:00
elements.push(data);
return;
2021-06-01 15:45:04 +00:00
}
2021-06-03 15:29:03 +00:00
var dragHandle;
2021-05-20 08:43:29 +00:00
var q = h('div.cp-form-block-question', block.q || Messages.form_default);
2021-05-21 15:40:41 +00:00
var editButtons, editContainer;
2021-05-20 11:54:20 +00:00
APP.formBlocks.push(data);
2021-05-20 08:43:29 +00:00
if (editable) {
2021-06-03 15:29:03 +00:00
// Drag handle
dragHandle = h('span.cp-form-block-drag-handle', [
h('i.fa.fa-ellipsis-h'),
h('i.fa.fa-ellipsis-h'),
]);
2021-05-20 08:43:29 +00:00
2021-06-03 15:29:03 +00:00
// Question
2021-05-20 08:43:29 +00:00
var inputQ = h('input', {
value: block.q || Messages.form_default
});
var $inputQ = $(inputQ);
2021-05-21 15:40:41 +00:00
2021-06-03 15:29:03 +00:00
var saving = false;
var cancel = false;
var onSaveQ = function (e) {
if (cancel) {
cancel = false;
2021-05-21 15:40:41 +00:00
return;
}
2021-05-20 08:43:29 +00:00
var v = $inputQ.val();
2021-05-21 15:40:41 +00:00
if (!v || !v.trim()) { return void UI.warn(Messages.error); }
2021-06-03 15:44:59 +00:00
// Don't save if no change
if (v.trim() === block.q) {
$(q).removeClass('editing');
if (!e) { $inputQ.blur(); }
return;
}
2021-06-03 15:29:03 +00:00
if (saving && !e) { return; } // Prevent spam Enter
2021-05-20 08:43:29 +00:00
block.q = v.trim();
framework.localChange();
2021-06-03 15:29:03 +00:00
saving = true;
2021-05-20 08:43:29 +00:00
framework._.cpNfInner.chainpad.onSettle(function () {
2021-06-03 15:29:03 +00:00
saving = false;
2021-05-21 15:40:41 +00:00
$(q).removeClass('editing');
2021-06-03 15:29:03 +00:00
if (!e) { $inputQ.blur(); }
2021-05-20 08:43:29 +00:00
UI.log(Messages.saved);
});
2021-06-03 15:29:03 +00:00
};
var onCancelQ = function () {
2021-05-21 15:40:41 +00:00
$inputQ.val(block.q || Messages.form_default);
2021-06-03 15:29:03 +00:00
cancel = true;
$inputQ.blur();
2021-05-21 15:40:41 +00:00
$(q).removeClass('editing');
2021-05-20 08:43:29 +00:00
};
$inputQ.keydown(function (e) {
2021-06-03 15:29:03 +00:00
if (e.which === 13) { return void onSaveQ(); }
2021-05-21 15:40:41 +00:00
if (e.which === 27) { return void onCancelQ(); }
});
$inputQ.focus(function () {
$(q).addClass('editing');
});
2021-06-03 15:29:03 +00:00
$inputQ.blur(onSaveQ);
q = h('div.cp-form-input-block', [inputQ]);
2021-05-21 15:40:41 +00:00
// Delete question
2021-06-03 15:29:03 +00:00
var edit = h('span');
var del = h('button.btn.btn-danger-alt', [
2021-05-21 15:40:41 +00:00
h('i.fa.fa-trash-o'),
h('span', Messages.form_delete)
]);
UI.confirmButton(del, {
classes: 'btn-danger',
new: true
}, function () {
delete content.form[uid];
var idx = content.order.indexOf(uid);
content.order.splice(idx, 1);
$('.cp-form-block[data-id="'+uid+'"]').remove();
framework.localChange();
2021-06-02 16:50:36 +00:00
updateAddInline();
2021-05-20 08:43:29 +00:00
});
// Values
if (data.edit) {
2021-06-03 15:29:03 +00:00
edit = h('button.btn.btn-default.cp-form-edit-button', [
2021-05-20 08:43:29 +00:00
h('i.fa.fa-pencil'),
h('span', Messages.form_editBlock)
]);
editContainer = h('div');
var onSave = function (newOpts) {
2021-05-25 13:15:51 +00:00
data.editing = false;
2021-05-20 08:43:29 +00:00
if (!newOpts) { // Cancel edit
$(editContainer).empty();
2021-05-21 15:40:41 +00:00
$(editButtons).show();
2021-05-20 08:43:29 +00:00
$(data.tag).show();
return;
}
$(editContainer).empty();
block.opts = newOpts;
2021-05-20 11:54:20 +00:00
framework.localChange();
2021-05-20 08:43:29 +00:00
var $oldTag = $(data.tag);
framework._.cpNfInner.chainpad.onSettle(function () {
2021-05-21 15:40:41 +00:00
$(editButtons).show();
2021-05-20 08:43:29 +00:00
UI.log(Messages.saved);
2021-05-28 12:04:24 +00:00
var _answers = getBlockAnswers(APP.answers, uid);
data = model.get(newOpts, _answers, null, evOnChange);
2021-05-27 15:46:46 +00:00
if (!data) { data = {}; }
2021-05-20 08:43:29 +00:00
$oldTag.before(data.tag).remove();
});
};
2021-05-25 13:15:51 +00:00
var onEdit = function (tmp) {
data.editing = true;
2021-05-20 08:43:29 +00:00
$(data.tag).hide();
2021-06-03 15:44:59 +00:00
$(editContainer).append(data.edit(onSave, tmp, framework));
2021-05-21 15:40:41 +00:00
$(editButtons).hide();
2021-05-25 13:15:51 +00:00
};
$(edit).click(function () {
onEdit();
2021-05-20 08:43:29 +00:00
});
2021-05-25 13:15:51 +00:00
// If we were editing this field, recover our unsaved changes
if (temp && temp[uid]) {
setTimeout(function () {
onEdit(temp[uid]);
});
}
2021-05-20 08:43:29 +00:00
}
2021-05-21 15:40:41 +00:00
editButtons = h('div.cp-form-edit-buttons-container', [
edit, del
]);
2021-05-20 08:43:29 +00:00
}
2021-05-21 15:40:41 +00:00
var editableCls = editable ? ".editable" : "";
2021-06-02 16:50:36 +00:00
elements.push(h('div.cp-form-block'+editableCls, {
2021-05-21 15:40:41 +00:00
'data-id':uid
}, [
2021-06-03 15:29:03 +00:00
APP.isEditor ? dragHandle : undefined,
2021-05-31 16:23:25 +00:00
isStatic ? undefined : q,
2021-05-20 08:43:29 +00:00
h('div.cp-form-block-content', [
data.tag,
2021-05-21 15:40:41 +00:00
editButtons
2021-05-20 08:43:29 +00:00
]),
editContainer
2021-06-02 16:50:36 +00:00
]));
2021-05-20 08:43:29 +00:00
});
2021-06-02 16:50:36 +00:00
if (APP.isEditor) {
elements.push(getFormCreator());
}
2021-06-01 15:45:04 +00:00
var _content = elements;
if (!editable) {
_content = [];
var div = h('div.cp-form-page');
var pages = 1;
var wasPage = false;
2021-06-03 15:29:03 +00:00
elements.forEach(function (obj, i) {
2021-06-01 15:45:04 +00:00
if (obj && obj.pageBreak) {
2021-06-03 15:29:03 +00:00
if (i === 0) { return; } // Can't start with a page break
if (i === (elements.length - 1)) { return; } // Can't end with a page break
2021-06-01 15:45:04 +00:00
if (wasPage) { return; } // Prevent double page break
_content.push(div);
pages++;
div = h('div.cp-form-page');
wasPage = true;
return;
}
wasPage = false;
$(div).append(obj);
});
_content.push(div);
if (pages > 1) {
var pageContainer = h('div.cp-form-page-container');
var $page = $(pageContainer);
_content.push(pageContainer);
var refreshPage = function (current) {
$page.empty();
if (!current || current < 1) { current = 1; }
if (current > pages) { current = pages; }
var left = h('button.btn.btn-secondary.small.cp-prev', [
h('i.fa.fa-chevron-left'),
h('span', Messages.form_page_prev)
]);
var state = h('span', Messages._getKey('form_page', [current, pages]));
var right = h('button.btn.btn-secondary.small.cp-next', [
h('span', Messages.form_page_next),
h('i.fa.fa-chevron-right'),
]);
$(left).click(function () { refreshPage(current - 1); });
$(right).click(function () { refreshPage(current + 1); });
$page.append([left, state, right]);
$container.find('.cp-form-page').hide();
$($container.find('.cp-form-page').get(current-1)).show();
if (current !== pages) {
$container.find('.cp-form-send-container').hide();
} else {
$container.find('.cp-form-send-container').show();
}
};
setTimeout(refreshPage);
}
2021-06-01 15:45:04 +00:00
}
$container.empty().append(_content);
2021-06-02 16:50:36 +00:00
updateAddInline();
2021-05-21 15:40:41 +00:00
if (editable) {
Sortable.create($container[0], {
direction: "vertical",
filter: "input, button, .CodeMirror, .cp-form-type-sort",
2021-05-21 15:40:41 +00:00
preventOnFilter: false,
2021-06-03 15:29:03 +00:00
draggable: ".cp-form-block",
forceFallback: true,
2021-06-03 15:44:59 +00:00
fallbackTolerance: 5,
2021-06-03 15:29:03 +00:00
onStart: function () {
$container.find('.cp-form-creator-add-inline').remove();
},
2021-05-21 15:40:41 +00:00
store: {
set: function (s) {
content.order = s.toArray();
framework.localChange();
2021-06-02 16:50:36 +00:00
updateAddInline();
2021-05-21 15:40:41 +00:00
}
}
});
return;
}
// In view mode, add "Submit" and "reset" buttons
2021-05-21 11:39:33 +00:00
$container.append(makeFormControls(framework, content, Boolean(answers)));
};
2021-05-25 13:15:51 +00:00
var getTempFields = function () {
if (!Array.isArray(APP.formBlocks)) { return; }
var temp = {};
APP.formBlocks.forEach(function (data) {
if (data.editing) {
var cursor = data.getCursor && data.getCursor();
temp[data.uid] = cursor;
}
});
return temp;
};
2021-05-20 08:43:29 +00:00
var andThen = function (framework) {
framework.start();
2021-05-31 15:19:14 +00:00
var evOnChange = Util.mkEvent();
2021-05-20 08:43:29 +00:00
var content = {};
2021-05-31 16:23:25 +00:00
APP.common = framework._.sfCommon;
2021-05-20 11:54:20 +00:00
var sframeChan = framework._.sfCommon.getSframeChannel();
var metadataMgr = framework._.cpNfInner.metadataMgr;
2021-05-28 12:04:24 +00:00
var user = metadataMgr.getUserData();
2021-05-20 11:54:20 +00:00
var priv = metadataMgr.getPrivateData();
APP.isEditor = Boolean(priv.form_public);
2021-05-21 11:39:33 +00:00
var $body = $('body');
2021-05-26 15:02:34 +00:00
var $toolbarContainer = $('#cp-toolbar');
var helpMenu = framework._.sfCommon.createHelpMenu(['text', 'pad']);
$toolbarContainer.after(helpMenu.menu);
2021-05-21 11:39:33 +00:00
var makeFormSettings = function () {
2021-05-31 15:19:14 +00:00
// Private / public status
var resultsType = h('div.cp-form-results-type-container');
var $results = $(resultsType);
var refreshPublic = function () {
$results.empty();
2021-06-03 15:29:03 +00:00
var makePublic = h('button.btn.btn-secondary', Messages.form_makePublic);
var makePublicDiv = h('div', makePublic);
if (content.answers.privateKey) { makePublicDiv = undefined; }
2021-05-31 15:19:14 +00:00
var publicText = content.answers.privateKey ? Messages.form_isPublic : Messages.form_isPrivate;
$results.append(h('span.cp-form-results-type', publicText));
2021-06-03 15:29:03 +00:00
$results.append(makePublicDiv);
2021-05-31 15:19:14 +00:00
var $makePublic = $(makePublic).click(function () {
UI.confirm(Messages.form_makePublicWarning, function (yes) {
if (!yes) { return; }
$makePublic.attr('disabled', 'disabled');
var priv = metadataMgr.getPrivateData();
2021-05-31 15:19:14 +00:00
content.answers.privateKey = priv.form_private;
framework.localChange();
framework._.cpNfInner.chainpad.onSettle(function () {
UI.log(Messages.saved);
refreshPublic();
});
});
});
};
refreshPublic();
// Allow anonymous answers
var privacyContainer = h('div.cp-form-privacy-container');
var $privacy = $(privacyContainer);
var refreshPrivacy = function () {
$privacy.empty();
var anonymous = content.answers.anonymous;
2021-06-03 15:29:03 +00:00
var radioOn = UI.createRadio('cp-form-privacy', 'cp-form-privacy-on',
Messages.form_anonymous_on, Boolean(anonymous), {
input: { value: 1 },
mark: { tabindex:1 }
});
var radioOff = UI.createRadio('cp-form-privacy', 'cp-form-privacy-off',
Messages.form_anonymous_off, !anonymous, {
input: { value: 0 },
mark: { tabindex:1 }
});
var radioContainer = h('div.cp-form-privacy-radio', [radioOn, radioOff]);
$(radioContainer).find('input[type="radio"]').on('change', function() {
var val = $('input:radio[name="cp-form-privacy"]:checked').val();
val = Number(val) || 0;
content.answers.anonymous = Boolean(val);
framework.localChange();
framework._.cpNfInner.chainpad.onSettle(function () {
UI.log(Messages.saved);
});
});
2021-06-03 15:29:03 +00:00
$privacy.append(h('div.cp-form-status', Messages.form_anonymous));
$privacy.append(h('div.cp-form-actions', radioContainer));
2021-05-31 15:19:14 +00:00
};
refreshPrivacy();
2021-05-26 15:02:34 +00:00
// End date / Closed state
var endDateContainer = h('div.cp-form-status-container');
var $endDate = $(endDateContainer);
var refreshEndDate = function () {
$endDate.empty();
var endDate = content.answers.endDate;
var date = new Date(endDate).toLocaleString();
var now = +new Date();
var text = Messages.form_isOpen;
var buttonTxt = Messages.form_setEnd;
if (endDate <= now) {
text = Messages._getKey('form_isClosed', [date]);
buttonTxt = Messages.form_open;
} else if (endDate > now) {
text = Messages._getKey('form_willClose', [date]);
buttonTxt = Messages.form_removeEnd;
}
var button = h('button.btn.btn-secondary', buttonTxt);
var $button = $(button).click(function () {
$button.attr('disabled', 'disabled');
// If there is an end date, remove it
if (endDate) {
delete content.answers.endDate;
framework.localChange();
refreshEndDate();
return;
}
// Otherwise add it
var datePicker = h('input');
var picker = Flatpickr(datePicker, {
enableTime: true,
time_24hr: is24h,
dateFormat: dateFormat,
minDate: new Date()
});
var save = h('button.btn.btn-primary', Messages.settings_save);
$(save).click(function () {
var d = picker.parseDate(datePicker.value);
content.answers.endDate = +d;
framework.localChange();
refreshEndDate();
});
var confirmContent = h('div', [
h('div', Messages.form_setEnd),
h('div.cp-form-input-block', [datePicker, save]),
]);
$button.after(confirmContent);
$button.remove();
2021-06-01 16:37:29 +00:00
picker.open();
2021-05-26 15:02:34 +00:00
});
$endDate.append(h('div.cp-form-status', text));
$endDate.append(h('div.cp-form-actions', button));
};
refreshEndDate();
2021-05-31 15:19:14 +00:00
evOnChange.reg(refreshPublic);
evOnChange.reg(refreshPrivacy);
evOnChange.reg(refreshEndDate);
2021-05-21 11:39:33 +00:00
return [
2021-05-26 15:02:34 +00:00
endDateContainer,
2021-05-31 15:19:14 +00:00
privacyContainer,
resultsType,
2021-05-21 11:39:33 +00:00
];
};
2021-05-20 08:43:29 +00:00
2021-05-21 15:40:41 +00:00
var checkIntegrity = function (getter) {
2021-05-26 12:54:56 +00:00
if (!content.order || !content.form) { return; }
2021-05-21 15:40:41 +00:00
var changed = false;
content.order.forEach(function (uid) {
if (!content.form[uid]) {
var idx = content.order.indexOf(uid);
content.order.splice(idx, 1);
changed = true;
}
});
Object.keys(content.form).forEach(function (uid) {
var idx = content.order.indexOf(uid);
if (idx === -1) {
changed = true;
content.order.push(uid);
}
});
if (!getter && changed) { framework.localChange(); }
};
2021-05-20 08:43:29 +00:00
var makeFormCreator = function () {
2021-05-20 11:54:20 +00:00
var controlContainer;
2021-06-03 15:29:03 +00:00
var fillerContainer;
2021-05-20 11:54:20 +00:00
if (APP.isEditor) {
2021-05-21 11:39:33 +00:00
var settings = makeFormSettings();
controlContainer = h('div.cp-form-creator-control', [
h('div.cp-form-creator-settings', settings),
]);
2021-06-03 15:29:03 +00:00
fillerContainer = h('div.cp-form-filler-container');
2021-05-20 11:54:20 +00:00
}
2021-05-20 08:43:29 +00:00
var contentContainer = h('div.cp-form-creator-content');
2021-05-21 11:39:33 +00:00
var resultsContainer = h('div.cp-form-creator-results');
2021-05-20 08:43:29 +00:00
var div = h('div.cp-form-creator-container', [
controlContainer,
contentContainer,
2021-06-03 15:29:03 +00:00
resultsContainer,
fillerContainer
2021-05-20 08:43:29 +00:00
]);
return div;
};
2021-05-26 15:02:34 +00:00
var endDateEl = h('div.alert.alert-warning.cp-burn-after-reading');
var endDate;
var endDateTo;
var refreshEndDateBanner = function (force) {
2021-05-27 15:46:46 +00:00
if (APP.isEditor) { return; }
2021-05-26 15:02:34 +00:00
var _endDate = content.answers.endDate;
if (_endDate === endDate && !force) { return; }
endDate = _endDate;
var date = new Date(endDate).toLocaleString();
var text = Messages._getKey('form_isClosed', [date]);
if (endDate > +new Date()) {
text = Messages._getKey('form_willClose', [date]);
}
if ($('.cp-help-container').length && endDate) {
$(endDateEl).text(text);
$('.cp-help-container').before(endDateEl);
} else {
$(endDateEl).remove();
}
APP.isClosed = endDate && endDate < (+new Date());
clearTimeout(endDateTo);
if (!APP.isClosed && endDate) {
setTimeout(function () {
refreshEndDateBanner(true);
$('.cp-form-send-container').find('.cp-open').remove();
},(endDate - +new Date() + 100));
}
};
2021-05-28 12:13:16 +00:00
framework.onReady(function () {
2021-05-20 08:43:29 +00:00
var priv = metadataMgr.getPrivateData();
2021-05-20 08:43:29 +00:00
if (APP.isEditor) {
if (!content.form) {
content.form = {};
framework.localChange();
}
2021-05-21 15:40:41 +00:00
if (!content.order) {
content.order = [];
framework.localChange();
}
2021-05-20 14:20:15 +00:00
if (!content.answers || !content.answers.channel || !content.answers.publicKey || !content.answers.validateKey) {
2021-05-20 08:43:29 +00:00
content.answers = {
channel: Hash.createChannelId(),
2021-05-20 14:20:15 +00:00
publicKey: priv.form_public,
validateKey: priv.form_answerValidateKey
2021-05-20 08:43:29 +00:00
};
framework.localChange();
}
}
2021-05-26 12:54:56 +00:00
sframeChan.event('EV_FORM_PIN', {channel: content.answers.channel});
2021-05-26 10:03:32 +00:00
var $container = $('#cp-app-form-container');
$container.append(makeFormCreator());
2021-05-20 14:20:15 +00:00
if (!content.answers || !content.answers.channel || !content.answers.publicKey || !content.answers.validateKey) {
2021-05-20 08:43:29 +00:00
return void UI.errorLoadingScreen(Messages.form_invalid);
}
var getResults = function (key) {
sframeChan.query("Q_FORM_FETCH_ANSWERS", {
channel: content.answers.channel,
validateKey: content.answers.validateKey,
publicKey: content.answers.publicKey,
privateKey: key
}, function (err, obj) {
2021-05-31 15:19:14 +00:00
var answers = obj && obj.results;
if (answers) { APP.answers = answers; }
$body.addClass('cp-app-form-results');
2021-05-31 15:19:14 +00:00
renderResults(content, answers);
});
};
if (priv.form_auditorKey) {
APP.isAuditor = true;
getResults(priv.form_auditorKey);
return;
}
2021-05-20 08:43:29 +00:00
if (APP.isEditor) {
2021-06-03 15:29:03 +00:00
addResultsButton(framework, content);
2021-05-20 08:43:29 +00:00
sframeChan.query("Q_FORM_FETCH_ANSWERS", {
channel: content.answers.channel,
2021-05-21 11:39:33 +00:00
validateKey: content.answers.validateKey,
2021-05-20 08:43:29 +00:00
publicKey: content.answers.publicKey
2021-05-21 11:39:33 +00:00
}, function (err, obj) {
2021-05-31 15:19:14 +00:00
var answers = obj && obj.results;
if (answers) { APP.answers = answers; }
2021-05-21 15:40:41 +00:00
checkIntegrity(false);
2021-05-20 08:43:29 +00:00
updateForm(framework, content, true);
});
return;
}
2021-05-20 14:20:15 +00:00
2021-05-26 15:02:34 +00:00
refreshEndDateBanner();
2021-05-31 15:19:14 +00:00
var loggedIn = framework._.sfCommon.isLoggedIn();
if (!loggedIn && !content.answers.anonymous) {
UI.alert(Messages.form_anonymous_blocked);
}
2021-05-28 12:04:24 +00:00
// If the results are public and there is at least one doodle, fetch the results now
if (content.answers.privateKey && Object.keys(content.form).some(function (uid) {
return content.form[uid].type === "poll";
})) {
sframeChan.query("Q_FORM_FETCH_ANSWERS", {
channel: content.answers.channel,
validateKey: content.answers.validateKey,
publicKey: content.answers.publicKey,
privateKey: content.answers.privateKey,
}, function (err, obj) {
2021-05-31 15:19:14 +00:00
var answers = obj && obj.results;
if (answers) { APP.answers = answers; }
if (obj && obj.noDriveAnswered) {
// No drive mode already answered: can't answer again
if (answers) {
$body.addClass('cp-app-form-results');
renderResults(content, answers);
} else {
return void UI.errorLoadingScreen(Messages.form_answered);
}
return;
}
2021-05-28 12:04:24 +00:00
checkIntegrity(false);
var myAnswers;
2021-05-31 16:23:25 +00:00
var curve1 = user.curvePublic;
2021-05-31 15:19:14 +00:00
var curve2 = obj && obj.myKey; // Anonymous answer key
if (answers) {
var myAnswersObj = answers[curve1] || answers[curve2] || undefined;
if (myAnswersObj) {
myAnswers = myAnswersObj.msg;
}
2021-05-28 12:04:24 +00:00
}
2021-06-01 16:37:29 +00:00
// If we have a non-anon answer, we can't answer anonymously later
if (answers[curve1]) { APP.cantAnon = true; }
2021-06-03 15:29:03 +00:00
// Add results button
if (myAnswers) { addResultsButton(framework, content); }
2021-05-28 12:04:24 +00:00
updateForm(framework, content, false, myAnswers);
});
return;
}
2021-05-26 15:02:34 +00:00
2021-05-20 14:20:15 +00:00
sframeChan.query("Q_FETCH_MY_ANSWERS", {
channel: content.answers.channel,
validateKey: content.answers.validateKey,
publicKey: content.answers.publicKey
}, function (err, obj) {
if (obj && obj.error) {
if (obj.error === "EANSWERED") {
// No drive mode already answered: can't answer again
if (content.answers.privateKey) {
return void getResults(content.answers.privateKey);
}
// Here, we know results are private so we can use an error screen
return void UI.errorLoadingScreen(Messages.form_answered);
}
2021-05-20 14:20:15 +00:00
UI.warn(Messages.form_cantFindAnswers);
}
var answers;
2021-06-01 16:37:29 +00:00
if (obj && !obj.error) {
answers = obj;
// If we have a non-anon answer, we can't answer anonymously later
if (!obj._isAnon) { APP.cantAnon = true; }
}
2021-05-21 15:40:41 +00:00
checkIntegrity(false);
2021-05-20 14:20:15 +00:00
updateForm(framework, content, false, answers);
});
2021-05-20 08:43:29 +00:00
});
framework.onContentUpdate(function (newContent) {
content = newContent;
2021-05-31 15:19:14 +00:00
evOnChange.fire();
2021-05-26 15:02:34 +00:00
refreshEndDateBanner();
2021-05-25 13:15:51 +00:00
var answers, temp;
if (!APP.isEditor) { answers = getFormResults(); }
else { temp = getTempFields(); }
updateForm(framework, content, APP.isEditor, answers, temp);
2021-05-20 08:43:29 +00:00
});
framework.setContentGetter(function () {
2021-05-21 15:40:41 +00:00
checkIntegrity(true);
2021-05-20 08:43:29 +00:00
return content;
});
};
Framework.create({
toolbarContainer: '#cp-toolbar',
contentContainer: '#cp-app-form-editor',
}, andThen);
});