Skip to content

Instantly share code, notes, and snippets.

@khsk
Last active September 26, 2017 01:26
Show Gist options
  • Save khsk/08b545586899ce263b7eea87986bc764 to your computer and use it in GitHub Desktop.
Save khsk/08b545586899ce263b7eea87986bc764 to your computer and use it in GitHub Desktop.
Qiitaのフィードに記事投稿者の名前を表示するユーザースクリプト ref: http://qiita.com/khsk/items/e93df0adef897fea8fe2
// ==UserScript==
// @name Qiita show username to feed
// @namespace khsk
// @description フィードに投稿者の名前を追加する
// @include http://qiita.com/
// @include https://qiita.com/
// @include http://qiita.com/items
// @include https://qiita.com/items
// @include http://qiita.com/stock
// @include https://qiita.com/stock
// @include http://qiita.com/mine
// @include https://qiita.com/mine
// @version 1
// @grant none
// ==/UserScript==
console.time('show name');
//const FEED_ITEMS = 20; // 一度に読み込むフィード数
const ITEN_CLASS = 'item-box track' // 'item-box track hidden'はおそらく投稿のタグを複数フォローしていたとき、ひとつ以外につけられる。だから、見るたびに同じ記事でもタグ表記が異なるフィードになることがあると思う。
const getUserName = node => {
const link = node.querySelector('div.item-box-title > h1 > a');
return link.href.match(/https?:\/\/qiita.com\/([^/]+)/)[1];
};
const createUserNameNode = parentNode => {
const userName = getUserName(parentNode);
const a = document.createElement('a');
a.href = 'https://qiita.com/' + userName;
a.innerHTML = ' ' + userName + ' ';
const span = document.createElement('span');
// タグ名みたいに太文字にするよ
span.className = 'user';
// insertBeforeが面倒くさい
span.innerHTML = ' ' + a.outerHTML + ' ';
return span;
}
const insertUserNameNode = (parentNode) => {
const userNameNode = createUserNameNode(parentNode);
// 語尾変化 : 挿入前 + 挿入後
const insertPattarn = {
'の' : /(に)(新しい投稿がありました)/,
// いいねと!コメントが!なぜか!spanに!囲まれている!!
'の投稿に' : /(が)(<span>(?:コメント|いいね)<\/span>しました)/,
// フォロイーの投稿は別にいいよね。
};
const action = parentNode.querySelector('div.item-box-header > div.action');
if (action == null) {
return;
}
let html = action.innerHTML;
// ここわかりにくい
for (let suffix in insertPattarn) {
let newHtml = html.replace(insertPattarn[suffix], '$1' + userNameNode.outerHTML + suffix + '$2');
if (newHtml != html) {
action.innerHTML = newHtml;
break;
}
}
}
const mo = new MutationObserver((mutationRecords, data2) => {
mutationRecords.forEach(mutationRecord =>{
if (mutationRecord.addedNodes == null) {
return;
}
// 追加だけでもいろいろ引っかかるので、1フィード読み込み件数をひとつのフィルターにする
// が、表示後の「n件の新しいアクティビティ」に対応できないと思う。気にしないってときは使う
// if (mutationRecord.addedNodes.length != FEED_ITEMS) {
// return;
// }
mutationRecord.addedNodes.forEach(node => {
// フィードであることをクラス名でチェック
if(node.className != ITEN_CLASS) {
return;
}
insertUserNameNode(node);
});
});
});
const items = document.getElementsByClassName('col-sm-9')[0];
const options = {childList: true, subtree:true};
mo.observe(items, options);
console.timeEnd('show name');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment