code
stringlengths 24
2.07M
| docstring
stringlengths 25
85.3k
| func_name
stringlengths 1
92
| language
stringclasses 1
value | repo
stringlengths 5
64
| path
stringlengths 4
172
| url
stringlengths 44
218
| license
stringclasses 7
values |
---|---|---|---|---|---|---|---|
function validateInput (value) {
// undefined values are always valid
if (value === undefined || value === null || value === '') return true;
// If a string is provided, check it is an upload or delete instruction
// TODO: This should really validate files as well, but that's not pased to this method
if (typeof value === 'string' && /^(upload\:)|(delete$)|(data:[a-z\/]+;base64)|(https?\:\/\/)/.test(value)) return true;
// If the value is an object and has a cloudinary public_id, it is valid
if (typeof value === 'object' && value.public_id) return true;
// None of the above? we can't recognise it.
return false;
}
|
Detects whether the field has been modified
|
validateInput
|
javascript
|
keystonejs/keystone-classic
|
fields/types/cloudinaryimage/CloudinaryImageType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/cloudinaryimage/CloudinaryImageType.js
|
MIT
|
function trimSupportedFileExtensions (publicId) {
var supportedExtensions = [
'.jpg', '.jpe', '.jpeg', '.jpc', '.jp2', '.j2k', '.wdp', '.jxr',
'.hdp', '.png', '.gif', '.webp', '.bmp', '.tif', '.tiff', '.ico',
'.pdf', '.ps', '.ept', '.eps', '.eps3', '.psd', '.svg', '.ai',
'.djvu', '.flif', '.tga',
];
for (var i = 0; i < supportedExtensions.length; i++) {
var extension = supportedExtensions[i];
if (_.endsWith(publicId, extension)) {
return publicId.slice(0, -extension.length);
}
}
return publicId;
}
|
Trim supported file extensions from the public id because cloudinary uses these at
the end of the a url to dynamically convert the image filetype
|
trimSupportedFileExtensions
|
javascript
|
keystonejs/keystone-classic
|
fields/types/cloudinaryimage/CloudinaryImageType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/cloudinaryimage/CloudinaryImageType.js
|
MIT
|
uploadComplete = function (result) {
if (result.error) {
callback(result.error);
} else {
item.set(field.path, result);
callback();
}
}
|
Returns a callback that handles a standard form submission for the field
Expected form parts are
- `field.paths.action` in `req.body` (`clear` or `delete`)
- `field.paths.upload` in `req.files` (uploads the image to cloudinary)
@api public
|
uploadComplete
|
javascript
|
keystonejs/keystone-classic
|
fields/types/cloudinaryimage/CloudinaryImageType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/cloudinaryimage/CloudinaryImageType.js
|
MIT
|
folder = function (item) { // eslint-disable-line no-unused-vars
var folderValue = '';
if (keystone.get('cloudinary folders')) {
if (field.options.folder) {
folderValue = field.options.folder;
} else {
var folderList = keystone.get('cloudinary prefix') ? [keystone.get('cloudinary prefix')] : [];
folderList.push(field.list.path);
folderList.push(field.path);
folderValue = folderList.join('/');
}
}
return folderValue;
}
|
Registers the field on the List's Mongoose Schema.
|
folder
|
javascript
|
keystonejs/keystone-classic
|
fields/types/cloudinaryimages/CloudinaryImagesType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/cloudinaryimages/CloudinaryImagesType.js
|
MIT
|
src = function (img, options) {
if (keystone.get('cloudinary secure')) {
options = options || {};
options.secure = true;
}
options.format = options.format || img.format;
return img.public_id ? cloudinary.url(img.public_id, options) : '';
}
|
Registers the field on the List's Mongoose Schema.
|
src
|
javascript
|
keystonejs/keystone-classic
|
fields/types/cloudinaryimages/CloudinaryImagesType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/cloudinaryimages/CloudinaryImagesType.js
|
MIT
|
addSize = function (options, width, height, other) {
if (width) options.width = width;
if (height) options.height = height;
if (typeof other === 'object') {
assign(options, other);
}
return options;
}
|
Registers the field on the List's Mongoose Schema.
|
addSize
|
javascript
|
keystonejs/keystone-classic
|
fields/types/cloudinaryimages/CloudinaryImagesType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/cloudinaryimages/CloudinaryImagesType.js
|
MIT
|
function getUploadOptions () {
if (cachedUploadOptions) {
return cachedUploadOptions;
}
var tagPrefix = keystone.get('cloudinary prefix') || '';
var uploadOptions = {
tags: [],
};
if (tagPrefix.length) {
uploadOptions.tags.push(tagPrefix);
tagPrefix += '_';
}
uploadOptions.tags.push(tagPrefix + field.list.path + '_' + field.path);
if (keystone.get('env') !== 'production') {
uploadOptions.tags.push(tagPrefix + 'dev');
}
var folder = field.getFolder();
if (folder) {
uploadOptions.folder = folder;
}
cachedUploadOptions = uploadOptions;
return uploadOptions;
}
|
Updates the value for this field in the item from a data object
|
getUploadOptions
|
javascript
|
keystonejs/keystone-classic
|
fields/types/cloudinaryimages/CloudinaryImagesType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/cloudinaryimages/CloudinaryImagesType.js
|
MIT
|
function code (list, path, options) {
this._nativeType = String;
this._defaultSize = 'full';
this.height = options.height || 180;
this.lang = options.lang || options.language;
this._properties = ['editor', 'height', 'lang'];
this.codemirror = options.codemirror || {};
this.editor = assign({ mode: this.lang }, this.codemirror);
code.super_.call(this, list, path, options);
}
|
Code FieldType Constructor
@extends Field
@api public
|
code
|
javascript
|
keystonejs/keystone-classic
|
fields/types/code/CodeType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/code/CodeType.js
|
MIT
|
function color (list, path, options) {
this._nativeType = String;
color.super_.call(this, list, path, options);
}
|
Color FieldType Constructor
@extends Field
@api public
|
color
|
javascript
|
keystonejs/keystone-classic
|
fields/types/color/ColorType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/color/ColorType.js
|
MIT
|
function date (list, path, options) {
this._nativeType = Date;
this._underscoreMethods = ['format', 'moment', 'parse'];
this._fixedSize = 'medium';
this._properties = ['formatString', 'yearRange', 'isUTC', 'inputFormat', 'todayButton'];
this.parseFormatString = options.inputFormat || 'YYYY-MM-DD';
this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY');
this.yearRange = options.yearRange;
this.isUTC = options.utc || false;
this.todayButton = typeof options.todayButton !== 'undefined' ? options.todayButton : true;
/*
* This offset is used to determine whether or not a stored date is probably corrupted or not.
* If the date/time stored plus this offset equals a time close to midnight for that day, that
* resulting date/time will be provided via the getData method instead of the one that is stored.
* By default this timezone offset matches the offset of the keystone server. Using the default
* setting is highly recommended.
*/
this.timezoneUtcOffsetMinutes = options.timezoneUtcOffsetMinutes || moment().utcOffset();
if (this.formatString && typeof this.formatString !== 'string') {
throw new Error('FieldType.Date: options.format must be a string.');
}
date.super_.call(this, list, path, options);
}
|
Date FieldType Constructor
@extends Field
@api public
|
date
|
javascript
|
keystonejs/keystone-classic
|
fields/types/date/DateType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/date/DateType.js
|
MIT
|
function datearray (list, path, options) {
this._nativeType = [Date];
this._defaultSize = 'medium';
this._underscoreMethods = ['format'];
this._properties = ['formatString'];
this.parseFormatString = options.parseFormat || 'YYYY-MM-DD';
this.formatString = (options.format === false) ? false : (options.format || 'Do MMM YYYY');
if (this.formatString && typeof this.formatString !== 'string') {
throw new Error('FieldType.DateArray: options.format must be a string.');
}
this.separator = options.separator || ' | ';
datearray.super_.call(this, list, path, options);
}
|
Date FieldType Constructor
@extends Field
@api public
|
datearray
|
javascript
|
keystonejs/keystone-classic
|
fields/types/datearray/DateArrayType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/datearray/DateArrayType.js
|
MIT
|
function datetime (list, path, options) {
this._nativeType = Date;
this._underscoreMethods = ['format', 'moment', 'parse'];
this._fixedSize = 'full';
this._properties = ['formatString', 'isUTC'];
this.typeDescription = 'date and time';
this.parseFormatString = options.parseFormat || parseFormats;
this.formatString = (options.format === false) ? false : (options.format || 'YYYY-MM-DD h:mm:ss a');
this.isUTC = options.utc || false;
if (this.formatString && typeof this.formatString !== 'string') {
throw new Error('FieldType.DateTime: options.format must be a string.');
}
datetime.super_.call(this, list, path, options);
this.paths = {
date: this.path + '_date',
time: this.path + '_time',
tzOffset: this.path + '_tzOffset',
};
}
|
DateTime FieldType Constructor
@extends Field
@api public
|
datetime
|
javascript
|
keystonejs/keystone-classic
|
fields/types/datetime/DatetimeType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/datetime/DatetimeType.js
|
MIT
|
function email (list, path, options) {
this._nativeType = String;
this._underscoreMethods = ['gravatarUrl'];
this.typeDescription = 'email address';
email.super_.call(this, list, path, options);
}
|
Email FieldType Constructor
@extends Field
@api public
|
email
|
javascript
|
keystonejs/keystone-classic
|
fields/types/email/EmailType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/email/EmailType.js
|
MIT
|
function embedly(list, path, options) {
this._underscoreMethods = ["reset"];
this._fixedSize = "full";
this.fromPath = options.from;
this.embedlyOptions = options.options || {};
// check and api key has been set, or bail.
if (!keystone.get("embedly api key")) {
throw new Error(
"Invalid Configuration\n\n" +
"Embedly fields (" +
list.key +
"." +
path +
') require the "embedly api key" option to be set.\n\n' +
"See http://v4.keystonejs.com/docs/configuration/#services-embedly for more information.\n"
);
}
// ensure a fromPath has been defined
if (!options.from) {
throw new Error(
"Invalid Configuration\n\n" +
"Embedly fields (" +
list.key +
"." +
path +
") require a fromPath option to be set.\n" +
"See http://v4.keystonejs.com/docs/database/#fieldtypes-embedly for more information.\n"
);
}
// embedly fields cannot be set as initial fields
if (options.initial) {
throw new Error(
"Invalid Configuration\n\n" +
"Embedly fields (" +
list.key +
"." +
path +
") cannot be set as initial fields.\n"
);
}
embedly.super_.call(this, list, path, options);
}
|
Embedly FieldType Constructor
Reqires the option `from` to refer to another path in the schema
that provides the url to expand
@extends Field
@api public
|
embedly
|
javascript
|
keystonejs/keystone-classic
|
fields/types/embedly/EmbedlyType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/embedly/EmbedlyType.js
|
MIT
|
buildInitialState = (props) => ({
action: null,
removeExisting: false,
uploadFieldPath: `File-${props.path}-${++uploadInc}`,
userSelectedFile: null,
})
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
buildInitialState
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
buildInitialState = (props) => ({
action: null,
removeExisting: false,
uploadFieldPath: `File-${props.path}-${++uploadInc}`,
userSelectedFile: null,
})
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
buildInitialState
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
getInitialState () {
return buildInitialState(this.props);
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
getInitialState
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
shouldCollapse () {
return this.props.collapse && !this.hasExisting();
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
shouldCollapse
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
componentWillUpdate (nextProps) {
// Show the new filename when it's finished uploading
if (this.props.value.filename !== nextProps.value.filename) {
this.setState(buildInitialState(nextProps));
}
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
componentWillUpdate
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
hasFile () {
return this.hasExisting() || !!this.state.userSelectedFile;
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
hasFile
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
hasExisting () {
return this.props.value && !!this.props.value.filename;
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
hasExisting
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
getFilename () {
return this.state.userSelectedFile
? this.state.userSelectedFile.name
: this.props.value.filename;
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
getFilename
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
getFileUrl () {
return this.props.value && this.props.value.url;
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
getFileUrl
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
isImage () {
const href = this.props.value ? this.props.value.url : undefined;
return href && href.match(/\.(jpeg|jpg|gif|png|svg)$/i) != null;
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
isImage
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
handleFileChange (event) {
const userSelectedFile = event.target.files[0];
this.setState({
userSelectedFile: userSelectedFile,
});
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
handleFileChange
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
handleRemove (e) {
var state = {};
if (this.state.userSelectedFile) {
state = buildInitialState(this.props);
} else if (this.hasExisting()) {
state.removeExisting = true;
if (this.props.autoCleanup) {
if (e.altKey) {
state.action = 'reset';
} else {
state.action = 'delete';
}
} else {
if (e.altKey) {
state.action = 'delete';
} else {
state.action = 'reset';
}
}
}
this.setState(state);
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
handleRemove
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
renderFileNameAndChangeMessage () {
const href = this.props.value ? this.props.value.url : undefined;
return (
<div>
{(this.hasFile() && !this.state.removeExisting) ? (
<FileChangeMessage component={href ? 'a' : 'span'} href={href} target="_blank">
{this.getFilename()}
</FileChangeMessage>
) : null}
{this.renderChangeMessage()}
</div>
);
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
renderFileNameAndChangeMessage
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
renderChangeMessage () {
if (this.state.userSelectedFile) {
return (
<FileChangeMessage color="success">
Save to Upload
</FileChangeMessage>
);
} else if (this.state.removeExisting) {
return (
<FileChangeMessage color="danger">
File {this.props.autoCleanup ? 'deleted' : 'removed'} - save to confirm
</FileChangeMessage>
);
} else {
return null;
}
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
renderChangeMessage
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
renderClearButton () {
if (this.state.removeExisting) {
return (
<Button variant="link" onClick={this.undoRemove}>
Undo Remove
</Button>
);
} else {
var clearText;
if (this.state.userSelectedFile) {
clearText = 'Cancel Upload';
} else {
clearText = (this.props.autoCleanup ? 'Delete File' : 'Remove File');
}
return (
<Button variant="link" color="cancel" onClick={this.handleRemove}>
{clearText}
</Button>
);
}
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
renderClearButton
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
renderActionInput () {
// If the user has selected a file for uploading, we need to point at
// the upload field. If the file is being deleted, we submit that.
if (this.state.userSelectedFile || this.state.action) {
const value = this.state.userSelectedFile
? `upload:${this.state.uploadFieldPath}`
: (this.state.action === 'delete' ? 'remove' : '');
return (
<input
name={this.getInputName(this.props.path)}
type="hidden"
value={value}
/>
);
} else {
return null;
}
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
renderActionInput
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
renderImagePreview () {
const imageSource = this.getFileUrl();
return (
<ImageThumbnail
component="a"
href={imageSource}
target="__blank"
style={{ float: 'left', marginRight: '1em', maxWidth: '50%' }}
>
<img src={imageSource} style={{ 'max-height': 100, 'max-width': '100%' }} />
</ImageThumbnail>
);
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
renderImagePreview
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
renderUI () {
const { label, note, path, thumb } = this.props;
const isImage = this.isImage();
const hasFile = this.hasFile();
const previews = (
<div style={(isImage && thumb) ? { marginBottom: '1em' } : null}>
{isImage && thumb && this.renderImagePreview()}
{hasFile && this.renderFileNameAndChangeMessage()}
</div>
);
const buttons = (
<div style={hasFile ? { marginTop: '1em' } : null}>
<Button onClick={this.triggerFileBrowser}>
{hasFile ? 'Change' : 'Upload'} File
</Button>
{hasFile && this.renderClearButton()}
</div>
);
return (
<div data-field-name={path} data-field-type="file">
<FormField label={label} htmlFor={path}>
{this.shouldRenderField() ? (
<div>
{previews}
{buttons}
<HiddenFileInput
key={this.state.uploadFieldPath}
name={this.state.uploadFieldPath}
onChange={this.handleFileChange}
ref="fileInput"
/>
{this.renderActionInput()}
</div>
) : (
<div>
{hasFile
? this.renderFileNameAndChangeMessage()
: <FormInput noedit>no file</FormInput>}
</div>
)}
{!!note && <FormNote html={note} />}
</FormField>
</div>
);
}
|
TODO:
- Format size of stored file (if present) using bytes package?
- Display file type icon? (see LocalFileField)
|
renderUI
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileField.js
|
MIT
|
function validateInput (value) {
// undefined, null and empty values are always valid
if (value === undefined || value === null || value === '') return true;
// If a string is provided, check it is an upload or delete instruction
if (typeof value === 'string' && /^(upload\:)|(delete$)/.test(value)) return true;
// If the value is an object with a filename property, it is a stored value
// TODO: Need to actually check a dynamic path based on the adapter
if (typeof value === 'object' && value.filename) return true;
return false;
}
|
Detects whether the field has been modified
|
validateInput
|
javascript
|
keystonejs/keystone-classic
|
fields/types/file/FileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/file/FileType.js
|
MIT
|
function geopoint (list, path, options) {
this._fixedSize = 'medium';
geopoint.super_.call(this, list, path, options);
}
|
Geo FieldType Constructor
@extends Field
@api public
|
geopoint
|
javascript
|
keystonejs/keystone-classic
|
fields/types/geopoint/GeoPointType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/geopoint/GeoPointType.js
|
MIT
|
function html (list, path, options) {
this._nativeType = String;
this._defaultSize = 'full';
this.wysiwyg = options.wysiwyg || false;
this.height = options.height || 180;
this._properties = ['wysiwyg', 'height'];
html.super_.call(this, list, path, options);
}
|
HTML FieldType Constructor
@extends Field
@api public
|
html
|
javascript
|
keystonejs/keystone-classic
|
fields/types/html/HtmlType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/html/HtmlType.js
|
MIT
|
function key (list, path, options) {
this._nativeType = String;
this._defaultSize = 'medium';
this.separator = options.separator || '-';
key.super_.call(this, list, path, options);
}
|
Key FieldType Constructor
@extends Field
@api public
|
key
|
javascript
|
keystonejs/keystone-classic
|
fields/types/key/KeyType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/key/KeyType.js
|
MIT
|
function localfile (list, path, options) {
throw new Error('The LocalFile field type has been removed. Please use File instead.'
+ '\n\nSee https://github.com/keystonejs/keystone/wiki/File-Fields-Upgrade-Guide\n');
/*
grappling.mixin(this).allowHooks('move');
this._underscoreMethods = ['format', 'uploadFile'];
this._fixedSize = 'full';
this.autoCleanup = options.autoCleanup || false;
if (options.overwrite !== false) {
options.overwrite = true;
}
localfile.super_.call(this, list, path, options);
// validate destination dir
if (!options.dest) {
throw new Error('Invalid Configuration\n\n'
+ 'localfile fields (' + list.key + '.' + path + ') require the "dest" option to be set.');
}
// Allow hook into before and after
if (options.pre && options.pre.move) {
this.pre('move', options.pre.move);
}
if (options.post && options.post.move) {
this.post('move', options.post.move);
}
*/
}
|
localfile FieldType Constructor
@extends Field
@api public
|
localfile
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfile/LocalFileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfile/LocalFileType.js
|
MIT
|
exists = function (item) {
var filepath = item.get(paths.path);
var filename = item.get(paths.filename);
if (!filepath || !filename) {
return false;
}
return fs.existsSync(path.join(filepath, filename));
}
|
Registers the field on the List's Mongoose Schema.
@api public
|
exists
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfile/LocalFileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfile/LocalFileType.js
|
MIT
|
reset = function (item) {
item.set(field.path, {
filename: '',
path: '',
size: 0,
filetype: '',
});
}
|
Registers the field on the List's Mongoose Schema.
@api public
|
reset
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfile/LocalFileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfile/LocalFileType.js
|
MIT
|
function validateInput (value) {
// undefined values are always valid
if (value === undefined) return true;
// TODO: strings may not actually be valid but this will be OK for now
// If a string is provided, assume it's a file path and move the file into
// place. Come back and check the file actually exists if a string is provided
if (typeof value === 'string') return true;
// If the value is an object with a path, it is valid
if (typeof value === 'object' && value.path) return true;
return false;
}
|
Detects whether the field has been modified
@api public
|
validateInput
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfile/LocalFileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfile/LocalFileType.js
|
MIT
|
doMove = function (callback) {
if (typeof field.options.filename === 'function') {
filename = field.options.filename(item, file);
}
fs.move(file.path, path.join(field.options.dest, filename), { clobber: field.options.overwrite }, function (err) {
if (err) return callback(err);
var fileData = {
filename: filename,
originalname: file.originalname,
path: field.options.dest,
size: file.size,
filetype: filetype,
};
if (update) {
item.set(field.path, fileData);
}
callback(null, fileData);
});
}
|
Uploads the file for this field
@api public
|
doMove
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfile/LocalFileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfile/LocalFileType.js
|
MIT
|
function localfiles (list, path, options) {
throw new Error('The LocalFiles field type has been removed. Please use File instead.'
+ '\n\nSee https://github.com/keystonejs/keystone/wiki/File-Fields-Upgrade-Guide\n');
/*
grappling.mixin(this).allowHooks('move');
this._underscoreMethods = ['format', 'uploadFiles'];
this._fixedSize = 'full';
// TODO: implement filtering, usage disabled for now
options.nofilter = true;
// TODO: implement initial form, usage disabled for now
if (options.initial) {
throw new Error('Invalid Configuration\n\n'
+ 'localfiles fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
}
if (options.overwrite !== false) {
options.overwrite = true;
}
localfiles.super_.call(this, list, path, options);
// validate destination dir
if (!options.dest) {
throw new Error('Invalid Configuration\n\n'
+ 'localfiles fields (' + list.key + '.' + path + ') require the "dest" option to be set.');
}
// Allow hook into before and after
if (options.pre && options.pre.move) {
this.pre('move', options.pre.move);
}
if (options.post && options.post.move) {
this.post('move', options.post.move);
}
*/
}
|
localfiles FieldType Constructor
@extends Field
@api public
|
localfiles
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfiles/LocalFilesType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfiles/LocalFilesType.js
|
MIT
|
exists = function (item, element_id) {
var values = item.get(field.path);
var value;
if (typeof values === 'undefined' || values.length === 0) {
return false;
}
// if current Field contains any file, it means it exists
if (typeof element_id === 'undefined') {
value = values[0];
} else {
// allow implicit type coercion to compare string IDs with MongoID objects
value = values.find(function (val) { return val._id == element_id; }); // eslint-disable-line eqeqeq
}
if (typeof value === 'undefined') {
return false;
}
var filepaths = value.path;
var filename = value.filename;
if (!filepaths || !filename) {
return false;
}
return fs.existsSync(path.join(filepaths, filename));
}
|
Registers the field on the List's Mongoose Schema.
|
exists
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfiles/LocalFilesType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfiles/LocalFilesType.js
|
MIT
|
reset = function (item, element_id) {
if (typeof element_id === 'undefined') {
item.set(field.path, []);
} else {
var values = item.get(field.path);
// allow implicit type coercion to compare string IDs with MongoID objects
var value = values.find(function (val) { return val._id == element_id; }); // eslint-disable-line eqeqeq
if (typeof value !== 'undefined') {
values.splice(values.indexOf(value), 1);
item.set(field.path, values);
}
}
}
|
Registers the field on the List's Mongoose Schema.
|
reset
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfiles/LocalFilesType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfiles/LocalFilesType.js
|
MIT
|
doMove = function (doneMove) {
if (typeof field.options.filename === 'function') {
filename = field.options.filename(item, file);
}
fs.move(file.path, path.join(field.options.dest, filename), { clobber: field.options.overwrite }, function (err) {
if (err) return doneMove(err);
var fileData = {
filename: filename,
originalname: file.originalname,
path: field.options.dest,
size: file.size,
filetype: filetype,
};
if (update) {
item.get(field.path).push(fileData);
}
doneMove(null, fileData);
});
}
|
Uploads the file for this field
|
doMove
|
javascript
|
keystonejs/keystone-classic
|
fields/types/localfiles/LocalFilesType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/localfiles/LocalFilesType.js
|
MIT
|
getInitialState () {
return {
collapsedFields: {},
improve: false,
overwrite: false,
};
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
getInitialState
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
componentWillMount () {
const { value = [] } = this.props;
var collapsedFields = {};
_.forEach(['number', 'name', 'street2', 'geo'], (i) => {
if (!value[i]) {
collapsedFields[i] = true;
}
}, this);
this.setState({ collapsedFields });
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
componentWillMount
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
shouldCollapse () {
return this.props.collapse && !this.formatValue();
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
shouldCollapse
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
uncollapseFields () {
this.setState({
collapsedFields: {},
});
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
uncollapseFields
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
fieldChanged (fieldPath, event) {
const { value = {}, path, onChange } = this.props;
onChange({
path,
value: {
...value,
[fieldPath]: event.target.value,
},
});
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
fieldChanged
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
makeChanger (fieldPath) {
return this.fieldChanged.bind(this, fieldPath);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
makeChanger
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
geoChanged (i, event) {
const { value = {}, path, onChange } = this.props;
const newVal = event.target.value;
const geo = [
i === 0 ? newVal : value.geo ? value.geo[0] : '',
i === 1 ? newVal : value.geo ? value.geo[1] : '',
];
onChange({
path,
value: {
...value,
geo,
},
});
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
geoChanged
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
makeGeoChanger (fieldPath) {
return this.geoChanged.bind(this, fieldPath);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
makeGeoChanger
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
formatValue () {
const { value = {} } = this.props;
return _.compact([
value.number,
value.name,
value.street1,
value.street2,
value.suburb,
value.state,
value.postcode,
value.country,
]).join(', ');
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
formatValue
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
renderValue () {
return <FormInput noedit>{this.formatValue() || ''}</FormInput>;
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
renderValue
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
renderField (fieldPath, label, collapse, autoFocus) {
if (this.state.collapsedFields[fieldPath]) {
return null;
}
const { value = {}, path } = this.props;
return (
<NestedFormField label={label} data-field-location-path={path + '.' + fieldPath}>
<FormInput
autoFocus={autoFocus}
name={this.getInputName(path + '.' + fieldPath)}
onChange={this.makeChanger(fieldPath)}
placeholder={label}
value={value[fieldPath] || ''}
/>
</NestedFormField>
);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
renderField
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
renderSuburbState () {
const { value = {}, path } = this.props;
return (
<NestedFormField label="Suburb / State" data-field-location-path={path + '.suburb_state'}>
<Grid.Row gutter={10}>
<Grid.Col small="two-thirds" data-field-location-path={path + '.suburb'}>
<FormInput
name={this.getInputName(path + '.suburb')}
onChange={this.makeChanger('suburb')}
placeholder="Suburb"
value={value.suburb || ''}
/>
</Grid.Col>
<Grid.Col small="one-third" data-field-location-path={path + '.state'}>
<FormInput
name={this.getInputName(path + '.state')}
onChange={this.makeChanger('state')}
placeholder="State"
value={value.state || ''}
/>
</Grid.Col>
</Grid.Row>
</NestedFormField>
);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
renderSuburbState
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
renderPostcodeCountry () {
const { value = {}, path } = this.props;
return (
<NestedFormField label="Postcode / Country" data-field-location-path={path + '.postcode_country'}>
<Grid.Row gutter={10}>
<Grid.Col small="one-third" data-field-location-path={path + '.postcode'}>
<FormInput
name={this.getInputName(path + '.postcode')}
onChange={this.makeChanger('postcode')}
placeholder="Post Code"
value={value.postcode || ''}
/>
</Grid.Col>
<Grid.Col small="two-thirds" data-field-location-path={path + '.country'}>
<FormInput
name={this.getInputName(path + '.country')}
onChange={this.makeChanger('country')}
placeholder="Country"
value={value.country || ''}
/>
</Grid.Col>
</Grid.Row>
</NestedFormField>
);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
renderPostcodeCountry
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
renderGeo () {
if (this.state.collapsedFields.geo) {
return null;
}
const { value = {}, path, paths } = this.props;
const geo = value.geo || [];
return (
<NestedFormField label="Lat / Lng" data-field-location-path={path + '.geo'}>
<Grid.Row gutter={10}>
<Grid.Col small="one-half" data-field-location-path="latitude">
<FormInput
name={this.getInputName(paths.geo + '[1]')}
onChange={this.makeGeoChanger(1)}
placeholder="Latitude"
value={geo[1] || ''}
/>
</Grid.Col>
<Grid.Col small="one-half" data-field-location-path="longitude">
<FormInput
name={this.getInputName(paths.geo + '[0]')}
onChange={this.makeGeoChanger(0)}
placeholder="Longitude"
value={geo[0] || ''}
/>
</Grid.Col>
</Grid.Row>
</NestedFormField>
);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
renderGeo
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
updateGoogleOption (key, e) {
var newState = {};
newState[key] = e.target.checked;
this.setState(newState);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
updateGoogleOption
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
makeGoogler (key) {
return this.updateGoogleOption.bind(this, key);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
makeGoogler
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
renderGoogleOptions () {
const { paths, enableMapsAPI } = this.props;
if (!enableMapsAPI) return null;
var replace = this.state.improve ? (
<LabelledControl
checked={this.state.overwrite}
label="Replace existing data"
name={this.getInputName(paths.overwrite)}
onChange={this.makeGoogler('overwrite')}
type="checkbox"
/>
) : null;
return (
<FormField offsetAbsentLabel>
<LabelledControl
checked={this.state.improve}
label="Autodetect and improve location on save"
name={this.getInputName(paths.improve)}
onChange={this.makeGoogler('improve')}
title="When checked, this will attempt to fill missing fields. It will also get the lat/long"
type="checkbox"
/>
{replace}
</FormField>
);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
renderGoogleOptions
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
renderNote () {
const { note } = this.props;
if (!note) return null;
return (
<FormField offsetAbsentLabel>
<FormNote note={note} />
</FormField>
);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
renderNote
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
renderUI () {
if (!this.shouldRenderField()) {
return (
<FormField label={this.props.label}>{this.renderValue()}</FormField>
);
}
/* eslint-disable no-script-url */
var showMore = !_.isEmpty(this.state.collapsedFields)
? <CollapsedFieldLabel onClick={this.uncollapseFields}>(show more fields)</CollapsedFieldLabel>
: null;
/* eslint-enable */
const { label, path } = this.props;
return (
<div data-field-name={path} data-field-type="location">
<FormField label={label} htmlFor={path}>
{showMore}
</FormField>
{this.renderField('number', 'PO Box / Shop', true, true)}
{this.renderField('name', 'Building Name', true)}
{this.renderField('street1', 'Street Address')}
{this.renderField('street2', 'Street Address 2', true)}
{this.renderSuburbState()}
{this.renderPostcodeCountry()}
{this.renderGeo()}
{this.renderGoogleOptions()}
{this.renderNote()}
</div>
);
}
|
TODO:
- Remove dependency on underscore
- Custom path support
|
renderUI
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationField.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationField.js
|
MIT
|
getFieldDef = function (type, key) {
var def = { type: type };
if (options.defaults[key]) {
def.default = options.defaults[key];
}
return def;
}
|
Registers the field on the List's Mongoose Schema.
|
getFieldDef
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationType.js
|
MIT
|
setValue = function (key) {
if (valuePaths[key] in values && values[valuePaths[key]] !== item.get(paths[key])) {
item.set(paths[key], values[valuePaths[key]] || null);
}
}
|
Updates the value for this field in the item from a data object
|
setValue
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationType.js
|
MIT
|
function calculateDistance (point1, point2) {
var dLng = (point2[0] - point1[0]) * Math.PI / 180;
var dLat = (point2[1] - point1[1]) * Math.PI / 180;
var lat1 = (point1[1]) * Math.PI / 180;
var lat2 = (point2[1]) * Math.PI / 180;
/* eslint-disable space-infix-ops */
var a = Math.sin(dLat/2) * Math.sin(dLat/2) + Math.sin(dLng/2) * Math.sin(dLng/2) * Math.cos(lat1) * Math.cos(lat2);
var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
/* eslint-enable space-infix-ops */
return c;
}
|
Internal Distance calculation function
See http://en.wikipedia.org/wiki/Haversine_formula
|
calculateDistance
|
javascript
|
keystonejs/keystone-classic
|
fields/types/location/LocationType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/location/LocationType.js
|
MIT
|
function markdown (list, path, options) {
this._defaultSize = 'full';
this.toolbarOptions = options.toolbarOptions || {};
this.markedOptions = options.markedOptions || {};
// See sanitize-html docs for defaults
// .. https://www.npmjs.com/package/sanitize-html#what-are-the-default-options
this.sanitizeOptions = options.sanitizeOptions || {};
this.height = options.height || 90;
this.wysiwyg = ('wysiwyg' in options) ? options.wysiwyg : true;
this._properties = ['wysiwyg', 'height', 'toolbarOptions'];
markdown.super_.call(this, list, path, options);
}
|
Markdown FieldType Constructor
@extends Field
@api public
|
markdown
|
javascript
|
keystonejs/keystone-classic
|
fields/types/markdown/MarkdownType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/markdown/MarkdownType.js
|
MIT
|
setMarkdown = function (value) {
// Clear if saving invalid value
if (typeof value !== 'string') {
this.set(paths.md, undefined);
this.set(paths.html, undefined);
return undefined;
}
var newMd = sanitizeHtml(value, sanitizeOptions);
var newHtml = marked(newMd, markedOptions);
// Return early if no changes to save
if (newMd === this.get(paths.md) && newHtml === this.get(paths.html)) {
return newMd;
}
this.set(paths.md, newMd);
this.set(paths.html, newHtml);
return newMd;
}
|
Registers the field on the List's Mongoose Schema.
Adds String properties for .md and .html markdown, and a setter for .md
that generates html when it is updated.
|
setMarkdown
|
javascript
|
keystonejs/keystone-classic
|
fields/types/markdown/MarkdownType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/markdown/MarkdownType.js
|
MIT
|
function normalizeResults (results) {
var normalized = [];
for (var i = 0; i < results.length; i++) {
normalized.push(results[i].md);
}
return normalized;
}
|
Normalizes the results we get from filter()
@param {array} results The results array
@return {array} The normalized results
|
normalizeResults
|
javascript
|
keystonejs/keystone-classic
|
fields/types/markdown/test/filters.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/markdown/test/filters.js
|
MIT
|
function money (list, path, options) {
if (options.currency) {
throw new Error('The currency option from money has been deprecated. Provide a formatString instead');
}
this._nativeType = Number;
this._underscoreMethods = ['format'];
this._properties = ['currency'];
this._fixedSize = 'small';
this._formatString = (options.format === false) ? false : (options.format || '$0,0.00');
if (this._formatString && typeof this._formatString !== 'string') {
throw new Error('FieldType.Money: options.format must be a string.');
}
money.super_.call(this, list, path, options);
}
|
Money FieldType Constructor
@extends Field
@api public
|
money
|
javascript
|
keystonejs/keystone-classic
|
fields/types/money/MoneyType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/money/MoneyType.js
|
MIT
|
function name (list, path, options) {
this._fixedSize = 'full';
options.default = { first: '', last: '' };
name.super_.call(this, list, path, options);
}
|
Name FieldType Constructor
@extends Field
@api public
|
name
|
javascript
|
keystonejs/keystone-classic
|
fields/types/name/NameType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/name/NameType.js
|
MIT
|
function number (list, path, options) {
this._nativeType = Number;
this._fixedSize = 'small';
this._underscoreMethods = ['format'];
this.formatString = (options.format === false) ? false : (options.format || '0,0[.][000000000000]');
if (this.formatString && typeof this.formatString !== 'string') {
throw new Error('FieldType.Number: options.format must be a string.');
}
number.super_.call(this, list, path, options);
}
|
Number FieldType Constructor
@extends Field
@api public
|
number
|
javascript
|
keystonejs/keystone-classic
|
fields/types/number/NumberType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/number/NumberType.js
|
MIT
|
function numberarray (list, path, options) {
this._nativeType = [Number];
this._underscoreMethods = ['format'];
this._formatString = (options.format === false) ? false : (options.format || '0,0[.][000000000000]');
this._defaultSize = 'small';
if (this._formatString && typeof this._formatString !== 'string') {
throw new Error('FieldType.NumberArray: options.format must be a string.');
}
this.separator = options.separator || ' | ';
numberarray.super_.call(this, list, path, options);
}
|
Number FieldType Constructor
@extends Field
@api public
|
numberarray
|
javascript
|
keystonejs/keystone-classic
|
fields/types/numberarray/NumberArrayType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/numberarray/NumberArrayType.js
|
MIT
|
function isValidNumber (value) {
return !Number.isNaN(utils.number(value));
}
|
Checks if a value is a valid number
|
isValidNumber
|
javascript
|
keystonejs/keystone-classic
|
fields/types/numberarray/NumberArrayType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/numberarray/NumberArrayType.js
|
MIT
|
function password (list, path, options) {
// Apply default and enforced options (you can't sort on password fields)
options = Object.assign({}, defaultOptions, options, { nosort: false });
this._nativeType = String;
this._underscoreMethods = ['format', 'compare'];
this._fixedSize = 'full';
password.super_.call(this, list, path, options);
for (var key in this.options.complexity) {
if ({}.hasOwnProperty.call(this.options.complexity, key)) {
if (key in regexChunk !== key in this.options.complexity) {
throw new Error('FieldType.Password: options.complexity - option does not exist.');
}
if (typeof this.options.complexity[key] !== 'boolean') {
throw new Error('FieldType.Password: options.complexity - Value must be boolean.');
}
}
}
if (this.options.max && this.options.max < this.options.min) {
throw new Error('FieldType.Password: options - maximum password length cannot be less than the minimum length.');
}
}
|
password FieldType Constructor
@extends Field
@api public
|
password
|
javascript
|
keystonejs/keystone-classic
|
fields/types/password/PasswordType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/password/PasswordType.js
|
MIT
|
function relationship (list, path, options) {
this.many = (options.many) ? true : false;
this.filters = options.filters;
this.createInline = (options.createInline) ? true : false;
this._defaultSize = 'full';
this._nativeType = keystone.mongoose.Schema.Types.ObjectId;
this._underscoreMethods = ['format', 'getExpandedData'];
this._properties = ['isValid', 'many', 'filters', 'createInline'];
relationship.super_.call(this, list, path, options);
}
|
Relationship FieldType Constructor
@extends Field
@api public
|
relationship
|
javascript
|
keystonejs/keystone-classic
|
fields/types/relationship/RelationshipType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/relationship/RelationshipType.js
|
MIT
|
function expandRelatedItemData (item) {
if (!item || !item.id) return undefined;
return {
id: item.id,
name: this.refList.getDocumentName(item),
};
}
|
Gets id and name for the related item(s) from populated values
|
expandRelatedItemData
|
javascript
|
keystonejs/keystone-classic
|
fields/types/relationship/RelationshipType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/relationship/RelationshipType.js
|
MIT
|
function truthy (value) {
return value;
}
|
Gets id and name for the related item(s) from populated values
|
truthy
|
javascript
|
keystonejs/keystone-classic
|
fields/types/relationship/RelationshipType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/relationship/RelationshipType.js
|
MIT
|
function s3file(list, path, options) {
throw new Error(
"The S3File field type has been removed. Please use File instead." +
"\n\nSee https://github.com/keystonejs/keystone/wiki/File-Fields-Upgrade-Guide\n"
);
/*
grappling.mixin(this).allowHooks('pre:upload');
this._underscoreMethods = ['format', 'uploadFile'];
this._fixedSize = 'full';
// TODO: implement filtering, usage disabled for now
options.nofilter = true;
// TODO: implement initial form, usage disabled for now
if (options.initial) {
throw new Error('Invalid Configuration\n\n'
+ 'S3File fields (' + list.key + '.' + path + ') do not currently support being used as initial fields.\n');
}
s3file.super_.call(this, list, path, options);
// validate s3 config (has to happen after super_.call)
if (!this.s3config) {
throw new Error('Invalid Configuration\n\n'
+ 'S3File fields (' + list.key + '.' + path + ') require the "s3 config" option to be set.\n\n'
+ 'See http://v4.keystonejs.com/docs/configuration/#services-amazons3 for more information.\n');
}
// Could be more pre- hooks, just upload for now
if (options.pre && options.pre.upload) {
this.pre('upload', options.pre.upload);
}
*/
}
|
S3File FieldType Constructor
@extends Field
@api public
|
s3file
|
javascript
|
keystonejs/keystone-classic
|
fields/types/s3file/S3FileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/s3file/S3FileType.js
|
MIT
|
exists = function(item) {
return item.get(paths.url) ? true : false;
}
|
Registers the field on the List's Mongoose Schema.
|
exists
|
javascript
|
keystonejs/keystone-classic
|
fields/types/s3file/S3FileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/s3file/S3FileType.js
|
MIT
|
reset = function(item) {
item.set(field.path, {
filename: "",
originalname: "",
path: "",
size: 0,
filetype: "",
url: ""
});
}
|
Registers the field on the List's Mongoose Schema.
|
reset
|
javascript
|
keystonejs/keystone-classic
|
fields/types/s3file/S3FileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/s3file/S3FileType.js
|
MIT
|
validateHeader = function(header, callback) {
var HEADER_NAME_KEY = "name";
var HEADER_VALUE_KEY = "value";
var validKeys = [HEADER_NAME_KEY, HEADER_VALUE_KEY];
var filteredKeys;
if (!_.has(header, HEADER_NAME_KEY)) {
return callback(
new Error(
'Unsupported Header option: missing required key "' +
HEADER_NAME_KEY +
'" in ' +
JSON.stringify(header)
)
);
}
if (!_.has(header, HEADER_VALUE_KEY)) {
return callback(
new Error(
'Unsupported Header option: missing required key "' +
HEADER_VALUE_KEY +
'" in ' +
JSON.stringify(header)
)
);
}
filteredKeys = _.filter(_.keys(header), function(key) {
return _.indexOf(validKeys, key) > -1;
});
_.forEach(filteredKeys, function(key) {
if (!_.isString(header[key])) {
return callback(
new Error(
"Unsupported Header option: value for " +
key +
" header must be a String " +
header[key].toString()
)
);
}
});
return true;
}
|
Validates a header option value provided for this item, throwing an error otherwise
@param header {Object} the header object to validate
@param callback {Function} a callback function to call when validation is complete
@return {Boolean}
|
validateHeader
|
javascript
|
keystonejs/keystone-classic
|
fields/types/s3file/S3FileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/s3file/S3FileType.js
|
MIT
|
validateHeaders = function(headers, callback) {
var _headers = [];
if (!_.isObject(headers)) {
return callback(
new Error(
"Unsupported Header option: headers must be an Object " +
JSON.stringify(headers)
)
);
}
_.forEach(headers, function(value, key) {
_headers.push({ name: key, value: value });
});
_.forEach(_headers, function(header) {
validateHeader(header, callback);
});
return true;
}
|
Convenience method to validate a headers object
@param headers {Object} the headers object to validate
@param callback {Function} a callback function to call when validation is complete
@return {Boolean}
|
validateHeaders
|
javascript
|
keystonejs/keystone-classic
|
fields/types/s3file/S3FileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/s3file/S3FileType.js
|
MIT
|
doUpload = function() {
if (typeof field.options.path === "function") {
path = field.options.path(item, path);
}
if (typeof field.options.filename === "function") {
filename = field.options.filename(item, filename, originalname);
}
headers = field.generateHeaders(item, file, callback);
knox
.createClient(field.s3config)
.putFile(file.path, path + filename, headers, function(err, res) {
if (err) return callback(err);
if (res) {
if (res.statusCode !== 200) {
return callback(
new Error("Amazon returned Http Code: " + res.statusCode)
);
} else {
res.resume();
}
}
var protocol =
(field.s3config.protocol && field.s3config.protocol + ":") || "";
var url = res.req.url
.replace(/^https?:/i, protocol)
.replace(/%25/g, "%");
var fileData = {
filename: filename,
originalname: originalname,
path: path,
size: file.size,
filetype: filetype,
url: url
};
if (update) {
item.set(field.path, fileData);
}
callback(null, fileData);
});
}
|
Uploads the file for this field
|
doUpload
|
javascript
|
keystonejs/keystone-classic
|
fields/types/s3file/S3FileType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/s3file/S3FileType.js
|
MIT
|
function select (list, path, options) {
this.ui = options.ui || 'select';
this.numeric = options.numeric ? true : false;
this._nativeType = (options.numeric) ? Number : String;
this._underscoreMethods = ['format', 'pluck'];
this._properties = ['ops', 'numeric'];
if (typeof options.options === 'string') {
options.options = options.options.split(',');
}
if (!Array.isArray(options.options)) {
throw new Error('Select fields require an options array.');
}
this.ops = options.options.map(function (i) {
var op = typeof i === 'string' ? { value: i.trim(), label: utils.keyToLabel(i) } : i;
if (!_.isObject(op)) {
op = { label: '' + i, value: '' + i };
}
if (options.numeric && !_.isNumber(op.value)) {
op.value = Number(op.value);
}
return op;
});
// undefined options.emptyOption defaults to true
if (options.emptyOption === undefined) {
options.emptyOption = true;
}
// ensure this.emptyOption is a boolean
this.emptyOption = !!options.emptyOption;
// cached maps for options, labels and values
this.map = utils.optionsMap(this.ops);
this.labels = utils.optionsMap(this.ops, 'label');
this.values = _.map(this.ops, 'value');
select.super_.call(this, list, path, options);
}
|
Select FieldType Constructor
@extends Field
@api public
|
select
|
javascript
|
keystonejs/keystone-classic
|
fields/types/select/SelectType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/select/SelectType.js
|
MIT
|
function text (list, path, options) {
this.options = options;
this._nativeType = String;
this._properties = ['monospace'];
this._underscoreMethods = ['crop'];
text.super_.call(this, list, path, options);
}
|
Text FieldType Constructor
@extends Field
@api public
|
text
|
javascript
|
keystonejs/keystone-classic
|
fields/types/text/TextType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/text/TextType.js
|
MIT
|
function textarea (list, path, options) {
this._nativeType = String;
this._underscoreMethods = ['format', 'crop'];
this.height = options.height || 90;
this.multiline = true;
this._properties = ['height', 'multiline'];
textarea.super_.call(this, list, path, options);
}
|
Text FieldType Constructor
@extends Field
@api public
|
textarea
|
javascript
|
keystonejs/keystone-classic
|
fields/types/textarea/TextareaType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/textarea/TextareaType.js
|
MIT
|
function textarray (list, path, options) {
this._nativeType = [String];
this._underscoreMethods = ['format'];
this.separator = options.separator || ' | ';
textarray.super_.call(this, list, path, options);
}
|
TextArray FieldType Constructor
@extends Field
@api public
|
textarray
|
javascript
|
keystonejs/keystone-classic
|
fields/types/textarray/TextArrayType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/textarray/TextArrayType.js
|
MIT
|
function url (list, path, options) {
this._nativeType = String;
this._underscoreMethods = ['format'];
url.super_.call(this, list, path, options);
}
|
URL FieldType Constructor
@extends Field
@api public
|
url
|
javascript
|
keystonejs/keystone-classic
|
fields/types/url/UrlType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/url/UrlType.js
|
MIT
|
function removeProtocolPrefix (url) {
return url.replace(/^[a-zA-Z]+\:\/\//, '');
}
|
Remove the protocol prefix from url
|
removeProtocolPrefix
|
javascript
|
keystonejs/keystone-classic
|
fields/types/url/UrlType.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/types/url/UrlType.js
|
MIT
|
function addPresenceToQuery (presence, currentPathQuery) {
var newQuery;
// Adds $elemMatch if the presence choice is 'all'
// ('all' is the default)
if (presence === 'some') {
newQuery = {
$elemMatch: currentPathQuery,
};
// Adds $not if the presence is 'none'
} else if (presence === 'none') {
newQuery = {
$not: currentPathQuery,
};
}
// Return the newQuery if the presence changed something
// otherwise return the original query
return newQuery || currentPathQuery;
}
|
Accounts for the presence choice when filtering
@param {String} presence The current presence choice
@param {Object} currentPathQuery The current request query
|
addPresenceToQuery
|
javascript
|
keystonejs/keystone-classic
|
fields/utils/addPresenceToQuery.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/utils/addPresenceToQuery.js
|
MIT
|
function definePrototypeGetter (Constructor, key, getter) {
Object.defineProperty(Constructor.prototype, key, {
get: getter,
});
}
|
Defines a getter on the Field prototype
@param {string} key The key the getter should be at
@param {function} getter The getter itself
|
definePrototypeGetter
|
javascript
|
keystonejs/keystone-classic
|
fields/utils/definePrototypeGetters.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/utils/definePrototypeGetters.js
|
MIT
|
function definePrototypeGetters (Constructor, getterObj) {
Object.keys(getterObj).map(function (key) {
definePrototypeGetter(Constructor, key, getterObj[key]);
});
}
|
Define multiple getters on the Field prototype at once
@param {object} getterObj The getters with a getter at the key
|
definePrototypeGetters
|
javascript
|
keystonejs/keystone-classic
|
fields/utils/definePrototypeGetters.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/utils/definePrototypeGetters.js
|
MIT
|
function isObject (arg) {
return Object.prototype.toString.call(arg) === '[object Object]';
}
|
Checks if something is an object
@param {Any} arg The something we want to check the type of
@return {Boolean} If arg is an object or not
|
isObject
|
javascript
|
keystonejs/keystone-classic
|
fields/utils/evalDependsOn.js
|
https://github.com/keystonejs/keystone-classic/blob/master/fields/utils/evalDependsOn.js
|
MIT
|
Email = function (options) {
if (typeof options === 'string') {
options = { templateName: options };
}
if (!utils.isObject(options)) {
throw new Error('The keystone.Email class requires a templateName or options argument to be provided');
}
/**
* Keystone < 0.4 Compatibility
*
* NOTE: Add warnings and enable them in 4.1 or 4.2 release. These patterns
* will be deprecated with the 0.5 release!
*/
// keystome.set('email transport', 'sometransport') -> options.transport
var emailTransport = keystone.get('email transport');
if (!options.transport && emailTransport) {
options.transport = emailTransport;
}
// mandrill used to be the default; provide it if the api key is set
var mandrillApiKey = keystone.get('mandrill api key');
if (!options.transport && mandrillApiKey) {
options.transport = 'mandrill';
options.apiKey = mandrillApiKey;
}
// templateExt -> engine
if (!options.engine) {
options.engine = options.templateExt;
}
// keystone.set('view engine', 'something') -> engine
if (!options.engine) {
var customEngine = keystone.get('custom engine');
var viewEngine = keystone.get('view engine');
if (typeof customEngine === 'function') {
// when customEngine is a function, viewEngine is probably the extension
options.engine = customEngine;
options.ext = options.ext || options.templateExt || viewEngine;
} else if (viewEngine) {
// otherwise, default the email engine to keystone's view engine
options.engine = viewEngine;
}
}
// keystone.set('emails', 'rootpath') -> root
var rootPath = keystone.get('emails');
if (rootPath && !options.root) {
options.root = rootPath;
}
// Try to use the keystone-email package and throw if it hasn't been installed
// Can't use our global safeRequire here or none of the tests run
var KeystoneEmail = safeRequire('keystone-email', 'email');
// Create the new email instance with the template name and options
var templateName = options.templateName;
delete options.templateName;
var email = new KeystoneEmail(templateName, options);
// Make email.send backwards compatible with old argument signature
var send = email.send;
email.send = function () {
var args = [arguments[0]];
if (typeof arguments[1] === 'function') {
// map .send(options, callback) => .send(locals, options, callback)
// TOOD: Deprecate this call signature
args.push(arguments[0]);
args.push(arguments[1]);
} else {
// map .send(locals options, callback) => .send(locals, options, callback)
args.push(arguments[1]);
args.push(arguments[2]);
}
send.apply(email, args);
};
return email;
}
|
Email Class
===========
Helper class for sending emails with Mandrill.
New instances take a `templatePath` string which must be a folder in the
emails path, and must contain either `templateName/email.templateExt` or
`templateName.templateExt` which is used as the template for the HTML part
of the email.
Once created, emails can be rendered or sent.
Requires the `emails` path option and the `mandrill api key` option to be
set on Keystone.
@api public
|
Email
|
javascript
|
keystonejs/keystone-classic
|
lib/email.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/email.js
|
MIT
|
function hash (str) {
// force type
str = '' + str;
// get the first half
str = str.substr(0, Math.round(str.length / 2));
// hash using sha256
return crypto
.createHmac('sha256', keystone.get('cookie secret'))
.update(str)
.digest('base64')
.replace(/\=+$/, '');
}
|
Creates a hash of str with Keystone's cookie secret.
Only hashes the first half of the string.
|
hash
|
javascript
|
keystonejs/keystone-classic
|
lib/session.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/session.js
|
MIT
|
function signinWithUser (user, req, res, onSuccess) {
if (arguments.length < 4) {
throw new Error('keystone.session.signinWithUser requires user, req and res objects, and an onSuccess callback.');
}
if (typeof user !== 'object') {
throw new Error('keystone.session.signinWithUser requires user to be an object.');
}
if (typeof req !== 'object') {
throw new Error('keystone.session.signinWithUser requires req to be an object.');
}
if (typeof res !== 'object') {
throw new Error('keystone.session.signinWithUser requires res to be an object.');
}
if (typeof onSuccess !== 'function') {
throw new Error('keystone.session.signinWithUser requires onSuccess to be a function.');
}
req.session.regenerate(function () {
req.user = user;
req.session.userId = user.id;
// if the user has a password set, store a persistent cookie to resume sessions
if (keystone.get('cookie signin') && user.password) {
var userToken = user.id + ':' + hash(user.password);
var cookieOpts = _.defaults({}, keystone.get('cookie signin options'), {
signed: true,
httpOnly: true,
maxAge: 10 * 24 * 60 * 60 * 1000,
});
if (req.session.cookie) {
req.session.cookie.maxAge = cookieOpts.maxAge;
}
res.cookie('keystone.uid', userToken, cookieOpts);
}
onSuccess(user);
});
}
|
Signs in a user using user obejct
@param {Object} user - user object
@param {Object} req - express request object
@param {Object} res - express response object
@param {function()} onSuccess callback, is passed the User instance
|
signinWithUser
|
javascript
|
keystonejs/keystone-classic
|
lib/session.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/session.js
|
MIT
|
postHookedSigninWithUser = function (user, req, res, onSuccess, onFail) {
keystone.callHook(user, 'post:signin', req, function (err) {
if (err) {
return onFail(err);
}
exports.signinWithUser(user, req, res, onSuccess, onFail);
});
}
|
Signs in a user using user obejct
@param {Object} user - user object
@param {Object} req - express request object
@param {Object} res - express response object
@param {function()} onSuccess callback, is passed the User instance
|
postHookedSigninWithUser
|
javascript
|
keystonejs/keystone-classic
|
lib/session.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/session.js
|
MIT
|
doSignin = function (lookup, req, res, onSuccess, onFail) {
if (!lookup) {
return onFail(new Error('session.signin requires a User ID or Object as the first argument'));
}
var User = keystone.list(keystone.get('user model'));
if (typeof lookup.email === 'string' && typeof lookup.password === 'string') {
// ensure that it is an email, we don't want people being able to sign in by just using "\." and a haphazardly correct password.
if (!utils.isEmail(lookup.email)) {
return onFail(new Error('Incorrect email or password'));
}
// create regex for email lookup with special characters escaped
var emailRegExp = new RegExp('^' + utils.escapeRegExp(lookup.email) + '$', 'i');
// match email address and password
User.model.findOne({ email: emailRegExp }).exec(function (err, user) {
if (user) {
user._.password.compare(lookup.password, function (err, isMatch) {
if (!err && isMatch) {
postHookedSigninWithUser(user, req, res, onSuccess, onFail);
} else {
onFail(err || new Error('Incorrect email or password'));
}
});
} else {
onFail(err);
}
});
} else {
lookup = '' + lookup;
// match the userId, with optional password check
var userId = (lookup.indexOf(':') > 0) ? lookup.substr(0, lookup.indexOf(':')) : lookup;
var passwordCheck = (lookup.indexOf(':') > 0) ? lookup.substr(lookup.indexOf(':') + 1) : false;
User.model.findById(userId).exec(function (err, user) {
if (user && (!passwordCheck || scmp(passwordCheck, hash(user.password)))) {
postHookedSigninWithUser(user, req, res, onSuccess, onFail);
} else {
onFail(err || new Error('Incorrect user or password'));
}
});
}
}
|
Signs in a user user matching the lookup filters
@param {Object} lookup - must contain email and password
@param {Object} req - express request object
@param {Object} res - express response object
@param {function()} onSuccess callback, is passed the User instance
@param {function()} onFail callback
|
doSignin
|
javascript
|
keystonejs/keystone-classic
|
lib/session.js
|
https://github.com/keystonejs/keystone-classic/blob/master/lib/session.js
|
MIT
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.