How does Twitter implement its Tweet Box? - javascript
I'm trying to implement something like Twitter's tweet box, specifically:
Automatically highlights text in a red background when the overall length exceeds 140 characters.
Automatically highlights links, mentions, and hashtags in blue.
These should happen automatically aka when a user types.
By the semantic markup I'm seeing on Twitter, it looks like they're using a contentEditable div. And the DOM inside is modified whenever a mention/hashtag/link is detected, or when the length is exceeded over 140 characters:
<div aria-labelledby="tweet-box-mini-home-profile-label" id="tweet-box-mini-home-profile" class="tweet-box rich-editor notie" contenteditable="true" spellcheck="true" role="textbox" aria-multiline="true" dir="ltr" aria-autocomplete="list" aria-expanded="false" aria-owns="typeahead-dropdown-6">
<div>hello world <a class="twitter-atreply pretty-link" href="/testMention" role="presentation"><s>#</s>testMention</a> text <s>#</s>helloWorld text http://www.google.com text text text text text text text text text text text text text text <em>overflow red text here</em>
</div>
</div>
What I have done so far
Currently, I'm using a contentEditable field. It triggers a function onChange/onInput that parses the text. Check if it has a username/link/hashtag via regexr and replace them with the respective tags (I'm just using a simple <i> tag to enclose username and hashtag for now).
The problem I'm having is that because I'm changing/modifying the DOM of the contentEditable, the caret cursor position becomes lost.
I looked at this thread Persisting the changes of range objects after selection in HTML and it works fine only if the DOM isn't changed (which it is in my case, surrounding tags/hashtags with <i> tags, links with <a> tags, and overflow with <b> tags.
Fiddle: http://jsfiddle.net/4Lsqjkjb/
Does anyone have any alternative solutions/approaches on how to tackle this problem? Maybe I shouldn't use contentEditable? Or some way that doesn't directly modify the DOM of the contentEditable field so the caret position is maintained? Any help would be appreciated! I tried playing around with window.getSelection() and saving it before DOM change, but it always seem to reset after DOM changes are applied.
What I did is kind of a hack but works quite well as a workaround solution.
I've got a simple textarea (not contenteditable because of what's next, I'll explain below) and a div which is absolute positioned behind the textarea. Using javascript, I copy the content from the textarea to the div while splitting it at 140 chars and putting all extra characters inside an <em /> tag.
Well, it's a little bit more complicated because twitter algorithm to compute a tweet length is different (links doesn't count as their real value, because of t.co url shortening). The exact method can be found as part of the official twitter/twitter-txt repository.
Step-by-step code.
Wrap a simple textarea into a div to simplify the css:
<div class="tweet-composer">
<textarea class="editor-textarea js-keeper-editor">This is some text that will be highlight when longer than 20 characters. Like twitter. Type something...</textarea>
<div class="js-keeper-placeholder-back"></div>
</div>
CSS is just making the textarea and the div right above each other and highlight the text.
.tweet-composer {
position: relative;
z-index: 1;
}
.js-keeper-editor,
.js-keeper-placeholder-back {
background: transparent;
border: 1px solid #eee;
font-family: Helvetica, Arial, sans-serif;
font-size: 14px; /* Same font for both. */
margin: auto;
min-height: 200px;
outline: none;
padding: 10px;
width: 100%;
}
.js-keeper-placeholder-back {
bottom: 0;
color: transparent;
left: 0;
position: absolute;
top: 0;
white-space: pre-wrap;
width: 100%;
word-wrap: break-word;
z-index: -1;
}
.js-keeper-placeholder-back em {
background: #fcc !important;
}
Now the fun part, this is implemented using jQuery but that's not the important thing.
if (0 > remainingLength) {
// Split value if greater than
var allowedValuePart = currentValue.slice(0, realLength),
refusedValuePart = currentValue.slice(realLength)
;
// Fill the hidden div.
$placeholderBacker.html(allowedValuePart + '<em>' + refusedValuePart + '</em>');
} else {
$placeholderBacker.html('');
}
Add some event handler on change, and te common document ready and you're done. See the codepen link below.
Note that the div placed behind can be created using js too, when loading the page:
// Create a pseudo-element that will be hidden behind the placeholder.
var $placeholderBacker = $('<div class="js-keeper-placeholder-back"></div>');
$placeholderBacker.insertAfter($textarea);
Full example
See working example over here:
http://codepen.io/hussard/pen/EZvaBZ
This is not a direct answer with source code building the part of your application to your spec.
This is really not an easy thing to do.
You're right - the way to solving this problem is to use a contenteditable="true" container. But I'm afraid that from there it gets much much more complicated.
Enter DraftJS - A javascript solution to rich-text editing which does most of the heavy lifting for you.
Both of my solutions below require the use of both React and DraftJS
The Plug-&-Play Solution:
The React + DraftJS + Someone Else's "Plugin" solution is already here. You can check out draft-js-plugins.com. And here's the Github source code.
Personally, I wouldn't go this way. I would rather study their GitHub source code and implement my own DraftJS entities. Because I think that React-JS-Plugins feels a little bit clunky and overweight for just Links and Mentions. Plus, where are you "mentioning" from? Your own Application? Twitter? Doing it this way lets you have control over where you're grabbing the so-called "mentions".
The DIY Solution:
The best way I have found is to build your own set of working entities on top of a DraftJS based rich-text editor.
This of course also requires that you're using React.
Forgive me for not actually building a complete set of working code. I was interested in doing something similar for an App I'm building in Meteor with React on the front-end. So this really made sense to me because I'd only be adding one more library (DraftJS) and the rest would be my custom entities coded out.
Turns out this is really not an easy thing to do. I've been struggling with it for the past few days, and I'm not very close to a solution.
Your best drop-in solution currently is the At.js library, which is still being maintained, but definitely isn't perfect. One of the examples shows how you can kind of do a text highlight.
The most annoying part of this problem is that Twitter has a beautiful solution that seemingly works perfectly staring us right in the face. I took some time investigating the way they implement their "tweet box," and it's definitely not trivial. It looks like they're doing almost everything manually, including emulating undo/redo functionality, intercepting copy/pastes, providing custom code for IE/W3C, custom-coding Mac/PC, and more. They use a contenteditable div, which is in-and-of-itself problematic due to differences in browser implementations. It's pretty impressive, actually.
Here's the most relevant (obfuscated, unfortunately) code, taken from Twitter's boot JavaScript file (found by inspecting the header of the logged-in Twitter homepage). I didn't want to directly copy and paste the link, in case it's personalized to my Twitter account.
define("app/utils/html_text", ["module", "require", "exports"], function(module, require, exports) {
function isTextNode(a) {
return a.nodeType == 3 || a.nodeType == 4
}
function isElementNode(a) {
return a.nodeType == 1
}
function isBrNode(a) {
return isElementNode(a) && a.nodeName.toLowerCase() == "br"
}
function isOutsideContainer(a, b) {
while (a !== b) {
if (!a) return !0;
a = a.parentNode
}
}
var useW3CRange = window.getSelection,
useMsftTextRange = !useW3CRange && document.selection,
useIeHtmlFix = navigator.appName == "Microsoft Internet Explorer",
NBSP_REGEX = /[\xa0\n\t]/g,
CRLF_REGEX = /\r\n/g,
LINES_REGEX = /(.*?)\n/g,
SP_LEADING_OR_FOLLOWING_CLOSE_TAG_OR_PRECEDING_A_SP_REGEX = /^ |(<\/[^>]+>) | (?= )/g,
SP_LEADING_OR_TRAILING_OR_FOLLOWING_A_SP_REGEX = /^ | $|( ) /g,
MAX_OFFSET = Number.MAX_VALUE,
htmlText = function(a, b) {
function c(a, c) {
function h(a) {
var i = d.length;
if (isTextNode(a)) {
var j = a.nodeValue.replace(NBSP_REGEX, " "),
k = j.length;
k && (d += j, e = !0), c(a, !0, 0, i, i + k)
} else if (isElementNode(a)) {
c(a, !1, 0, i, i);
if (isBrNode(a)) a == f ? g = !0 : (d += "\n", e = !1);
else {
var l = a.currentStyle || window.getComputedStyle(a, ""),
m = l.display == "block";
m && b.msie && (e = !0);
for (var n = a.firstChild, o = 1; n; n = n.nextSibling, o++) {
h(n);
if (g) return;
i = d.length, c(a, !1, o, i, i)
}
g || a == f ? g = !0 : m && e && (d += "\n", e = !1)
}
}
}
var d = "",
e, f, g;
for (var i = a; i && isElementNode(i); i = i.lastChild) f = i;
return h(a), d
}
function d(a, b) {
var d = null,
e = b.length - 1;
if (useW3CRange) {
var f = b.map(function() {
return {}
}),
g;
c(a, function(a, c, d, h, i) {
g || f.forEach(function(f, j) {
var k = b[j];
h <= k && !isBrNode(a) && (f.node = a, f.offset = c ? Math.min(k, i) - h : d, g = c && j == e && i >= k)
})
}), f[0].node && f[e].node && (d = document.createRange(), d.setStart(f[0].node, f[0].offset), d.setEnd(f[e].node, f[e].offset))
} else if (useMsftTextRange) {
var h = document.body.createTextRange();
h.moveToElementText(a), d = h.duplicate();
if (b[0] == MAX_OFFSET) d.setEndPoint("StartToEnd", h);
else {
d.move("character", b[0]);
var i = e && b[1] - b[0];
i > 0 && d.moveEnd("character", i), h.inRange(d) || d.setEndPoint("EndToEnd", h)
}
}
return d
}
function e() {
return document.body.contains(a)
}
function f(b) {
a.innerHTML = b;
if (useIeHtmlFix)
for (var c = a.firstChild; c; c = c.nextSibling) isElementNode(c) && c.nodeName.toLowerCase() == "p" && c.innerHTML == "" && (c.innerText = "")
}
function g(a, b) {
return a.map(function(a) {
return Math.min(a, b.length)
})
}
function h() {
var b = getSelection();
if (b.rangeCount !== 1) return null;
var d = b.getRangeAt(0);
if (isOutsideContainer(d.commonAncestorContainer, a)) return null;
var e = [{
node: d.startContainer,
offset: d.startOffset
}];
d.collapsed || e.push({
node: d.endContainer,
offset: d.endOffset
});
var f = e.map(function() {
return MAX_OFFSET
}),
h = c(a, function(a, b, c, d) {
e.forEach(function(e, g) {
f[g] == MAX_OFFSET && a == e.node && (b || c == e.offset) && (f[g] = d + (b ? e.offset : 0))
})
});
return g(f, h)
}
function i() {
var b = document.selection.createRange();
if (isOutsideContainer(b.parentElement(), a)) return null;
var d = ["Start"];
b.compareEndPoints("StartToEnd", b) && d.push("End");
var e = d.map(function() {
return MAX_OFFSET
}),
f = document.body.createTextRange(),
h = c(a, function(c, g, h, i) {
function j(a, c) {
if (e[c] < MAX_OFFSET) return;
var d = f.compareEndPoints("StartTo" + a, b);
if (d > 0) return;
var g = f.compareEndPoints("EndTo" + a, b);
if (g < 0) return;
var h = f.duplicate();
h.setEndPoint("EndTo" + a, b), e[c] = i + h.text.length, c && !g && e[c]++
}!g && !h && c != a && (f.moveToElementText(c), d.forEach(j))
});
return g(e, h)
}
return {
getHtml: function() {
if (useIeHtmlFix) {
var b = "",
c = document.createElement("div");
for (var d = a.firstChild; d; d = d.nextSibling) isTextNode(d) ? (c.innerText = d.nodeValue, b += c.innerHTML) : b += d.outerHTML.replace(CRLF_REGEX, "");
return b
}
return a.innerHTML
},
setHtml: function(a) {
f(a)
},
getText: function() {
return c(a, function() {})
},
setTextWithMarkup: function(a) {
f((a + "\n").replace(LINES_REGEX, function(a, c) {
return b.mozilla || b.msie ? (c = c.replace(SP_LEADING_OR_FOLLOWING_CLOSE_TAG_OR_PRECEDING_A_SP_REGEX, "$1 "), b.mozilla ? c + "<BR>" : "<P>" + c + "</P>") : (c = (c || "<br>").replace(SP_LEADING_OR_TRAILING_OR_FOLLOWING_A_SP_REGEX, "$1 "), b.opera ? "<p>" + c + "</p>" : "<div>" + c + "</div>")
}))
},
getSelectionOffsets: function() {
var a = null;
return e() && (useW3CRange ? a = h() : useMsftTextRange && (a = i())), a
},
setSelectionOffsets: function(b) {
if (b && e()) {
var c = d(a, b);
if (c)
if (useW3CRange) {
var f = window.getSelection();
f.removeAllRanges(), f.addRange(c)
} else useMsftTextRange && c.select()
}
},
emphasizeText: function(b) {
var f = [];
b && b.length > 1 && e() && (c(a, function(a, c, d, e, g) {
if (c) {
var h = Math.max(e, b[0]),
i = Math.min(g, b[1]);
i > h && f.push([h, i])
}
}), f.forEach(function(b) {
var c = d(a, b);
c && (useW3CRange ? c.surroundContents(document.createElement("em")) : useMsftTextRange && c.execCommand("italic", !1, null))
}))
}
}
};
module.exports = htmlText
});
define("app/utils/tweet_helper", ["module", "require", "exports", "lib/twitter-text", "core/utils", "app/data/user_info"], function(module, require, exports) {
var twitterText = require("lib/twitter-text"),
utils = require("core/utils"),
userInfo = require("app/data/user_info"),
VALID_PROTOCOL_PREFIX_REGEX = /^https?:\/\//i,
tweetHelper = {
extractMentionsForReply: function(a, b) {
var c = a.attr("data-screen-name"),
d = a.attr("data-retweeter"),
e = a.attr("data-mentions") ? a.attr("data-mentions").split(" ") : [],
f = a.attr("data-tagged") ? a.attr("data-tagged").split(" ") : [];
e = e.concat(f);
var g = [c, b, d];
return e = e.filter(function(a) {
return g.indexOf(a) < 0
}), d && d != c && d != b && e.unshift(d), (!e.length || c != b) && e.unshift(c), e
},
linkify: function(a, b) {
return b = utils.merge({
hashtagClass: "twitter-hashtag pretty-link",
hashtagUrlBase: "/search?q=%23",
symbolTag: "s",
textWithSymbolTag: "b",
cashtagClass: "twitter-cashtag pretty-link",
cashtagUrlBase: "/search?q=%24",
usernameClass: "twitter-atreply pretty-link",
usernameUrlBase: "/",
usernameIncludeSymbol: !0,
listClass: "twitter-listname pretty-link",
urlClass: "twitter-timeline-link",
urlTarget: "_blank",
suppressNoFollow: !0,
htmlEscapeNonEntities: !0
}, b || {}), twitterText.autoLinkEntities(a, twitterText.extractEntitiesWithIndices(a), b)
}
};
module.exports = tweetHelper
});
define("app/ui/compose/with_rich_editor", ["module", "require", "exports", "app/utils/file", "app/utils/html_text", "app/utils/tweet_helper", "lib/twitter-text"], function(module, require, exports) {
function withRichEditor() {
this.defaultAttrs({
richSelector: "div.rich-editor",
linksSelector: "a",
normalizerSelector: "div.rich-normalizer",
$browser: $.browser
}), this.linkify = function(a) {
var b = {
urlTarget: null,
textWithSymbolTag: RENDER_URLS_AS_PRETTY_LINKS ? "b" : "",
linkAttributeBlock: function(a, b) {
var c = a.screenName || a.url;
c && (this.urlAndMentionsCharCount += c.length + 2), delete b.title, delete b["data-screen-name"], b.dir = a.hashtag && this.shouldBeRTL(a.hashtag, 0) ? "rtl" : "ltr", b.role = "presentation"
}.bind(this)
};
return this.urlAndMentionsCharCount = 0, tweetHelper.linkify(a, b)
}, this.around("setSelection", function(a, b) {
b && this.setSelectionIfFocused(b)
}), this.around("setCursorPosition", function(a, b) {
b === undefined && (b = this.attr.cursorPosition), b === undefined && (b = MAX_OFFSET), this.setSelectionIfFocused([b])
}), this.around("detectUpdatedText", function(a, b, c) {
var d = this.htmlRich.getHtml(),
e = this.htmlRich.getSelectionOffsets() || [MAX_OFFSET],
f = c !== undefined;
if (d === this.prevHtml && e[0] === this.prevSelectionOffset && !b && !f) return;
var g = f ? c : this.htmlRich.getText(),
h = g.replace(INVALID_CHARS_REGEX, "");
(f || !(!d && !this.hasFocus() || this.$text.attr("data-in-composition"))) && this.reformatHtml(h, d, e, f);
if (b || this.cleanedText != h || this.prevSelectionOffset != e[0]) this.prevSelectionOffset = e[0], this.updateCleanedTextAndOffset(h, e[0])
}), this.reformatHtml = function(a, b, c, d) {
this.htmlNormalizer.setTextWithMarkup(this.linkify(a)), this.interceptDataImageInContent();
var e = this.shouldBeRTL(a, this.urlAndMentionsCharCount);
this.$text.attr("dir", e ? "rtl" : "ltr"), this.$normalizer.find(e ? "[dir=rtl]" : "[dir=ltr]").removeAttr("dir"), RENDER_URLS_AS_PRETTY_LINKS && this.$normalizer.find(".twitter-timeline-link").wrapInner("<b>").addClass("pretty-link");
var f = this.getMaxLengthOffset(a);
f >= 0 && (this.htmlNormalizer.emphasizeText([f, MAX_OFFSET]), this.$normalizer.find("em").each(function() {
this.innerHTML = this.innerHTML.replace(TRAILING_SINGLE_SPACE_REGEX, "Â ")
}));
var g = this.htmlNormalizer.getHtml();
if (g !== b) {
var h = d && !this.isFocusing && this.hasFocus();
h && this.$text.addClass("fake-focus").blur(), this.htmlRich.setHtml(g), h && this.$text.focus().removeClass("fake-focus"), this.setSelectionIfFocused(c)
}
this.prevHtml = g
}, this.interceptDataImageInContent = function() {
if (!this.triggerGotImageData) return;
this.$text.find("img").filter(function(a, b) {
return b.src.match(/^data:/)
}).first().each(function(a, b) {
var c = file.getBlobFromDataUri(b.src);
file.getFileData("pasted.png", c).then(this.triggerGotImageData.bind(this))
}.bind(this))
}, this.getMaxLengthOffset = function(a) {
var b = this.getLength(a),
c = this.attr.maxLength;
if (b <= c) return -1;
c += twitterText.getUnicodeTextLength(a) - b;
var d = [{
indices: [c, c]
}];
return twitterText.modifyIndicesFromUnicodeToUTF16(a, d), d[0].indices[0]
}, this.setSelectionIfFocused = function(a) {
this.hasFocus() ? (this.previousSelection = null, this.htmlRich.setSelectionOffsets(a)) : this.previousSelection = a
}, this.selectPrevCharOnBackspace = function(a) {
if (a.which == 8 && !a.ctrlKey) {
var b = this.htmlRich.getSelectionOffsets();
b && b[0] != MAX_OFFSET && b.length == 1 && (b[0] ? this.setSelectionIfFocused([b[0] - 1, b[0]]) : this.stopEvent(a))
}
}, this.emulateCommandArrow = function(a) {
if (a.metaKey && !a.shiftKey && (a.which == 37 || a.which == 39)) {
var b = a.which == 37;
this.htmlRich.setSelectionOffsets([b ? 0 : MAX_OFFSET]), this.$text.scrollTop(b ? 0 : this.$text[0].scrollHeight), this.stopEvent(a)
}
}, this.stopEvent = function(a) {
a.preventDefault(), a.stopPropagation()
}, this.saveUndoStateDeferred = function(a) {
if (a.type == "mousemove" && a.which != 1) return;
setTimeout(function() {
this.detectUpdatedText(), this.saveUndoState()
}.bind(this), 0)
}, this.clearUndoState = function() {
this.undoHistory = [], this.undoIndex = -1
}, this.saveUndoState = function() {
var a = this.htmlRich.getText(),
b = this.htmlRich.getSelectionOffsets() || [a.length],
c = this.undoHistory,
d = c[this.undoIndex];
!d || d[0] !== a ? c.splice(++this.undoIndex, c.length, [a, b]) : d && (d[1] = b)
}, this.isUndoKey = function(a) {
return this.isMac ? a.which == 90 && a.metaKey && !a.shiftKey && !a.ctrlKey && !a.altKey : a.which == 90 && a.ctrlKey && !a.shiftKey && !a.altKey
}, this.emulateUndo = function(a) {
this.isUndoKey(a) && (this.stopEvent(a), this.saveUndoState(), this.undoIndex > 0 && this.setUndoState(this.undoHistory[--this.undoIndex]))
}, this.isRedoKey = function(a) {
return this.isMac ? a.which == 90 && a.metaKey && a.shiftKey && !a.ctrlKey && !a.altKey : this.isWin ? a.which == 89 && a.ctrlKey && !a.shiftKey && !a.altKey : a.which == 90 && a.shiftKey && a.ctrlKey && !a.altKey
}, this.emulateRedo = function(a) {
var b = this.undoHistory,
c = this.undoIndex;
c < b.length - 1 && this.htmlRich.getText() !== b[c][0] && b.splice(c + 1, b.length), this.isRedoKey(a) && (this.stopEvent(a), c < b.length - 1 && this.setUndoState(b[++this.undoIndex]))
}, this.setUndoState = function(a) {
this.detectUpdatedText(!1, a[0]), this.htmlRich.setSelectionOffsets(a[1]), this.trigger("uiHideAutocomplete")
}, this.undoStateAfterCursorMovement = function(a) {
a.which >= 33 && a.which <= 40 && this.saveUndoStateDeferred(a)
}, this.handleKeyDown = function(a) {
this.isIE && this.selectPrevCharOnBackspace(a), this.attr.$browser.mozilla && this.emulateCommandArrow(a), this.undoStateAfterCursorMovement(a), this.emulateUndo(a), this.emulateRedo(a)
}, this.interceptPaste = function(a) {
if (a.originalEvent && a.originalEvent.clipboardData) {
var b = a.originalEvent.clipboardData;
(this.interceptImagePaste(b) || this.interceptTextPaste(b)) && a.preventDefault()
}
}, this.interceptImagePaste = function(a) {
return this.triggerGotImageData && a.items && a.items.length === 1 && a.items[0].kind === "file" && a.items[0].type.indexOf("image/") === 0 ? (file.getFileData("pasted.png", a.items[0].getAsFile()).then(this.triggerGotImageData.bind(this)), !0) : !1
}, this.interceptTextPaste = function(a) {
var b = a.getData("text");
return b && document.execCommand("insertHTML", !1, $("<div>").text(b).html().replace(LINE_FEEDS_REGEX, "<br>")) ? !0 : !1
}, this.clearSelectionOnBlur = function() {
window.getSelection && (this.previousSelection = this.htmlRich.getSelectionOffsets(), this.previousSelection && getSelection().removeAllRanges())
}, this.restoreSelectionOnFocus = function() {
this.previousSelection ? setTimeout(function() {
this.htmlRich.setSelectionOffsets(this.previousSelection), this.previousSelection = null
}.bind(this), 0) : this.previousSelection = null
}, this.setFocusingState = function() {
this.isFocusing = !0, setTimeout(function() {
this.isFocusing = !1
}.bind(this), 0)
}, this.around("initTextNode", function(a) {
this.isIE = this.attr.$browser.msie || navigator.userAgent.indexOf("Trident") > -1, this.$text = this.select("richSelector"), this.undoHistory = [
["", [0]]
], this.undoIndex = 0, this.htmlRich = htmlText(this.$text[0], this.attr.$browser), this.$text.toggleClass("notie", !this.isIE), this.$normalizer = this.select("normalizerSelector"), this.htmlNormalizer = htmlText(this.$normalizer[0], this.attr.$browser);
var b = navigator.platform;
this.isMac = b.indexOf("Mac") != -1, this.isWin = b.indexOf("Win") != -1, this.on(this.$text, "click", {
linksSelector: this.stopEvent
}), this.on(this.$text, "focusin", this.setFocusingState), this.on(this.$text, "keydown", this.handleKeyDown), this.on(this.$text, "focusout", this.ignoreDuringFakeFocus(this.clearSelectionOnBlur)), this.on(this.$text, "focusin", this.ignoreDuringFakeFocus(this.restoreSelectionOnFocus)), this.on(this.$text, "focusin", this.ignoreDuringFakeFocus(this.saveUndoStateDeferred)), this.on(this.$text, "cut paste drop", this.saveUndoState), this.on(this.$text, "cut paste drop mousedown mousemove", this.saveUndoStateDeferred), this.on("uiSaveUndoState", this.saveUndoState), this.on("uiClearUndoState", this.clearUndoState), this.on(this.$text, "paste", this.interceptPaste), this.detectUpdatedText()
})
}
var file = require("app/utils/file"),
htmlText = require("app/utils/html_text"),
tweetHelper = require("app/utils/tweet_helper"),
twitterText = require("lib/twitter-text");
module.exports = withRichEditor;
var INVALID_CHARS_REGEX = /[\uFFFE\uFEFF\uFFFF\u200E\u200F\u202A-\u202E\x00-\x09\x0B\x0C\x0E-\x1F]/g,
RENDER_URLS_AS_PRETTY_LINKS = $.browser.mozilla && parseInt($.browser.version, 10) < 2,
TRAILING_SINGLE_SPACE_REGEX = / $/,
LINE_FEEDS_REGEX = /\r\n|\n\r|\n/g,
MAX_OFFSET = Number.MAX_VALUE
});
define("app/ui/compose/tweet_box_manager", ["module", "require", "exports", "app/ui/compose/tweet_box", "app/ui/compose/dm_composer", "app/ui/geo_picker", "core/component", "app/ui/compose/with_rich_editor"], function(module, require, exports) {
function tweetBoxManager() {
this.createTweetBoxAtTarget = function(a, b) {
this.createTweetBox(a.target, b)
}, this.createTweetBox = function(a, b) {
var c = $(a);
if (!((b.eventData || {}).scribeContext || {}).component) throw new Error("Please specify scribing component for tweet box.");
c.find(".geo-picker").length > 0 && GeoPicker.attachTo(c.find(".geo-picker"), b, {
parent: c
});
var d = c.find("div.rich-editor").length > 0 ? [withRichEditor] : [],
e = (b.dmOnly ? DmComposer : TweetBox).mixin.apply(this, d),
f = {
typeaheadData: this.attr.typeaheadData
};
e.attachTo(c, f, b)
}, this.after("initialize", function() {
this.on("uiInitTweetbox", this.createTweetBoxAtTarget)
})
}
var TweetBox = require("app/ui/compose/tweet_box"),
DmComposer = require("app/ui/compose/dm_composer"),
GeoPicker = require("app/ui/geo_picker"),
defineComponent = require("core/component"),
withRichEditor = require("app/ui/compose/with_rich_editor"),
TweetBoxManager = defineComponent(tweetBoxManager);
module.exports = TweetBoxManager
});
Obviously, this "answer" doesn't solve anything, but hopefully could provide enough to (re-)spark a conversation about this topic.
Related
Make a sticky scrollable sidebar with no styles applied through JS
That's how it should work. I saw this sidebar some time ago and was able to find the page in the web archive. When you scroll down the page, the sidebar scrolls too and sticks to the bottom. When you scroll up, even if you're somewhere in the middle of the page, the sidebar scrolls up too. This solution is fairly simple and doesn't apply any CSS while the sidebar is working. Some kind of magic using initial CSS like full viewport height, sticky positioning, hidden overflow and JS like scrollTop. I managed to pull out the part of the source code that's responsible for the sidebar, but I can't understand how it works. This function seems to be responsible for such behavior: function(e, t) { Air.define( 'module.sticky_sidebar', 'lib.DOM, module.DOM, module.metrics, module.propaganda, module.notify, module.smart_ajax', function(e, t, n, i, o, r) { var a, s, l, c = this, u = 0, d = !1, h = function() { var t = s.scrollTop, i = Math.round(e.rect(a).top) 50 === i ? (s.scrollTop = t + (n.scroll_top - u)) : i > 50 ? (s.scrollTop = 0) : i < 50 && (s.scrollTop = 999999), (u = n.scroll_top) }, f = function() { a && s && e.bem.toggle(a, 'height_auto', !(n.window_height - 50 < s.scrollHeight)) }, m = function(t) { if (((5 != t && 3 != t) || (l[t] = !1), !1 === l[5] && !1 === l[3])) { var n = e.find('.page--entry') n && (e.toggleClass(n, 'with--entry_center', !0), c.destroy()), (n = null) } } ;(c.init = function() { ;(a = c.elements[0].element), (s = e.find(a, '.sticky_sidebar__scroll')), (l = { 5: !0, 3: !0 }), n.on('Breakpoint changed', function(e) { 'wide' === e || 'desktop' === e ? !1 === d && n.document_height - 20 > n.window_height && (t.on('Window scroll', h), t.on('Window resize', f), f(), (d = !0)) : !0 === d && (t.off(), (d = !1)) }) }), (c.refresh = function() { c.destroy(), c.init() }), (c.destroy = function() { t.off(), n.off(), i.off(), (u = 0), (a = s = null), (d = !1) }) } ) } And the CSS: .sticky_sidebar { top: 50px; height: calc(100vh - 50px); width: 300px; margin-top: -20px; position: sticky; } .sticky_sidebar__scroll { width: 100%; height: 100%; overflow: hidden; } Can someone explain how this works?
DIsable JavaScript password strength meter
I would like to disable the JQuery password strength meter. I think it's running from the following script. Can I just remove the script link(s), or would it likely cause validation issues? Should I be un-enquing scripts instead? I am pretty clueless with JS, an example would be greatly appreciated. jQuery(function(s) { var r = { init: function() { s(document.body).on("keyup change", "form.register #reg_password, form.checkout #account_password, form.edit-account #password_1, form.lost_reset_password #password_1", this.strengthMeter), s("form.checkout #createaccount").change() }, strengthMeter: function() { var e = s("form.register, form.checkout, form.edit-account, form.lost_reset_password"), t = s('input[type="submit"]', e), a = s("#reg_password, #account_password, #password_1", e), o = 1, d = a.val(); r.includeMeter(e, a), o = r.checkPasswordStrength(e, a), d.length > 0 && o < wc_password_strength_meter_params.min_password_strength && !e.is("form.checkout") ? t.attr("disabled", "disabled").addClass("disabled") : t.removeAttr("disabled", "disabled").removeClass("disabled") }, includeMeter: function(r, e) { var t = r.find(".woocommerce-password-strength"); "" === e.val() ? (t.remove(), s(document.body).trigger("wc-password-strength-removed")) : 0 === t.length && (e.after('<div class="woocommerce-password-strength" aria-live="polite"></div>'), s(document.body).trigger("wc-password-strength-added")) }, checkPasswordStrength: function(s, r) { var e = s.find(".woocommerce-password-strength"), t = s.find(".woocommerce-password-hint"), a = '<small class="woocommerce-password-hint">' + wc_password_strength_meter_params.i18n_password_hint + "</small>", o = wp.passwordStrength.meter(r.val(), wp.passwordStrength.userInputBlacklist()), d = ""; switch (e.removeClass("short bad good strong"), t.remove(), o < wc_password_strength_meter_params.min_password_strength && (d = " - " + wc_password_strength_meter_params.i18n_password_error), o) { case 0: e.addClass("short").html(pwsL10n["short"] + d), e.after(a); break; case 1: case 2: e.addClass("bad").html(pwsL10n.bad + d), e.after(a); break; case 3: e.addClass("good").html(pwsL10n.good + d); break; case 4: e.addClass("strong").html(pwsL10n.strong + d); break; case 5: e.addClass("short").html(pwsL10n.mismatch) } return o } }; r.init() });
for jquery try $('#your-password-textbox').unbind() It will remove all event handlers for selected element.
Replace img with lazyload
I'm using lazyload plugin on my page and it has data-src parameter and at the same time I'm using another plugin to replace my image on responsive and it's using data-src parameter too.and I change name of data-src as data-swapMeto not conflict. but I wonder that lazyload notice my image or not ? which one is work lazy ? replace img ? or both ? and another thing is there any way to remove data-src-base my path can be different click to see my project on codepen function makeImagesResponsive() { var e = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth, t = document.getElementsByTagName("body")[0].getElementsByTagName("img"); if (t.length === 0) return; var n; t[0].hasAttribute ? n = function(e, t) { return e.hasAttribute(t) } : n = function(e, t) { return e.getAttribute(t) !== null }; var r = window.devicePixelRatio ? window.devicePixelRatio >= 1.2 ? 1 : 0 : 0; for (var i = 0; i < t.length; i++) { var s = t[i], o = r && n(s, "data-swapMe2x") ? "data-swapMe2x" : "data-swapMe", u = r && n(s, "data-src-base2x") ? "data-src-base2x" : "data-src-base"; if (!n(s, o)) continue; var a = n(s, u) ? s.getAttribute(u) : "", f = s.getAttribute(o), l = f.split(","); for (var c = 0; c < l.length; c++) { var h = l[c].split(":"), p = h[0], d = h[1], v, m; if (p.indexOf("<") !== -1) { v = p.split("<"); if (l[c - 1]) { var g = l[c - 1].split(/:(.+)/), y = g[0].split("<"); m = e <= v[1] && e > y[1] } else m = e <= v[1] } else { v = p.split(">"); if (l[c + 1]) { var b = l[c + 1].split(/:(.+)/), w = b[0].split(">"); m = e >= v[1] && e < w[1] } else m = e >= v[1] } if (m) { var E = a + d; s.src !== E && s.setAttribute("src", E); break } } } } if (window.addEventListener) { window.addEventListener("load", makeImagesResponsive, !1); window.addEventListener("resize", makeImagesResponsive, !1) } else { window.attachEvent("onload", makeImagesResponsive); window.attachEvent("onresize", makeImagesResponsive) }; <html lang="en"> <head> <meta charset="UTF-8" /> </head> <body> <aside> <img alt='kitten!' data-src-base='http://yurtici.anitur.com.tr/musteri/ingoing/2017/htm/img/' data-src="http://yurtici.anitur.com.tr/musteri/ingoing/2017/htm/img/1.jpg" data-swapMe='<480:4.jpg,<768:3.jpg,<960:2.jpg,>960:1.jpg' class="lazyload" /> </aside> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/2.0.7/lazysizes.min.js"></script> </body> </html>
How to scroll down to content box in this video style with jquery/javascript?
I have a page with video styles - http://picovico.com/video-styles/ in my WordPress. Everything is working fine, except that I would like to scroll down to content when the thumbnails are clicked. Right now the content box is opening but the window is not scrolling down to it. Actually I am using a plugin called expand grid. I am not getting support from the plugin author. I am using bellow code: $(".cq-expandgrid-item").click(function() { $('html, body').animate({ scrollTop: $(".cq-expandgrid-content").offset().top }, 5000); }); Thanks. #TTCC Here's the init.min.js present in the plugin file. The code is given below. With your help, I hope I can locate and add the code you suggested now: jQuery(document).ready(function(a) { a(".cq-expandgrid").each(function(b, c) { function r() { o = setInterval(function() { clearInterval(o), k++, k > m && (k = 0), a(".cq-expandgrid-toggle", p).eq(k).trigger("click"), r() }, 1e3 * j) } var d = a(this), e = a(this).data("itemsize"), f = "yes" == a(this).data("transparentitem") ? !0 : !1, g = a(this).data("labelfontsize"), h = a(this).data("subfontsize"), i = parseInt(a(this).data("itemheight"), 10), j = parseInt(a(this).data("autoslide"), 10), k = 0, m = a(".cq-expandgrid-item", d).length, n = "yes" == a(this).data("openfirst") ? !1 : !0, o = 0, p = a(".cq-expandgrid-item", d).each(function(b) { a(this).data("index", b); var c = a(this).data("image"), d = a(this).data("avatar"), f = a(this).data("backgroundcolor"), j = a(this).data("iconcolor"), k = a(this).data("iconsize"), l = a(this).data("contentcolor"), m = a(this).data("labelcolor"), n = a(this).data("subtitlecolor"), o = a(this).data("bgstyle"), p = a(this).data("avatartype"), q = a(this), r = a(this).attr("title"); if (r && "" !== r) var r = a(".cq-expandgrid-face", q).tooltipster({ content: r, position: "top", delay: 200, interactive: !0, speed: 300, touchDevices: !0, animation: "grow", theme: "tooltipster-shadow", contentAsHTML: !0 }); "" != l && a(".cq-expandgrid-text, .cq-expandgrid-text p, .cq-expandgrid-text h2, .cq-expandgrid-text h3, .cq-expandgrid-text h4, .cq-expandgrid-text h5, .cq-expandgrid-text h6", q).css("color", l), "" != m && a(".cq-expandgrid-title", q).css("color", m), "" != n && a(".cq-expandgrid-subtitle", q).css("color", n), "" != g && a(".cq-expandgrid-title", q).css("font-size", g), "" != h && a(".cq-expandgrid-subtitle", q).css("font-size", h), i > 0 && "customized" == e && a(".cq-expandgrid-face", q).css("height", i), "" != f && "customized" == o && a(".cq-expandgrid-face", q).css("background-color", f), "" != j && a(".cq-expandgrid-icon", q).css("color", j), "" != k && a(".cq-expandgrid-icon", q).css("font-size", k), "" != c && "undefined" != c && c && a(".cq-expandgrid-face", q).css({ "background-image": "url(" + c + ")" }), "image" == p && "" != d && "undefined" != d && d && a(".cq-expandgrid-avatar", q).css({ "background-image": "url(" + d + ")" }) }), q = null; d.on("mouseover", function(a) { clearInterval(o) }).on("mouseleave", function(a) { j > 0 && r() }), a(".cq-expandgrid-toggle", p).click(function() { var b = a(this).closest(".cq-expandgrid-item"); b.data("backgroundcolor"); if (k = b.data("index"), clearInterval(o), q && !b.is(q)) { q.removeClass("cq-expandgrid-openstate").addClass("cq-expandgrid-initstate"), f && p.removeClass("outfoucs"); var d = a("iframe", q).attr("src"); d && "" != d && (d.indexOf("youtube") > -1 || d.indexOf("vimeo") > -1) && (a("iframe", q).attr("src", ""), a("iframe", q).attr("src", d)) } b.hasClass("cq-expandgrid-initstate") ? (q = b.removeClass("cq-expandgrid-initstate").addClass("cq-expandgrid-openstate"), p.not(b).hasClass("outfoucs") || f && p.not(b).addClass("outfoucs")) : (b.removeClass("cq-expandgrid-openstate").addClass("cq-expandgrid-initstate"), f && p.not(b).removeClass("outfoucs")) }), (n || j > 0) && a(".cq-expandgrid-toggle", p).eq(0).trigger("click"), j > 0 && r(), p.find(".cq-expandgrid-close").click(function() { var b = a(this).closest(".cq-expandgrid-item"); b.removeClass("cq-expandgrid-openstate").addClass("cq-expandgrid-initstate"), p.not(b).removeClass("outfoucs") }) }) }); #TTCC, Here's the code I implemented as per your suggestion: b.hasClass("cq-expandgrid-initstate") ? (q = b.removeClass("cq-expandgrid-initstate").addClass("cq-expandgrid-openstate"), p.not(b).hasClass("outfoucs") || f && p.not(b).addClass("outfoucs")) : (b.removeClass("cq-expandgrid-openstate").addClass("cq-expandgrid-initstate"), f && p.not(b).removeClass("outfoucs")), b.hasClass("cq-expandgrid-initstate") && a('body').stop().animate({scrollTop: b.find(".cq-expandgrid-content").offset().top - 50 }, 500); })
Your javascript code has two script tag in your page, and this error make code can not run. Actually, you don't need to write a piece of code alone, and just move it to the "cq-expandgrid-toggle" click event in vc-extensions-expandgrid/js/init.min.js" file. You can use jQuery.animate() and scrollTop property to achieve it. Replace code in init.min.js file from line 63 to 65 (before "})") by my code below: b.hasClass("cq-expandgrid-initstate") ? (a('body').stop().animate({scrollTop: b.find(".cq-expandgrid-content").offset().top - 0}, 200),q = b.removeClass("cq-expandgrid-initstate").addClass("cq-expandgrid-openstate"), p.not(b).hasClass("outfoucs") || f && p.not(b).addClass("outfoucs")) : (b.removeClass("cq-expandgrid-openstate").addClass("cq-expandgrid-initstate"), f && p.not(b).removeClass("outfoucs")); "500" is a number determining in millisecond how long the animation will run, and you can change it as your wish. And remove transition style of .cq-expandgrid-content in /wp-content/plugins/vc-extensions-expandgrid/css/style.css file (about line 378). transition: all 0.2s ease-in-out; Here is a jsfiddle.
Try like this: $(".cq-expandgrid-item").click(function() { var $this = $(this); $('html, body').animate({ scrollTop: $this.find(".cq-expandgrid-content").offset().top }, 5000); }); PD: with $(".cq-expandgrid-content").offset().top you where trying get multiple values, because there are many .cq-expandgrid-content" occurrences
How to get an animation to start once in viewport
I have a page that uses the fullpage.js plugin. This plugin allows the user to scroll down and an entire 100%vh screen to appear. My issue is that I have animations on different sections that I want to delay until that div is within the viewport. It took me a while to figure this out and was trying to do scroll functions, forgetting that fact I am not really scrolling. Before I was trying to do this: <div id="section1-right-container"> <div id="think"></div> </div> $(window).on("scroll", function(){ // Determine if the element is in the viewport if($('section1-right-container').visible(true)) { $('section1-right-container').addClass("think"); } }); I found the following code and modified it some, I am just unsure of how to elimate the scrolling part and to start the animation once the section1-right-container is in the viewport. // Returns true if the specified element has been scrolled into the viewport. /*function isElementInViewport(elem) { var $elem = $(elem); // Get the scroll position of the page. var scrollElem = ((navigator.userAgent.toLowerCase().indexOf('webkit') != -1) ? 'body' : 'html'); var viewportTop = $(scrollElem).scrollTop(); var viewportBottom = viewportTop + $(window).height(); // Get the position of the element on the page. var elemTop = Math.round( $elem.offset().top ); var elemBottom = elemTop + $elem.height(); return ((elemTop < viewportBottom) && (elemBottom > viewportTop)); } // Check if it's time to start the animation. /*function checkAnimation() { var $elem = $('#think'); // If the animation has already been started if ($elem.hasClass('start')) return; if (isElementInViewport($elem)) { // Start the animation $elem.addClass('start'); } } Anyone know what I could do? UPDATE - visible plugin (function(e) { e.fn.visible = function(t, n, r) { var i = e(this).eq(0), s = i.get(0), o = e(window), u = o.scrollTop(), a = u + o.height(), f = o.scrollLeft(), l = f + o.width(), c = i.offset().top, h = c + i.height(), p = i.offset().left, d = p + i.width(), v = t === true ? h : c, m = t === true ? c : h, g = t === true ? d : p, y = t === true ? p : d, b = n === true ? s.offsetWidth * s.offsetHeight : true, r = r ? r : "both"; if (r === "both") return !!b && m <= a && v >= u && y <= l && g >= f; else if (r === "vertical") return !!b && m <= a && v >= u; else if (r === "horizontal") return !!b && y <= l && g >= f } })(jQuery)
Why don't you make use of the fullPage.js callbacks such as onLeave or afterLoad? That's the purpose of them.