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 createMatch(self, shift) {
var match = new Match(self, shift);
self.__compiled__[match.schema].normalize(match, self);
return match;
}
|
Match#url -> String
Normalized url of matched string.
|
createMatch
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function LinkifyIt(schemas) {
if (!(this instanceof LinkifyIt)) {
return new LinkifyIt(schemas);
}
// Cache last tested result. Used to skip repeating steps on next `match` call.
this.__index__ = -1;
this.__last_index__ = -1; // Next scan position
this.__schema__ = '';
this.__text_cache__ = '';
this.__schemas__ = assign({}, defaultSchemas, schemas);
this.__compiled__ = {};
this.__tlds__ = tlds_default;
this.__tlds_replaced__ = false;
this.re = {};
compile(this);
}
|
new LinkifyIt(schemas)
- schemas (Object): Optional. Additional schemas to validate (prefix/validator)
Creates new linkifier instance with optional additional schemas.
Can be called without `new` keyword for convenience.
By default understands:
- `http(s)://...` , `ftp://...`, `mailto:...` & `//...` links
- "fuzzy" links and emails (example.com, [email protected]).
`schemas` is an object, where each key/value describes protocol/rule:
- __key__ - link prefix (usually, protocol name with `:` at the end, `skype:`
for example). `linkify-it` makes shure that prefix is not preceeded with
alphanumeric char and symbols. Only whitespaces and punctuation allowed.
- __value__ - rule to check tail after link prefix
- _String_ - just alias to existing rule
- _Object_
- _validate_ - validator function (should return matched length on success),
or `RegExp`.
- _normalize_ - optional function to normalize text & url of matched result
(for example, for @twitter mentions).
|
LinkifyIt
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function getDecodeCache(exclude) {
var i, ch, cache = decodeCache[exclude];
if (cache) { return cache; }
cache = decodeCache[exclude] = [];
for (i = 0; i < 128; i++) {
ch = String.fromCharCode(i);
cache.push(ch);
}
for (i = 0; i < exclude.length; i++) {
ch = exclude.charCodeAt(i);
cache[ch] = '%' + ('0' + ch.toString(16).toUpperCase()).slice(-2);
}
return cache;
}
|
LinkifyIt#normalize(match)
Default normalizer (if schema does not define it's own).
|
getDecodeCache
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function decode(string, exclude) {
var cache;
if (typeof exclude !== 'string') {
exclude = decode.defaultChars;
}
cache = getDecodeCache(exclude);
return string.replace(/(%[a-f0-9]{2})+/gi, function(seq) {
var i, l, b1, b2, b3, b4, char,
result = '';
for (i = 0, l = seq.length; i < l; i += 3) {
b1 = parseInt(seq.slice(i + 1, i + 3), 16);
if (b1 < 0x80) {
result += cache[b1];
continue;
}
if ((b1 & 0xE0) === 0xC0 && (i + 3 < l)) {
// 110xxxxx 10xxxxxx
b2 = parseInt(seq.slice(i + 4, i + 6), 16);
if ((b2 & 0xC0) === 0x80) {
char = ((b1 << 6) & 0x7C0) | (b2 & 0x3F);
if (char < 0x80) {
result += '\ufffd\ufffd';
} else {
result += String.fromCharCode(char);
}
i += 3;
continue;
}
}
if ((b1 & 0xF0) === 0xE0 && (i + 6 < l)) {
// 1110xxxx 10xxxxxx 10xxxxxx
b2 = parseInt(seq.slice(i + 4, i + 6), 16);
b3 = parseInt(seq.slice(i + 7, i + 9), 16);
if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80) {
char = ((b1 << 12) & 0xF000) | ((b2 << 6) & 0xFC0) | (b3 & 0x3F);
if (char < 0x800 || (char >= 0xD800 && char <= 0xDFFF)) {
result += '\ufffd\ufffd\ufffd';
} else {
result += String.fromCharCode(char);
}
i += 6;
continue;
}
}
if ((b1 & 0xF8) === 0xF0 && (i + 9 < l)) {
// 111110xx 10xxxxxx 10xxxxxx 10xxxxxx
b2 = parseInt(seq.slice(i + 4, i + 6), 16);
b3 = parseInt(seq.slice(i + 7, i + 9), 16);
b4 = parseInt(seq.slice(i + 10, i + 12), 16);
if ((b2 & 0xC0) === 0x80 && (b3 & 0xC0) === 0x80 && (b4 & 0xC0) === 0x80) {
char = ((b1 << 18) & 0x1C0000) | ((b2 << 12) & 0x3F000) | ((b3 << 6) & 0xFC0) | (b4 & 0x3F);
if (char < 0x10000 || char > 0x10FFFF) {
result += '\ufffd\ufffd\ufffd\ufffd';
} else {
char -= 0x10000;
result += String.fromCharCode(0xD800 + (char >> 10), 0xDC00 + (char & 0x3FF));
}
i += 9;
continue;
}
}
result += '\ufffd';
}
return result;
});
}
|
LinkifyIt#normalize(match)
Default normalizer (if schema does not define it's own).
|
decode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function getEncodeCache(exclude) {
var i, ch, cache = encodeCache[exclude];
if (cache) { return cache; }
cache = encodeCache[exclude] = [];
for (i = 0; i < 128; i++) {
ch = String.fromCharCode(i);
if (/^[0-9a-z]$/i.test(ch)) {
// always allow unencoded alphanumeric characters
cache.push(ch);
} else {
cache.push('%' + ('0' + i.toString(16).toUpperCase()).slice(-2));
}
}
for (i = 0; i < exclude.length; i++) {
cache[exclude.charCodeAt(i)] = exclude[i];
}
return cache;
}
|
LinkifyIt#normalize(match)
Default normalizer (if schema does not define it's own).
|
getEncodeCache
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function encode(string, exclude, keepEscaped) {
var i, l, code, nextCode, cache,
result = '';
if (typeof exclude !== 'string') {
// encode(string, keepEscaped)
keepEscaped = exclude;
exclude = encode.defaultChars;
}
if (typeof keepEscaped === 'undefined') {
keepEscaped = true;
}
cache = getEncodeCache(exclude);
for (i = 0, l = string.length; i < l; i++) {
code = string.charCodeAt(i);
if (keepEscaped && code === 0x25 /* % */ && i + 2 < l) {
if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) {
result += string.slice(i, i + 3);
i += 2;
continue;
}
}
if (code < 128) {
result += cache[code];
continue;
}
if (code >= 0xD800 && code <= 0xDFFF) {
if (code >= 0xD800 && code <= 0xDBFF && i + 1 < l) {
nextCode = string.charCodeAt(i + 1);
if (nextCode >= 0xDC00 && nextCode <= 0xDFFF) {
result += encodeURIComponent(string[i] + string[i + 1]);
i++;
continue;
}
}
result += '%EF%BF%BD';
continue;
}
result += encodeURIComponent(string[i]);
}
return result;
}
|
LinkifyIt#normalize(match)
Default normalizer (if schema does not define it's own).
|
encode
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.pathname = null;
}
|
LinkifyIt#normalize(match)
Default normalizer (if schema does not define it's own).
|
Url
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
function urlParse(url, slashesDenoteHost) {
if (url && url instanceof Url) { return url; }
var u = new Url();
u.parse(url, slashesDenoteHost);
return u;
}
|
LinkifyIt#normalize(match)
Default normalizer (if schema does not define it's own).
|
urlParse
|
javascript
|
jbt/markdown-editor
|
lib/markdown-it.js
|
https://github.com/jbt/markdown-editor/blob/master/lib/markdown-it.js
|
ISC
|
arrayBufferToBase64 = buffer => {
let binary = '';
let bytes = [].slice.call(new Uint8Array(buffer.data.data));
bytes.forEach((b) => binary += String.fromCharCode(b));
return `data:${buffer.contentType};base64,${window.btoa(binary)}`;
}
|
base64.js
this helper formulate buffer data to base64 string
|
arrayBufferToBase64
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/base64.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/base64.js
|
MIT
|
arrayBufferToBase64 = buffer => {
let binary = '';
let bytes = [].slice.call(new Uint8Array(buffer.data.data));
bytes.forEach((b) => binary += String.fromCharCode(b));
return `data:${buffer.contentType};base64,${window.btoa(binary)}`;
}
|
base64.js
this helper formulate buffer data to base64 string
|
arrayBufferToBase64
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/base64.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/base64.js
|
MIT
|
formatDate = date => {
const newDate = new Date(date);
// const newDateOptions = {
// year: "numeric",
// month: "short",
// day: "numeric"
// };
return newDate.toLocaleDateString('en-US', dateOptions);
}
|
date.js
this helper formulate date
|
formatDate
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/date.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/date.js
|
MIT
|
formatDate = date => {
const newDate = new Date(date);
// const newDateOptions = {
// year: "numeric",
// month: "short",
// day: "numeric"
// };
return newDate.toLocaleDateString('en-US', dateOptions);
}
|
date.js
this helper formulate date
|
formatDate
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/date.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/date.js
|
MIT
|
formatTime = date => {
const newDate = new Date(date);
return newDate.toLocaleTimeString(undefined, timeOptions);
}
|
date.js
this helper formulate date
|
formatTime
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/date.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/date.js
|
MIT
|
formatTime = date => {
const newDate = new Date(date);
return newDate.toLocaleTimeString(undefined, timeOptions);
}
|
date.js
this helper formulate date
|
formatTime
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/date.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/date.js
|
MIT
|
handleError = (err, dispatch, title = '') => {
const unsuccessfulOptions = {
title: `${title}`,
message: ``,
position: 'tr',
autoDismiss: 1
};
if (err.response) {
if (err.response.status === 400) {
unsuccessfulOptions.title = title ? title : 'Please Try Again!';
unsuccessfulOptions.message = err.response.data.error;
dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 404) {
// unsuccessfulOptions.title =
// err.response.data.message ||
// 'Your request could not be processed. Please try again.';
// dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 401) {
unsuccessfulOptions.message = 'Unauthorized Access! Please login again';
dispatch(signOut());
dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 403) {
unsuccessfulOptions.message =
'Forbidden! You are not allowed to access this resource.';
dispatch(error(unsuccessfulOptions));
}
} else if (err.message) {
unsuccessfulOptions.message = err.message;
dispatch(error(unsuccessfulOptions));
} else {
// fallback
unsuccessfulOptions.message =
'Your request could not be processed. Please try again.';
}
}
|
error.js
This is a generic error handler, it receives the error returned from the server and present it on a pop up
|
handleError
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/error.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/error.js
|
MIT
|
handleError = (err, dispatch, title = '') => {
const unsuccessfulOptions = {
title: `${title}`,
message: ``,
position: 'tr',
autoDismiss: 1
};
if (err.response) {
if (err.response.status === 400) {
unsuccessfulOptions.title = title ? title : 'Please Try Again!';
unsuccessfulOptions.message = err.response.data.error;
dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 404) {
// unsuccessfulOptions.title =
// err.response.data.message ||
// 'Your request could not be processed. Please try again.';
// dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 401) {
unsuccessfulOptions.message = 'Unauthorized Access! Please login again';
dispatch(signOut());
dispatch(error(unsuccessfulOptions));
} else if (err.response.status === 403) {
unsuccessfulOptions.message =
'Forbidden! You are not allowed to access this resource.';
dispatch(error(unsuccessfulOptions));
}
} else if (err.message) {
unsuccessfulOptions.message = err.message;
dispatch(error(unsuccessfulOptions));
} else {
// fallback
unsuccessfulOptions.message =
'Your request could not be processed. Please try again.';
}
}
|
error.js
This is a generic error handler, it receives the error returned from the server and present it on a pop up
|
handleError
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/error.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/error.js
|
MIT
|
formatSelectOptions = (data, empty = false, from) => {
let newSelectOptions = [];
if (data && data.length > 0) {
data.map(option => {
let newOption = {};
newOption.value = option._id;
newOption.label = option.name;
newSelectOptions.push(newOption);
});
}
if (empty) {
const emptyOption = {
value: 0,
label: 'No option selected'
};
newSelectOptions.unshift(emptyOption);
}
return newSelectOptions;
}
|
select.js
this helper formulate data into select options
|
formatSelectOptions
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/select.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/select.js
|
MIT
|
formatSelectOptions = (data, empty = false, from) => {
let newSelectOptions = [];
if (data && data.length > 0) {
data.map(option => {
let newOption = {};
newOption.value = option._id;
newOption.label = option.name;
newSelectOptions.push(newOption);
});
}
if (empty) {
const emptyOption = {
value: 0,
label: 'No option selected'
};
newSelectOptions.unshift(emptyOption);
}
return newSelectOptions;
}
|
select.js
this helper formulate data into select options
|
formatSelectOptions
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/select.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/select.js
|
MIT
|
unformatSelectOptions = data => {
if (!data) return null;
let newSelectOptions = [];
if (data && data.length > 0) {
data.map(option => {
let newOption = {};
newOption._id = option.value;
newSelectOptions.push(newOption._id);
});
}
return newSelectOptions;
}
|
select.js
this helper formulate data into select options
|
unformatSelectOptions
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/select.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/select.js
|
MIT
|
unformatSelectOptions = data => {
if (!data) return null;
let newSelectOptions = [];
if (data && data.length > 0) {
data.map(option => {
let newOption = {};
newOption._id = option.value;
newSelectOptions.push(newOption._id);
});
}
return newSelectOptions;
}
|
select.js
this helper formulate data into select options
|
unformatSelectOptions
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/select.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/select.js
|
MIT
|
setToken = token => {
if (token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
delete axios.defaults.headers.common['Authorization'];
}
}
|
token.js
axios default headers setup
|
setToken
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/token.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/token.js
|
MIT
|
setToken = token => {
if (token) {
axios.defaults.headers.common['Authorization'] = token;
} else {
delete axios.defaults.headers.common['Authorization'];
}
}
|
token.js
axios default headers setup
|
setToken
|
javascript
|
mohamedsamara/mern-ecommerce
|
client/app/utils/token.js
|
https://github.com/mohamedsamara/mern-ecommerce/blob/master/client/app/utils/token.js
|
MIT
|
Tagging = function( elem, options ) {
this.elem = elem; // The tag box
this.$elem = $( elem ); // jQuerify tag box
this.options = options; // JS custom options
this.tags = []; // Here we store all tags
// this.$type_zone = void 0; // The tag box's input zone
}
|
taggingJS Constructor
@param obj elem DOM object of tag box
@param obj options Custom JS options
|
Tagging
|
javascript
|
sniperwolf/taggingJS
|
tagging.js
|
https://github.com/sniperwolf/taggingJS/blob/master/tagging.js
|
MIT
|
Tagging = function( elem, options ) {
this.elem = elem; // The tag box
this.$elem = $( elem ); // jQuerify tag box
this.options = options; // JS custom options
this.tags = []; // Here we store all tags
// this.$type_zone = void 0; // The tag box's input zone
}
|
taggingJS Constructor
@param obj elem DOM object of tag box
@param obj options Custom JS options
|
Tagging
|
javascript
|
sniperwolf/taggingJS
|
example/tagging.js
|
https://github.com/sniperwolf/taggingJS/blob/master/example/tagging.js
|
MIT
|
function _applyAttrs(context, attrs) {
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
context.setAttribute(attr, attrs[attr]);
}
}
}
|
Applies attributes to a DOM object
@param {object} context The DOM obj you want to apply the attributes to
@param {object} attrs A key/value pair of attributes you want to apply
@returns {undefined}
|
_applyAttrs
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _applyStyles(context, attrs) {
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
context.style[attr] = attrs[attr];
}
}
}
|
Applies styles to a DOM object
@param {object} context The DOM obj you want to apply the attributes to
@param {object} attrs A key/value pair of attributes you want to apply
@returns {undefined}
|
_applyStyles
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _getStyle(el, styleProp) {
var x = el
, y = null;
if (window.getComputedStyle) {
y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
}
else if (x.currentStyle) {
y = x.currentStyle[styleProp];
}
return y;
}
|
Returns a DOM objects computed style
@param {object} el The element you want to get the style from
@param {string} styleProp The property you want to get from the element
@returns {string} Returns a string of the value. If property is not set it will return a blank string
|
_getStyle
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _saveStyleState(el, type, styles) {
var returnState = {}
, style;
if (type === 'save') {
for (style in styles) {
if (styles.hasOwnProperty(style)) {
returnState[style] = _getStyle(el, style);
}
}
// After it's all done saving all the previous states, change the styles
_applyStyles(el, styles);
}
else if (type === 'apply') {
_applyStyles(el, styles);
}
return returnState;
}
|
Saves the current style state for the styles requested, then applies styles
to overwrite the existing one. The old styles are returned as an object so
you can pass it back in when you want to revert back to the old style
@param {object} el The element to get the styles of
@param {string} type Can be "save" or "apply". apply will just apply styles you give it. Save will write styles
@param {object} styles Key/value style/property pairs
@returns {object}
|
_saveStyleState
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _outerWidth(el) {
var b = parseInt(_getStyle(el, 'border-left-width'), 10) + parseInt(_getStyle(el, 'border-right-width'), 10)
, p = parseInt(_getStyle(el, 'padding-left'), 10) + parseInt(_getStyle(el, 'padding-right'), 10)
, w = el.offsetWidth
, t;
// For IE in case no border is set and it defaults to "medium"
if (isNaN(b)) { b = 0; }
t = b + p + w;
return t;
}
|
Gets an elements total width including it's borders and padding
@param {object} el The element to get the total width of
@returns {int}
|
_outerWidth
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _outerHeight(el) {
var b = parseInt(_getStyle(el, 'border-top-width'), 10) + parseInt(_getStyle(el, 'border-bottom-width'), 10)
, p = parseInt(_getStyle(el, 'padding-top'), 10) + parseInt(_getStyle(el, 'padding-bottom'), 10)
, w = parseInt(_getStyle(el, 'height'), 10)
, t;
// For IE in case no border is set and it defaults to "medium"
if (isNaN(b)) { b = 0; }
t = b + p + w;
return t;
}
|
Gets an elements total height including it's borders and padding
@param {object} el The element to get the total width of
@returns {int}
|
_outerHeight
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _insertCSSLink(path, context, id) {
id = id || '';
var headID = context.getElementsByTagName("head")[0]
, cssNode = context.createElement('link');
_applyAttrs(cssNode, {
type: 'text/css'
, id: id
, rel: 'stylesheet'
, href: path
, name: path
, media: 'screen'
});
headID.appendChild(cssNode);
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_insertCSSLink
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _replaceClass(e, o, n) {
e.className = e.className.replace(o, n);
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_replaceClass
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _getIframeInnards(el) {
return el.contentDocument || el.contentWindow.document;
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_getIframeInnards
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _getText(el) {
var theText;
// Make sure to check for type of string because if the body of the page
// doesn't have any text it'll be "" which is falsey and will go into
// the else which is meant for Firefox and shit will break
if (typeof document.body.innerText == 'string') {
theText = el.innerText;
}
else {
// First replace <br>s before replacing the rest of the HTML
theText = el.innerHTML.replace(/<br>/gi, "\n");
// Now we can clean the HTML
theText = theText.replace(/<(?:.|\n)*?>/gm, '');
// Now fix HTML entities
theText = theText.replace(/</gi, '<');
theText = theText.replace(/>/gi, '>');
}
return theText;
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_getText
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _setText(el, content) {
// Don't convert lt/gt characters as HTML when viewing the editor window
// TODO: Write a test to catch regressions for this
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
content = content.replace(/\n/g, '<br>');
// Make sure to there aren't two spaces in a row (replace one with )
// If you find and replace every space with a text will not wrap.
// Hence the name (Non-Breaking-SPace).
// TODO: Probably need to test this somehow...
content = content.replace(/<br>\s/g, '<br> ')
content = content.replace(/\s\s\s/g, ' ')
content = content.replace(/\s\s/g, ' ')
content = content.replace(/^ /, ' ')
el.innerHTML = content;
return true;
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_setText
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _sanitizeRawContent(content) {
// Get this, 2 spaces in a content editable actually converts to:
// 0020 00a0, meaning, "space no-break space". So, manually convert
// no-break spaces to spaces again before handing to marked.
// Also, WebKit converts no-break to unicode equivalent and FF HTML.
return content.replace(/\u00a0/g, ' ').replace(/ /g, ' ');
}
|
Converts the 'raw' format of a file's contents into plaintext
@param {string} content Contents of the file
@returns {string} the sanitized content
|
_sanitizeRawContent
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _isIE() {
var rv = -1 // Return value assumes failure.
, ua = navigator.userAgent
, re;
if (navigator.appName == 'Microsoft Internet Explorer') {
re = /MSIE ([0-9]{1,}[\.0-9]{0,})/;
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1, 10);
}
}
return rv;
}
|
Will return the version number if the browser is IE. If not will return -1
TRY NEVER TO USE THIS AND USE FEATURE DETECTION IF POSSIBLE
@returns {Number} -1 if false or the version number if true
|
_isIE
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _isSafari() {
var n = window.navigator;
return n.userAgent.indexOf('Safari') > -1 && n.userAgent.indexOf('Chrome') == -1;
}
|
Same as the isIE(), but simply returns a boolean
THIS IS TERRIBLE AND IS ONLY USED BECAUSE FULLSCREEN IN SAFARI IS BORKED
If some other engine uses WebKit and has support for fullscreen they
probably wont get native fullscreen until Safari's fullscreen is fixed
@returns {Boolean} true if Safari
|
_isSafari
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _isFirefox() {
var n = window.navigator;
return n.userAgent.indexOf('Firefox') > -1 && n.userAgent.indexOf('Seamonkey') == -1;
}
|
Same as the isIE(), but simply returns a boolean
THIS IS TERRIBLE ONLY USE IF ABSOLUTELY NEEDED
@returns {Boolean} true if Safari
|
_isFirefox
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
|
Determines if supplied value is a function
@param {object} object to determine type
|
_isFunction
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _mergeObjs() {
// copy reference to target object
var target = arguments[0] || {}
, i = 1
, length = arguments.length
, deep = false
, options
, name
, src
, copy
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !_isFunction(target)) {
target = {};
}
// extend jQuery itself if only one argument is passed
if (length === i) {
target = this;
--i;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
// @NOTE: added hasOwnProperty check
if (options.hasOwnProperty(name)) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging object values
if (deep && copy && typeof copy === "object" && !copy.nodeType) {
target[name] = _mergeObjs(deep,
// Never move original objects, clone them
src || (copy.length != null ? [] : {})
, copy);
} else if (copy !== undefined) { // Don't bring in undefined values
target[name] = copy;
}
}
}
}
}
// Return the modified object
return target;
}
|
Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
@param {boolean} [deepMerge=false] If true, will deep merge meaning it will merge sub-objects like {obj:obj2{foo:'bar'}}
@param {object} first object
@param {object} second object
@returnss {object} a new object based on obj1 and obj2
|
_mergeObjs
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function EpicEditor(options) {
// Default settings will be overwritten/extended by options arg
var self = this
, opts = options || {}
, _defaultFileSchema
, _defaultFile
, defaults = { container: 'epiceditor'
, basePath: 'epiceditor'
, textarea: undefined
, clientSideStorage: true
, localStorageName: 'epiceditor'
, useNativeFullscreen: true
, file: { name: null
, defaultContent: ''
, autoSave: 100 // Set to false for no auto saving
}
, theme: { base: '/themes/base/epiceditor.css'
, preview: '/themes/preview/github.css'
, editor: '/themes/editor/epic-dark.css'
}
, focusOnLoad: false
, shortcut: { modifier: 18 // alt keycode
, fullscreen: 70 // f keycode
, preview: 80 // p keycode
}
, string: { togglePreview: 'Toggle Preview Mode'
, toggleEdit: 'Toggle Edit Mode'
, toggleFullscreen: 'Enter Fullscreen'
}
, parser: typeof marked == 'function' ? marked : null
, autogrow: false
, button: { fullscreen: true
, preview: true
, bar: "auto"
}
}
, defaultStorage
, autogrowDefaults = { minHeight: 80
, maxHeight: false
, scroll: true
};
self.settings = _mergeObjs(true, defaults, opts);
var buttons = self.settings.button;
self._fullscreenEnabled = typeof(buttons) === 'object' ? typeof buttons.fullscreen === 'undefined' || buttons.fullscreen : buttons === true;
self._editEnabled = typeof(buttons) === 'object' ? typeof buttons.edit === 'undefined' || buttons.edit : buttons === true;
self._previewEnabled = typeof(buttons) === 'object' ? typeof buttons.preview === 'undefined' || buttons.preview : buttons === true;
if (!(typeof self.settings.parser == 'function' && typeof self.settings.parser('TEST') == 'string')) {
self.settings.parser = function (str) {
return str;
}
}
if (self.settings.autogrow) {
if (self.settings.autogrow === true) {
self.settings.autogrow = autogrowDefaults;
}
else {
self.settings.autogrow = _mergeObjs(true, autogrowDefaults, self.settings.autogrow);
}
self._oldHeight = -1;
}
// If you put an absolute link as the path of any of the themes ignore the basePath
// preview theme
if (!self.settings.theme.preview.match(/^https?:\/\//)) {
self.settings.theme.preview = self.settings.basePath + self.settings.theme.preview;
}
// editor theme
if (!self.settings.theme.editor.match(/^https?:\/\//)) {
self.settings.theme.editor = self.settings.basePath + self.settings.theme.editor;
}
// base theme
if (!self.settings.theme.base.match(/^https?:\/\//)) {
self.settings.theme.base = self.settings.basePath + self.settings.theme.base;
}
// Grab the container element and save it to self.element
// if it's a string assume it's an ID and if it's an object
// assume it's a DOM element
if (typeof self.settings.container == 'string') {
self.element = document.getElementById(self.settings.container);
}
else if (typeof self.settings.container == 'object') {
self.element = self.settings.container;
}
if (typeof self.settings.textarea == 'undefined' && typeof self.element != 'undefined') {
var textareas = self.element.getElementsByTagName('textarea');
if (textareas.length > 0) {
self.settings.textarea = textareas[0];
_applyStyles(self.settings.textarea, {
display: 'none'
});
}
}
// Figure out the file name. If no file name is given we'll use the ID.
// If there's no ID either we'll use a namespaced file name that's incremented
// based on the calling order. As long as it doesn't change, drafts will be saved.
if (!self.settings.file.name) {
if (typeof self.settings.container == 'string') {
self.settings.file.name = self.settings.container;
}
else if (typeof self.settings.container == 'object') {
if (self.element.id) {
self.settings.file.name = self.element.id;
}
else {
if (!EpicEditor._data.unnamedEditors) {
EpicEditor._data.unnamedEditors = [];
}
EpicEditor._data.unnamedEditors.push(self);
self.settings.file.name = '__epiceditor-untitled-' + EpicEditor._data.unnamedEditors.length;
}
}
}
if (self.settings.button.bar === "show") {
self.settings.button.bar = true;
}
if (self.settings.button.bar === "hide") {
self.settings.button.bar = false;
}
// Protect the id and overwrite if passed in as an option
// TODO: Put underscrore to denote that this is private
self._instanceId = 'epiceditor-' + Math.round(Math.random() * 100000);
self._storage = {};
self._canSave = true;
// Setup local storage of files
self._defaultFileSchema = function () {
return {
content: self.settings.file.defaultContent
, created: new Date()
, modified: new Date()
}
}
if (localStorage && self.settings.clientSideStorage) {
this._storage = localStorage;
if (this._storage[self.settings.localStorageName] && self.getFiles(self.settings.file.name) === undefined) {
_defaultFile = self._defaultFileSchema();
_defaultFile.content = self.settings.file.defaultContent;
}
}
if (!this._storage[self.settings.localStorageName]) {
defaultStorage = {};
defaultStorage[self.settings.file.name] = self._defaultFileSchema();
defaultStorage = JSON.stringify(defaultStorage);
this._storage[self.settings.localStorageName] = defaultStorage;
}
// A string to prepend files with to save draft versions of files
// and reset all preview drafts on each load!
self._previewDraftLocation = '__draft-';
self._storage[self._previewDraftLocation + self.settings.localStorageName] = self._storage[self.settings.localStorageName];
// This needs to replace the use of classes to check the state of EE
self._eeState = {
fullscreen: false
, preview: false
, edit: false
, loaded: false
, unloaded: false
}
// Now that it exists, allow binding of events if it doesn't exist yet
if (!self.events) {
self.events = {};
}
return this;
}
|
Initiates the EpicEditor object and sets up offline storage as well
@class Represents an EpicEditor instance
@param {object} options An optional customization object
@returns {object} EpicEditor will be returned
|
EpicEditor
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function utilBarHandler(e) {
if (self.settings.button.bar !== "auto") {
return;
}
// Here we check if the mouse has moves more than 5px in any direction before triggering the mousemove code
// we do this for 2 reasons:
// 1. On Mac OS X lion when you scroll and it does the iOS like "jump" when it hits the top/bottom of the page itll fire off
// a mousemove of a few pixels depending on how hard you scroll
// 2. We give a slight buffer to the user in case he barely touches his touchpad or mouse and not trigger the UI
if (Math.abs(mousePos.y - e.pageY) >= 5 || Math.abs(mousePos.x - e.pageX) >= 5) {
utilBar.style.display = 'block';
// if we have a timer already running, kill it out
if (utilBarTimer) {
clearTimeout(utilBarTimer);
}
// begin a new timer that hides our object after 1000 ms
utilBarTimer = window.setTimeout(function () {
utilBar.style.display = 'none';
}, 1000);
}
mousePos = { y: e.pageY, x: e.pageX };
}
|
Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
@returns {object} EpicEditor will be returned
|
utilBarHandler
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function shortcutHandler(e) {
if (e.keyCode == self.settings.shortcut.modifier) { isMod = true } // check for modifier press(default is alt key), save to var
if (e.keyCode == 17) { isCtrl = true } // check for ctrl/cmnd press, in order to catch ctrl/cmnd + s
if (e.keyCode == 18) { isCtrl = false }
// Check for alt+p and make sure were not in fullscreen - default shortcut to switch to preview
if (isMod === true && e.keyCode == self.settings.shortcut.preview && !self.is('fullscreen')) {
e.preventDefault();
if (self.is('edit') && self._previewEnabled) {
self.preview();
}
else if (self._editEnabled) {
self.edit();
}
}
// Check for alt+f - default shortcut to make editor fullscreen
if (isMod === true && e.keyCode == self.settings.shortcut.fullscreen && self._fullscreenEnabled) {
e.preventDefault();
self._goFullscreen(fsElement);
}
// Set the modifier key to false once *any* key combo is completed
// or else, on Windows, hitting the alt key will lock the isMod state to true (ticket #133)
if (isMod === true && e.keyCode !== self.settings.shortcut.modifier) {
isMod = false;
}
// When a user presses "esc", revert everything!
if (e.keyCode == 27 && self.is('fullscreen')) {
self._exitFullscreen(fsElement);
}
// Check for ctrl + s (since a lot of people do it out of habit) and make it do nothing
if (isCtrl === true && e.keyCode == 83) {
self.save();
e.preventDefault();
isCtrl = false;
}
// Do the same for Mac now (metaKey == cmd).
if (e.metaKey && e.keyCode == 83) {
self.save();
e.preventDefault();
}
}
|
Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
@returns {object} EpicEditor will be returned
|
shortcutHandler
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function shortcutUpHandler(e) {
if (e.keyCode == self.settings.shortcut.modifier) { isMod = false }
if (e.keyCode == 17) { isCtrl = false }
}
|
Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
@returns {object} EpicEditor will be returned
|
shortcutUpHandler
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function pasteHandler(e) {
var content;
if (e.clipboardData) {
//FF 22, Webkit, "standards"
e.preventDefault();
content = e.clipboardData.getData("text/plain");
self.editorIframeDocument.execCommand("insertText", false, content);
}
else if (window.clipboardData) {
//IE, "nasty"
e.preventDefault();
content = window.clipboardData.getData("Text");
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
content = content.replace(/\n/g, '<br>');
content = content.replace(/\r/g, ''); //fuck you, ie!
content = content.replace(/<br>\s/g, '<br> ')
content = content.replace(/\s\s\s/g, ' ')
content = content.replace(/\s\s/g, ' ')
self.editorIframeDocument.selection.createRange().pasteHTML(content);
}
}
|
Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
@returns {object} EpicEditor will be returned
|
pasteHandler
|
javascript
|
OscarGodson/EpicEditor
|
epiceditor/js/epiceditor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/epiceditor/js/epiceditor.js
|
MIT
|
function _applyAttrs(context, attrs) {
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
context.setAttribute(attr, attrs[attr]);
}
}
}
|
Applies attributes to a DOM object
@param {object} context The DOM obj you want to apply the attributes to
@param {object} attrs A key/value pair of attributes you want to apply
@returns {undefined}
|
_applyAttrs
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _applyStyles(context, attrs) {
for (var attr in attrs) {
if (attrs.hasOwnProperty(attr)) {
context.style[attr] = attrs[attr];
}
}
}
|
Applies styles to a DOM object
@param {object} context The DOM obj you want to apply the attributes to
@param {object} attrs A key/value pair of attributes you want to apply
@returns {undefined}
|
_applyStyles
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _getStyle(el, styleProp) {
var x = el
, y = null;
if (window.getComputedStyle) {
y = document.defaultView.getComputedStyle(x, null).getPropertyValue(styleProp);
}
else if (x.currentStyle) {
y = x.currentStyle[styleProp];
}
return y;
}
|
Returns a DOM objects computed style
@param {object} el The element you want to get the style from
@param {string} styleProp The property you want to get from the element
@returns {string} Returns a string of the value. If property is not set it will return a blank string
|
_getStyle
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _saveStyleState(el, type, styles) {
var returnState = {}
, style;
if (type === 'save') {
for (style in styles) {
if (styles.hasOwnProperty(style)) {
returnState[style] = _getStyle(el, style);
}
}
// After it's all done saving all the previous states, change the styles
_applyStyles(el, styles);
}
else if (type === 'apply') {
_applyStyles(el, styles);
}
return returnState;
}
|
Saves the current style state for the styles requested, then applies styles
to overwrite the existing one. The old styles are returned as an object so
you can pass it back in when you want to revert back to the old style
@param {object} el The element to get the styles of
@param {string} type Can be "save" or "apply". apply will just apply styles you give it. Save will write styles
@param {object} styles Key/value style/property pairs
@returns {object}
|
_saveStyleState
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _outerWidth(el) {
var b = parseInt(_getStyle(el, 'border-left-width'), 10) + parseInt(_getStyle(el, 'border-right-width'), 10)
, p = parseInt(_getStyle(el, 'padding-left'), 10) + parseInt(_getStyle(el, 'padding-right'), 10)
, w = el.offsetWidth
, t;
// For IE in case no border is set and it defaults to "medium"
if (isNaN(b)) { b = 0; }
t = b + p + w;
return t;
}
|
Gets an elements total width including it's borders and padding
@param {object} el The element to get the total width of
@returns {int}
|
_outerWidth
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _outerHeight(el) {
var b = parseInt(_getStyle(el, 'border-top-width'), 10) + parseInt(_getStyle(el, 'border-bottom-width'), 10)
, p = parseInt(_getStyle(el, 'padding-top'), 10) + parseInt(_getStyle(el, 'padding-bottom'), 10)
, w = parseInt(_getStyle(el, 'height'), 10)
, t;
// For IE in case no border is set and it defaults to "medium"
if (isNaN(b)) { b = 0; }
t = b + p + w;
return t;
}
|
Gets an elements total height including it's borders and padding
@param {object} el The element to get the total width of
@returns {int}
|
_outerHeight
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _insertCSSLink(path, context, id) {
id = id || '';
var headID = context.getElementsByTagName("head")[0]
, cssNode = context.createElement('link');
_applyAttrs(cssNode, {
type: 'text/css'
, id: id
, rel: 'stylesheet'
, href: path
, name: path
, media: 'screen'
});
headID.appendChild(cssNode);
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_insertCSSLink
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _replaceClass(e, o, n) {
e.className = e.className.replace(o, n);
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_replaceClass
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _getIframeInnards(el) {
return el.contentDocument || el.contentWindow.document;
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_getIframeInnards
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _getText(el) {
var theText;
// Make sure to check for type of string because if the body of the page
// doesn't have any text it'll be "" which is falsey and will go into
// the else which is meant for Firefox and shit will break
if (typeof document.body.innerText == 'string') {
theText = el.innerText;
}
else {
// First replace <br>s before replacing the rest of the HTML
theText = el.innerHTML.replace(/<br>/gi, "\n");
// Now we can clean the HTML
theText = theText.replace(/<(?:.|\n)*?>/gm, '');
// Now fix HTML entities
theText = theText.replace(/</gi, '<');
theText = theText.replace(/>/gi, '>');
}
return theText;
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_getText
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _setText(el, content) {
// Don't convert lt/gt characters as HTML when viewing the editor window
// TODO: Write a test to catch regressions for this
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
content = content.replace(/\n/g, '<br>');
// Make sure to there aren't two spaces in a row (replace one with )
// If you find and replace every space with a text will not wrap.
// Hence the name (Non-Breaking-SPace).
// TODO: Probably need to test this somehow...
content = content.replace(/<br>\s/g, '<br> ')
content = content.replace(/\s\s\s/g, ' ')
content = content.replace(/\s\s/g, ' ')
content = content.replace(/^ /, ' ')
el.innerHTML = content;
return true;
}
|
Inserts a <link> tag specifically for CSS
@param {string} path The path to the CSS file
@param {object} context In what context you want to apply this to (document, iframe, etc)
@param {string} id An id for you to reference later for changing properties of the <link>
@returns {undefined}
|
_setText
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _sanitizeRawContent(content) {
// Get this, 2 spaces in a content editable actually converts to:
// 0020 00a0, meaning, "space no-break space". So, manually convert
// no-break spaces to spaces again before handing to marked.
// Also, WebKit converts no-break to unicode equivalent and FF HTML.
return content.replace(/\u00a0/g, ' ').replace(/ /g, ' ');
}
|
Converts the 'raw' format of a file's contents into plaintext
@param {string} content Contents of the file
@returns {string} the sanitized content
|
_sanitizeRawContent
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _isIE() {
var rv = -1 // Return value assumes failure.
, ua = navigator.userAgent
, re;
if (navigator.appName == 'Microsoft Internet Explorer') {
re = /MSIE ([0-9]{1,}[\.0-9]{0,})/;
if (re.exec(ua) != null) {
rv = parseFloat(RegExp.$1, 10);
}
}
return rv;
}
|
Will return the version number if the browser is IE. If not will return -1
TRY NEVER TO USE THIS AND USE FEATURE DETECTION IF POSSIBLE
@returns {Number} -1 if false or the version number if true
|
_isIE
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _isSafari() {
var n = window.navigator;
return n.userAgent.indexOf('Safari') > -1 && n.userAgent.indexOf('Chrome') == -1;
}
|
Same as the isIE(), but simply returns a boolean
THIS IS TERRIBLE AND IS ONLY USED BECAUSE FULLSCREEN IN SAFARI IS BORKED
If some other engine uses WebKit and has support for fullscreen they
probably wont get native fullscreen until Safari's fullscreen is fixed
@returns {Boolean} true if Safari
|
_isSafari
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _isFirefox() {
var n = window.navigator;
return n.userAgent.indexOf('Firefox') > -1 && n.userAgent.indexOf('Seamonkey') == -1;
}
|
Same as the isIE(), but simply returns a boolean
THIS IS TERRIBLE ONLY USE IF ABSOLUTELY NEEDED
@returns {Boolean} true if Safari
|
_isFirefox
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _isFunction(functionToCheck) {
var getType = {};
return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]';
}
|
Determines if supplied value is a function
@param {object} object to determine type
|
_isFunction
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function _mergeObjs() {
// copy reference to target object
var target = arguments[0] || {}
, i = 1
, length = arguments.length
, deep = false
, options
, name
, src
, copy
// Handle a deep copy situation
if (typeof target === "boolean") {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if (typeof target !== "object" && !_isFunction(target)) {
target = {};
}
// extend jQuery itself if only one argument is passed
if (length === i) {
target = this;
--i;
}
for (; i < length; i++) {
// Only deal with non-null/undefined values
if ((options = arguments[i]) != null) {
// Extend the base object
for (name in options) {
// @NOTE: added hasOwnProperty check
if (options.hasOwnProperty(name)) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target === copy) {
continue;
}
// Recurse if we're merging object values
if (deep && copy && typeof copy === "object" && !copy.nodeType) {
target[name] = _mergeObjs(deep,
// Never move original objects, clone them
src || (copy.length != null ? [] : {})
, copy);
} else if (copy !== undefined) { // Don't bring in undefined values
target[name] = copy;
}
}
}
}
}
// Return the modified object
return target;
}
|
Overwrites obj1's values with obj2's and adds obj2's if non existent in obj1
@param {boolean} [deepMerge=false] If true, will deep merge meaning it will merge sub-objects like {obj:obj2{foo:'bar'}}
@param {object} first object
@param {object} second object
@returnss {object} a new object based on obj1 and obj2
|
_mergeObjs
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function EpicEditor(options) {
// Default settings will be overwritten/extended by options arg
var self = this
, opts = options || {}
, _defaultFileSchema
, _defaultFile
, defaults = { container: 'epiceditor'
, basePath: 'epiceditor'
, textarea: undefined
, clientSideStorage: true
, localStorageName: 'epiceditor'
, useNativeFullscreen: true
, file: { name: null
, defaultContent: ''
, autoSave: 100 // Set to false for no auto saving
}
, theme: { base: '/themes/base/epiceditor.css'
, preview: '/themes/preview/github.css'
, editor: '/themes/editor/epic-dark.css'
}
, focusOnLoad: false
, shortcut: { modifier: 18 // alt keycode
, fullscreen: 70 // f keycode
, preview: 80 // p keycode
}
, string: { togglePreview: 'Toggle Preview Mode'
, toggleEdit: 'Toggle Edit Mode'
, toggleFullscreen: 'Enter Fullscreen'
}
, parser: typeof marked == 'function' ? marked : null
, autogrow: false
, button: { fullscreen: true
, preview: true
, bar: "auto"
}
}
, defaultStorage
, autogrowDefaults = { minHeight: 80
, maxHeight: false
, scroll: true
};
self.settings = _mergeObjs(true, defaults, opts);
var buttons = self.settings.button;
self._fullscreenEnabled = typeof(buttons) === 'object' ? typeof buttons.fullscreen === 'undefined' || buttons.fullscreen : buttons === true;
self._editEnabled = typeof(buttons) === 'object' ? typeof buttons.edit === 'undefined' || buttons.edit : buttons === true;
self._previewEnabled = typeof(buttons) === 'object' ? typeof buttons.preview === 'undefined' || buttons.preview : buttons === true;
if (!(typeof self.settings.parser == 'function' && typeof self.settings.parser('TEST') == 'string')) {
self.settings.parser = function (str) {
return str;
}
}
if (self.settings.autogrow) {
if (self.settings.autogrow === true) {
self.settings.autogrow = autogrowDefaults;
}
else {
self.settings.autogrow = _mergeObjs(true, autogrowDefaults, self.settings.autogrow);
}
self._oldHeight = -1;
}
// If you put an absolute link as the path of any of the themes ignore the basePath
// preview theme
if (!self.settings.theme.preview.match(/^https?:\/\//)) {
self.settings.theme.preview = self.settings.basePath + self.settings.theme.preview;
}
// editor theme
if (!self.settings.theme.editor.match(/^https?:\/\//)) {
self.settings.theme.editor = self.settings.basePath + self.settings.theme.editor;
}
// base theme
if (!self.settings.theme.base.match(/^https?:\/\//)) {
self.settings.theme.base = self.settings.basePath + self.settings.theme.base;
}
// Grab the container element and save it to self.element
// if it's a string assume it's an ID and if it's an object
// assume it's a DOM element
if (typeof self.settings.container == 'string') {
self.element = document.getElementById(self.settings.container);
}
else if (typeof self.settings.container == 'object') {
self.element = self.settings.container;
}
if (typeof self.settings.textarea == 'undefined' && typeof self.element != 'undefined') {
var textareas = self.element.getElementsByTagName('textarea');
if (textareas.length > 0) {
self.settings.textarea = textareas[0];
_applyStyles(self.settings.textarea, {
display: 'none'
});
}
}
// Figure out the file name. If no file name is given we'll use the ID.
// If there's no ID either we'll use a namespaced file name that's incremented
// based on the calling order. As long as it doesn't change, drafts will be saved.
if (!self.settings.file.name) {
if (typeof self.settings.container == 'string') {
self.settings.file.name = self.settings.container;
}
else if (typeof self.settings.container == 'object') {
if (self.element.id) {
self.settings.file.name = self.element.id;
}
else {
if (!EpicEditor._data.unnamedEditors) {
EpicEditor._data.unnamedEditors = [];
}
EpicEditor._data.unnamedEditors.push(self);
self.settings.file.name = '__epiceditor-untitled-' + EpicEditor._data.unnamedEditors.length;
}
}
}
if (self.settings.button.bar === "show") {
self.settings.button.bar = true;
}
if (self.settings.button.bar === "hide") {
self.settings.button.bar = false;
}
// Protect the id and overwrite if passed in as an option
// TODO: Put underscrore to denote that this is private
self._instanceId = 'epiceditor-' + Math.round(Math.random() * 100000);
self._storage = {};
self._canSave = true;
// Setup local storage of files
self._defaultFileSchema = function () {
return {
content: self.settings.file.defaultContent
, created: new Date()
, modified: new Date()
}
}
if (localStorage && self.settings.clientSideStorage) {
this._storage = localStorage;
if (this._storage[self.settings.localStorageName] && self.getFiles(self.settings.file.name) === undefined) {
_defaultFile = self._defaultFileSchema();
_defaultFile.content = self.settings.file.defaultContent;
}
}
if (!this._storage[self.settings.localStorageName]) {
defaultStorage = {};
defaultStorage[self.settings.file.name] = self._defaultFileSchema();
defaultStorage = JSON.stringify(defaultStorage);
this._storage[self.settings.localStorageName] = defaultStorage;
}
// A string to prepend files with to save draft versions of files
// and reset all preview drafts on each load!
self._previewDraftLocation = '__draft-';
self._storage[self._previewDraftLocation + self.settings.localStorageName] = self._storage[self.settings.localStorageName];
// This needs to replace the use of classes to check the state of EE
self._eeState = {
fullscreen: false
, preview: false
, edit: false
, loaded: false
, unloaded: false
}
// Now that it exists, allow binding of events if it doesn't exist yet
if (!self.events) {
self.events = {};
}
return this;
}
|
Initiates the EpicEditor object and sets up offline storage as well
@class Represents an EpicEditor instance
@param {object} options An optional customization object
@returns {object} EpicEditor will be returned
|
EpicEditor
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function utilBarHandler(e) {
if (self.settings.button.bar !== "auto") {
return;
}
// Here we check if the mouse has moves more than 5px in any direction before triggering the mousemove code
// we do this for 2 reasons:
// 1. On Mac OS X lion when you scroll and it does the iOS like "jump" when it hits the top/bottom of the page itll fire off
// a mousemove of a few pixels depending on how hard you scroll
// 2. We give a slight buffer to the user in case he barely touches his touchpad or mouse and not trigger the UI
if (Math.abs(mousePos.y - e.pageY) >= 5 || Math.abs(mousePos.x - e.pageX) >= 5) {
utilBar.style.display = 'block';
// if we have a timer already running, kill it out
if (utilBarTimer) {
clearTimeout(utilBarTimer);
}
// begin a new timer that hides our object after 1000 ms
utilBarTimer = window.setTimeout(function () {
utilBar.style.display = 'none';
}, 1000);
}
mousePos = { y: e.pageY, x: e.pageX };
}
|
Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
@returns {object} EpicEditor will be returned
|
utilBarHandler
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function shortcutHandler(e) {
if (e.keyCode == self.settings.shortcut.modifier) { isMod = true } // check for modifier press(default is alt key), save to var
if (e.keyCode == 17) { isCtrl = true } // check for ctrl/cmnd press, in order to catch ctrl/cmnd + s
if (e.keyCode == 18) { isCtrl = false }
// Check for alt+p and make sure were not in fullscreen - default shortcut to switch to preview
if (isMod === true && e.keyCode == self.settings.shortcut.preview && !self.is('fullscreen')) {
e.preventDefault();
if (self.is('edit') && self._previewEnabled) {
self.preview();
}
else if (self._editEnabled) {
self.edit();
}
}
// Check for alt+f - default shortcut to make editor fullscreen
if (isMod === true && e.keyCode == self.settings.shortcut.fullscreen && self._fullscreenEnabled) {
e.preventDefault();
self._goFullscreen(fsElement);
}
// Set the modifier key to false once *any* key combo is completed
// or else, on Windows, hitting the alt key will lock the isMod state to true (ticket #133)
if (isMod === true && e.keyCode !== self.settings.shortcut.modifier) {
isMod = false;
}
// When a user presses "esc", revert everything!
if (e.keyCode == 27 && self.is('fullscreen')) {
self._exitFullscreen(fsElement);
}
// Check for ctrl + s (since a lot of people do it out of habit) and make it do nothing
if (isCtrl === true && e.keyCode == 83) {
self.save();
e.preventDefault();
isCtrl = false;
}
// Do the same for Mac now (metaKey == cmd).
if (e.metaKey && e.keyCode == 83) {
self.save();
e.preventDefault();
}
}
|
Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
@returns {object} EpicEditor will be returned
|
shortcutHandler
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function shortcutUpHandler(e) {
if (e.keyCode == self.settings.shortcut.modifier) { isMod = false }
if (e.keyCode == 17) { isCtrl = false }
}
|
Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
@returns {object} EpicEditor will be returned
|
shortcutUpHandler
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function pasteHandler(e) {
var content;
if (e.clipboardData) {
//FF 22, Webkit, "standards"
e.preventDefault();
content = e.clipboardData.getData("text/plain");
self.editorIframeDocument.execCommand("insertText", false, content);
}
else if (window.clipboardData) {
//IE, "nasty"
e.preventDefault();
content = window.clipboardData.getData("Text");
content = content.replace(/</g, '<');
content = content.replace(/>/g, '>');
content = content.replace(/\n/g, '<br>');
content = content.replace(/\r/g, ''); //fuck you, ie!
content = content.replace(/<br>\s/g, '<br> ')
content = content.replace(/\s\s\s/g, ' ')
content = content.replace(/\s\s/g, ' ')
self.editorIframeDocument.selection.createRange().pasteHTML(content);
}
}
|
Inserts the EpicEditor into the DOM via an iframe and gets it ready for editing and previewing
@returns {object} EpicEditor will be returned
|
pasteHandler
|
javascript
|
OscarGodson/EpicEditor
|
src/editor.js
|
https://github.com/OscarGodson/EpicEditor/blob/master/src/editor.js
|
MIT
|
function formatDate(language) {
var finalDate,
date = new Date();
switch (language) {
case 'en_US' :
finalDate = date.getFullYear() + '/' + (parseInt(date.getMonth(), 10) + 1) + '/' + date.getDate();
break;
case 'pt_BR' :
finalDate = date.getDate() + '/' + (parseInt(date.getMonth(), 10) + 1) + '/' + date.getFullYear();
break;
default :
finalDate = date.getFullYear() + '/' + (parseInt(date.getMonth(), 10) + 1) + '/' + date.getDate();
}
return finalDate;
}
|
Write last change date (current day)
to the main _data.json file.
It will appear in the header of the Styleguide.
Additional date formats should be configured here.
|
formatDate
|
javascript
|
hugeinc/styleguide
|
styleguide/structure/_node-files/modules/write-date.js
|
https://github.com/hugeinc/styleguide/blob/master/styleguide/structure/_node-files/modules/write-date.js
|
MIT
|
function getCoords(event) {
// touch move and touch end have different touch data
var touches = event.touches,
data = touches && touches.length ? touches : event.changedTouches;
return {
x: isTouch ? data[0].pageX : event.pageX,
y: isTouch ? data[0].pageY : event.pageY
};
}
|
Returns an object containing the co-ordinates for the event, normalising for touch / non-touch.
@param {Object} event
@returns {Object}
|
getCoords
|
javascript
|
Stereobit/dragend
|
dragend.js
|
https://github.com/Stereobit/dragend/blob/master/dragend.js
|
MIT
|
function Dragend( container, settings ) {
var defaultSettingsCopy = extend( {}, defaultSettings );
this.settings = extend( defaultSettingsCopy, settings );
this.container = container;
this.pageContainer = doc.createElement( "div" );
this.scrollBorder = { x: 0, y: 0 };
this.page = 0;
this.preventScroll = false;
this.pageCssProperties = {
margin: 0
};
// bind events
this._onStart = proxy( this._onStart, this );
this._onMove = proxy( this._onMove, this );
this._onEnd = proxy( this._onEnd, this );
this._onKeydown = proxy( this._onKeydown, this );
this._sizePages = proxy( this._sizePages, this );
this._afterScrollTransform = proxy(this._afterScrollTransform, this);
this.pageContainer.innerHTML = container.cloneNode(true).innerHTML;
container.innerHTML = "";
container.appendChild( this.pageContainer );
this._scroll = supportTransform ? this._scrollWithTransform : this._scrollWithoutTransform;
this._animateScroll = supportTransform ? this._animateScrollWithTransform : this._animateScrollWithoutTransform;
// Initialization
setStyles(container, containerStyles);
// Give the DOM some time to update ...
setTimeout( proxy(function() {
this.updateInstance( settings );
if (!this.settings.preventDrag) {
this._observe();
}
this.settings.afterInitialize.call(this);
}, this), 10 );
}
|
Returns an object containing the co-ordinates for the event, normalising for touch / non-touch.
@param {Object} event
@returns {Object}
|
Dragend
|
javascript
|
Stereobit/dragend
|
dragend.js
|
https://github.com/Stereobit/dragend/blob/master/dragend.js
|
MIT
|
function addEventListener(container, event, callback) {
if ($) {
$(container).on(event, callback);
} else {
container.addEventListener(event, callback, false);
}
}
|
Returns an object containing the co-ordinates for the event, normalising for touch / non-touch.
@param {Object} event
@returns {Object}
|
addEventListener
|
javascript
|
Stereobit/dragend
|
dragend.js
|
https://github.com/Stereobit/dragend/blob/master/dragend.js
|
MIT
|
function removeEventListener(container, event, callback) {
if ($) {
$(container).off(event, callback);
} else {
container.removeEventListener(event, callback, false);
}
}
|
Returns an object containing the co-ordinates for the event, normalising for touch / non-touch.
@param {Object} event
@returns {Object}
|
removeEventListener
|
javascript
|
Stereobit/dragend
|
dragend.js
|
https://github.com/Stereobit/dragend/blob/master/dragend.js
|
MIT
|
function getCoords(event) {
// touch move and touch end have different touch data
var touches = event.touches,
data = touches && touches.length ? touches : event.changedTouches;
return {
x: isTouch ? data[0].pageX : event.pageX,
y: isTouch ? data[0].pageY : event.pageY
};
}
|
Returns an object containing the co-ordinates for the event, normalising for touch / non-touch.
@param {Object} event
@returns {Object}
|
getCoords
|
javascript
|
Stereobit/dragend
|
dist/dragend.js
|
https://github.com/Stereobit/dragend/blob/master/dist/dragend.js
|
MIT
|
function Dragend( container, settings ) {
var defaultSettingsCopy = extend( {}, defaultSettings );
this.settings = extend( defaultSettingsCopy, settings );
this.container = container;
this.pageContainer = doc.createElement( "div" );
this.scrollBorder = { x: 0, y: 0 };
this.page = 0;
this.preventScroll = false;
this.pageCssProperties = {
margin: 0
};
// bind events
this._onStart = proxy( this._onStart, this );
this._onMove = proxy( this._onMove, this );
this._onEnd = proxy( this._onEnd, this );
this._onKeydown = proxy( this._onKeydown, this );
this._sizePages = proxy( this._sizePages, this );
this._afterScrollTransform = proxy(this._afterScrollTransform, this);
this.pageContainer.innerHTML = container.cloneNode(true).innerHTML;
container.innerHTML = "";
container.appendChild( this.pageContainer );
this._scroll = supportTransform ? this._scrollWithTransform : this._scrollWithoutTransform;
this._animateScroll = supportTransform ? this._animateScrollWithTransform : this._animateScrollWithoutTransform;
// Initialization
setStyles(container, containerStyles);
// Give the DOM some time to update ...
setTimeout( proxy(function() {
this.updateInstance( settings );
if (!this.settings.preventDrag) {
this._observe();
}
this.settings.afterInitialize.call(this);
}, this), 10 );
}
|
Returns an object containing the co-ordinates for the event, normalising for touch / non-touch.
@param {Object} event
@returns {Object}
|
Dragend
|
javascript
|
Stereobit/dragend
|
dist/dragend.js
|
https://github.com/Stereobit/dragend/blob/master/dist/dragend.js
|
MIT
|
function addEventListener(container, event, callback) {
if ($) {
$(container).on(event, callback);
} else {
container.addEventListener(event, callback, false);
}
}
|
Returns an object containing the co-ordinates for the event, normalising for touch / non-touch.
@param {Object} event
@returns {Object}
|
addEventListener
|
javascript
|
Stereobit/dragend
|
dist/dragend.js
|
https://github.com/Stereobit/dragend/blob/master/dist/dragend.js
|
MIT
|
function removeEventListener(container, event, callback) {
if ($) {
$(container).off(event, callback);
} else {
container.removeEventListener(event, callback, false);
}
}
|
Returns an object containing the co-ordinates for the event, normalising for touch / non-touch.
@param {Object} event
@returns {Object}
|
removeEventListener
|
javascript
|
Stereobit/dragend
|
dist/dragend.js
|
https://github.com/Stereobit/dragend/blob/master/dist/dragend.js
|
MIT
|
addInlineAddButton = function() {
if (addButton === null) {
if ($this.prop("tagName") === "TR") {
// If forms are laid out as table rows, insert the
// "add" button in a new table row:
const numCols = $this.eq(-1).children().length;
$parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>");
addButton = $parent.find("tr:last a");
} else {
// Otherwise, insert it immediately after the last form:
$this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>");
addButton = $this.filter(":last").next().find("a");
}
}
addButton.on('click', addInlineClickHandler);
}
|
The "Add another MyModel" button below the inline forms.
|
addInlineAddButton
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
addInlineAddButton = function() {
if (addButton === null) {
if ($this.prop("tagName") === "TR") {
// If forms are laid out as table rows, insert the
// "add" button in a new table row:
const numCols = $this.eq(-1).children().length;
$parent.append('<tr class="' + options.addCssClass + '"><td colspan="' + numCols + '"><a href="#">' + options.addText + "</a></tr>");
addButton = $parent.find("tr:last a");
} else {
// Otherwise, insert it immediately after the last form:
$this.filter(":last").after('<div class="' + options.addCssClass + '"><a href="#">' + options.addText + "</a></div>");
addButton = $this.filter(":last").next().find("a");
}
}
addButton.on('click', addInlineClickHandler);
}
|
The "Add another MyModel" button below the inline forms.
|
addInlineAddButton
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
addInlineClickHandler = function(e) {
e.preventDefault();
const template = $("#" + options.prefix + "-empty");
const row = template.clone(true);
row.removeClass(options.emptyCssClass)
.addClass(options.formCssClass)
.attr("id", options.prefix + "-" + nextIndex);
addInlineDeleteButton(row);
row.find("*").each(function() {
updateElementIndex(this, options.prefix, totalForms.val());
});
// Insert the new form when it has been fully edited.
row.insertBefore($(template));
// Update number of total forms.
$(totalForms).val(parseInt(totalForms.val(), 10) + 1);
nextIndex += 1;
// Hide the add button if there's a limit and it's been reached.
if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) {
addButton.parent().hide();
}
// Show the remove buttons if there are more than min_num.
toggleDeleteButtonVisibility(row.closest('.inline-group'));
// Pass the new form to the post-add callback, if provided.
if (options.added) {
options.added(row);
}
$(document).trigger('formset:added', [row, options.prefix]);
}
|
The "Add another MyModel" button below the inline forms.
|
addInlineClickHandler
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
addInlineClickHandler = function(e) {
e.preventDefault();
const template = $("#" + options.prefix + "-empty");
const row = template.clone(true);
row.removeClass(options.emptyCssClass)
.addClass(options.formCssClass)
.attr("id", options.prefix + "-" + nextIndex);
addInlineDeleteButton(row);
row.find("*").each(function() {
updateElementIndex(this, options.prefix, totalForms.val());
});
// Insert the new form when it has been fully edited.
row.insertBefore($(template));
// Update number of total forms.
$(totalForms).val(parseInt(totalForms.val(), 10) + 1);
nextIndex += 1;
// Hide the add button if there's a limit and it's been reached.
if ((maxForms.val() !== '') && (maxForms.val() - totalForms.val()) <= 0) {
addButton.parent().hide();
}
// Show the remove buttons if there are more than min_num.
toggleDeleteButtonVisibility(row.closest('.inline-group'));
// Pass the new form to the post-add callback, if provided.
if (options.added) {
options.added(row);
}
$(document).trigger('formset:added', [row, options.prefix]);
}
|
The "Add another MyModel" button below the inline forms.
|
addInlineClickHandler
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
addInlineDeleteButton = function(row) {
if (row.is("tr")) {
// If the forms are laid out in table rows, insert
// the remove button into the last table cell:
row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></div>");
} else if (row.is("ul") || row.is("ol")) {
// If they're laid out as an ordered/unordered list,
// insert an <li> after the last list item:
row.append('<li><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></li>");
} else {
// Otherwise, just insert the remove button as the
// last child element of the form's container:
row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></span>");
}
// Add delete handler for each row.
row.find("a." + options.deleteCssClass).on('click', inlineDeleteHandler.bind(this));
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
addInlineDeleteButton
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
addInlineDeleteButton = function(row) {
if (row.is("tr")) {
// If the forms are laid out in table rows, insert
// the remove button into the last table cell:
row.children(":last").append('<div><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></div>");
} else if (row.is("ul") || row.is("ol")) {
// If they're laid out as an ordered/unordered list,
// insert an <li> after the last list item:
row.append('<li><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></li>");
} else {
// Otherwise, just insert the remove button as the
// last child element of the form's container:
row.children(":first").append('<span><a class="' + options.deleteCssClass + '" href="#">' + options.deleteText + "</a></span>");
}
// Add delete handler for each row.
row.find("a." + options.deleteCssClass).on('click', inlineDeleteHandler.bind(this));
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
addInlineDeleteButton
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
inlineDeleteHandler = function(e1) {
e1.preventDefault();
const deleteButton = $(e1.target);
const row = deleteButton.closest('.' + options.formCssClass);
const inlineGroup = row.closest('.inline-group');
// Remove the parent form containing this button,
// and also remove the relevant row with non-field errors:
const prevRow = row.prev();
if (prevRow.length && prevRow.hasClass('row-form-errors')) {
prevRow.remove();
}
row.remove();
nextIndex -= 1;
// Pass the deleted form to the post-delete callback, if provided.
if (options.removed) {
options.removed(row);
}
$(document).trigger('formset:removed', [row, options.prefix]);
// Update the TOTAL_FORMS form count.
const forms = $("." + options.formCssClass);
$("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
// Show add button again once below maximum number.
if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
addButton.parent().show();
}
// Hide the remove buttons if at min_num.
toggleDeleteButtonVisibility(inlineGroup);
// Also, update names and ids for all remaining form controls so
// they remain in sequence:
let i, formCount;
const updateElementCallback = function() {
updateElementIndex(this, options.prefix, i);
};
for (i = 0, formCount = forms.length; i < formCount; i++) {
updateElementIndex($(forms).get(i), options.prefix, i);
$(forms.get(i)).find("*").each(updateElementCallback);
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
inlineDeleteHandler
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
inlineDeleteHandler = function(e1) {
e1.preventDefault();
const deleteButton = $(e1.target);
const row = deleteButton.closest('.' + options.formCssClass);
const inlineGroup = row.closest('.inline-group');
// Remove the parent form containing this button,
// and also remove the relevant row with non-field errors:
const prevRow = row.prev();
if (prevRow.length && prevRow.hasClass('row-form-errors')) {
prevRow.remove();
}
row.remove();
nextIndex -= 1;
// Pass the deleted form to the post-delete callback, if provided.
if (options.removed) {
options.removed(row);
}
$(document).trigger('formset:removed', [row, options.prefix]);
// Update the TOTAL_FORMS form count.
const forms = $("." + options.formCssClass);
$("#id_" + options.prefix + "-TOTAL_FORMS").val(forms.length);
// Show add button again once below maximum number.
if ((maxForms.val() === '') || (maxForms.val() - forms.length) > 0) {
addButton.parent().show();
}
// Hide the remove buttons if at min_num.
toggleDeleteButtonVisibility(inlineGroup);
// Also, update names and ids for all remaining form controls so
// they remain in sequence:
let i, formCount;
const updateElementCallback = function() {
updateElementIndex(this, options.prefix, i);
};
for (i = 0, formCount = forms.length; i < formCount; i++) {
updateElementIndex($(forms).get(i), options.prefix, i);
$(forms.get(i)).find("*").each(updateElementCallback);
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
inlineDeleteHandler
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
updateElementCallback = function() {
updateElementIndex(this, options.prefix, i);
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
updateElementCallback
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
updateElementCallback = function() {
updateElementIndex(this, options.prefix, i);
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
updateElementCallback
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
toggleDeleteButtonVisibility = function(inlineGroup) {
if ((minForms.val() !== '') && (minForms.val() - totalForms.val()) >= 0) {
inlineGroup.find('.inline-deletelink').hide();
} else {
inlineGroup.find('.inline-deletelink').show();
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
toggleDeleteButtonVisibility
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
toggleDeleteButtonVisibility = function(inlineGroup) {
if ((minForms.val() !== '') && (minForms.val() - totalForms.val()) >= 0) {
inlineGroup.find('.inline-deletelink').hide();
} else {
inlineGroup.find('.inline-deletelink').show();
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
toggleDeleteButtonVisibility
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
reinitDateTimeShortCuts = function() {
// Reinitialize the calendar and clock widgets by force
if (typeof DateTimeShortcuts !== "undefined") {
$(".datetimeshortcuts").remove();
DateTimeShortcuts.init();
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
reinitDateTimeShortCuts
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
reinitDateTimeShortCuts = function() {
// Reinitialize the calendar and clock widgets by force
if (typeof DateTimeShortcuts !== "undefined") {
$(".datetimeshortcuts").remove();
DateTimeShortcuts.init();
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
reinitDateTimeShortCuts
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
updateSelectFilter = function() {
// If any SelectFilter widgets are a part of the new form,
// instantiate a new SelectFilter instance for it.
if (typeof SelectFilter !== 'undefined') {
$('.selectfilter').each(function(index, value) {
const namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false);
});
$('.selectfilterstacked').each(function(index, value) {
const namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true);
});
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
updateSelectFilter
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
updateSelectFilter = function() {
// If any SelectFilter widgets are a part of the new form,
// instantiate a new SelectFilter instance for it.
if (typeof SelectFilter !== 'undefined') {
$('.selectfilter').each(function(index, value) {
const namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false);
});
$('.selectfilterstacked').each(function(index, value) {
const namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true);
});
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
updateSelectFilter
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
initPrepopulatedFields = function(row) {
row.find('.prepopulated_field').each(function() {
const field = $(this),
input = field.find('input, select, textarea'),
dependency_list = input.data('dependency_list') || [],
dependencies = [];
$.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
});
if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength'));
}
});
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
initPrepopulatedFields
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
initPrepopulatedFields = function(row) {
row.find('.prepopulated_field').each(function() {
const field = $(this),
input = field.find('input, select, textarea'),
dependency_list = input.data('dependency_list') || [],
dependencies = [];
$.each(dependency_list, function(i, field_name) {
dependencies.push('#' + row.find('.field-' + field_name).find('input, select, textarea').attr('id'));
});
if (dependencies.length) {
input.prepopulate(dependencies, input.attr('maxlength'));
}
});
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
initPrepopulatedFields
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
updateInlineLabel = function(row) {
$(selector).find(".inline_label").each(function(i) {
const count = i + 1;
$(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
});
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
updateInlineLabel
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
updateInlineLabel = function(row) {
$(selector).find(".inline_label").each(function(i) {
const count = i + 1;
$(this).html($(this).html().replace(/(#\d+)/g, "#" + count));
});
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
updateInlineLabel
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
reinitDateTimeShortCuts = function() {
// Reinitialize the calendar and clock widgets by force, yuck.
if (typeof DateTimeShortcuts !== "undefined") {
$(".datetimeshortcuts").remove();
DateTimeShortcuts.init();
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
reinitDateTimeShortCuts
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
reinitDateTimeShortCuts = function() {
// Reinitialize the calendar and clock widgets by force, yuck.
if (typeof DateTimeShortcuts !== "undefined") {
$(".datetimeshortcuts").remove();
DateTimeShortcuts.init();
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
reinitDateTimeShortCuts
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
updateSelectFilter = function() {
// If any SelectFilter widgets were added, instantiate a new instance.
if (typeof SelectFilter !== "undefined") {
$(".selectfilter").each(function(index, value) {
const namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], false);
});
$(".selectfilterstacked").each(function(index, value) {
const namearr = value.name.split('-');
SelectFilter.init(value.id, namearr[namearr.length - 1], true);
});
}
}
|
The "X" button that is part of every unsaved inline.
(When saved, it is replaced with a "Delete" checkbox.)
|
updateSelectFilter
|
javascript
|
johanmodin/clifs
|
www/assets/admin/js/inlines.js
|
https://github.com/johanmodin/clifs/blob/master/www/assets/admin/js/inlines.js
|
Apache-2.0
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.