Skip to content

Instantly share code, notes, and snippets.

@fabianuribe
Last active November 23, 2022 11:03
Show Gist options
  • Save fabianuribe/6006ba448997f30af40d791f31f65c73 to your computer and use it in GitHub Desktop.
Save fabianuribe/6006ba448997f30af40d791f31f65c73 to your computer and use it in GitHub Desktop.
George's Twitter Search Box Hack Challenge
const fetchHeaders = {
accept: "*/*",
"accept-language": "en-US,en;q=0.9",
authorization:
"Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA", // This will expire, you can get a new one by inspecting the network requests on twitter.com
"cache-control": "no-cache",
pragma: "no-cache",
"sec-ch-ua":
'"Google Chrome";v="107", "Chromium";v="107", "Not=A?Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": '"macOS"',
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin",
"x-csrf-token": "9aa4a04e21356ad60975fa176e8cd883",
"x-guest-token": "1595319724329603074",
"x-twitter-active-user": "yes",
"x-twitter-client-language": "en",
};
const tokenStyles =
"display: flex; align-self: center; background: #1d9bf0; border-radius: 10px; padding: 2px 7px; color: #000;";
const tokenContainerStyles = "display: flex; gap: 10px;";
const createNode = (name, classname, styles, textContent) => {
const node = document.createElement(name);
node.classList.add(classname);
node.setAttribute("style", styles);
const content = document.createTextNode(textContent);
node.appendChild(content);
return node;
};
const createImageNode = (url, style) => {
const node = document.createElement("img");
node.setAttribute("src", url);
node.setAttribute(
"style",
style || "display: width: 20px; height: 20px; border-radius: 50%;"
);
return node;
};
const searchBoxParent = document.querySelector(
"#react-root > div > div > div.css-1dbjc4n.r-18u37iz.r-13qz1uu.r-417010 > main > div > div > div > div > div > div.css-1dbjc4n.r-aqfbo4.r-gtdqiz.r-1gn8etr.r-1g40b8q > div.css-1dbjc4n.r-1e5uvyk.r-5zmot > div.css-1dbjc4n.r-136ojw6 > div > div > div > div > div.css-1dbjc4n.r-16y2uox.r-1wbh5a2.r-1pi2tsx.r-1777fci > div.css-1dbjc4n.r-1awozwy.r-18u37iz.r-16y2uox.r-1wbh5a2.r-4amgru.r-itp27i > div > div > div > form > div.css-1dbjc4n.r-1wbh5a2 > div > div > div > label > div.css-1dbjc4n.r-16y2uox.r-1wbh5a2 > div"
);
const tokenList = ["from:"];
const tokenizeQuery = (query) => {
const tokens = query.split(" ");
if (tokens.length > 1) {
const tokenNodes = tokens
.map((token) => {
if (tokenList.includes(token)) {
return createNode("span", "token", tokenStyles, token);
}
return null;
})
.filter((node) => node !== null);
return tokenNodes;
} else {
return [];
}
};
var searchBox = searchBoxParent.querySelector("input");
searchBoxParent.prepend(
createNode("div", "token-container", tokenContainerStyles, "")
);
const tokenContainer = document.querySelector(".token-container");
searchBox.addEventListener("input", (e) => {
e.stopImmediatePropagation;
const query = e.target.value;
const tokens = tokenizeQuery(query);
if (tokens.length > 0) {
searchBox.value = query.split(" ").pop();
tokens.forEach((token) => {
tokenContainer.append(token);
});
}
if (searchBox.value.length > 0) {
findUserInSuggestions(searchBox.value);
}
});
const fetchSuggestions = async (query) => {
return fetch(
`https://twitter.com/i/api/1.1/search/typeahead.json?include_ext_is_blue_verified=1&q=${query}&src=search_box&result_type=events%2Cusers%2Ctopics`,
{
headers: fetchHeaders,
referrer: "https://twitter.com/",
referrerPolicy: "strict-origin-when-cross-origin",
body: null,
method: "GET",
mode: "cors",
credentials: "include",
}
).then((response) => {
if (response.ok) {
return response.json();
}
return {};
});
};
const findUserInSuggestions = async (username) => {
const suggestions = await fetchSuggestions(username);
const users = (suggestions && suggestions.users) || [];
const user = users.find((user) => user.screen_name === username);
if (user) {
const userNode = createNode("div", "token", tokenStyles, username);
const userPfp = createImageNode(user.profile_image_url_https);
userNode.prepend(userPfp);
tokenContainer.append(userNode);
searchBox.value = "";
injectUsersLastTweets(username);
}
};
const fetchLastTweets = async (username) => {
return fetch(
`https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name=${username}&count=2`,
{
headers: fetchHeaders,
referrer: "https://twitter.com/",
referrerPolicy: "strict-origin-when-cross-origin",
body: null,
method: "GET",
mode: "cors",
credentials: "include",
}
).then((response) => {
if (response.ok) {
return response.json();
}
return {};
});
};
const injectUsersLastTweets = async (username) => {
const tweets = await fetchLastTweets(username);
const suggestionsPanel = document.querySelector("#typeaheadDropdown-1");
if (tweets.length > 0 && suggestionsPanel) {
tweets.reverse().forEach((tweet) => {
suggestionsPanel.prepend(createTweetNode(tweet));
});
suggestionsPanel.prepend(
createNode(
"div",
"tweet-separator",
`border: 0 solid black; box-sizing: border-box; padding-left: 16px; padding-right: 16px; padding-bottom: 16px; padding-top: 16px; min-width: 0px; word-wrap: break-word; line-height: 20px; font-size: 15px; font-weight: 400; font-family: TwitterChirp, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; color: rgb(231, 233, 234);`,
`Latest Tweets from ${username}`
)
)``;
}
};
const createTweetNode = (tweet) => {
const displayNameNode = createNode(
"div",
"display-name",
"font-weight: bold; margin-bottom: 2px",
tweet.user.name
);
const usernameNode = createNode(
"div",
"username",
"opacity: 0.5; margin-bottom: 2px",
tweet.user.screen_name
);
const tweetNode = createNode("div", "tweet", "", tweet.text);
const textWrapper = createNode("div", "tweet-wrapper", "color: white;", "");
textWrapper.append(displayNameNode);
textWrapper.append(usernameNode);
textWrapper.append(tweetNode);
const pfpNode = createImageNode(
tweet.user.profile_image_url_https,
"width: 56px; height: 56px; border-radius: 50%;"
);
const tweetContainer = createNode(
"div",
"tweet-container",
`display:flex; gap: 10px; padding: 16px 12px; color: white; color: white; background: #0d0d0d; font-family: TwitterChirp, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;`,
""
);
tweetContainer.append(pfpNode);
tweetContainer.append(textWrapper);
return tweetContainer;
};
MIT License
Copyright (c) Meta Platforms, Inc. and affiliates.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment