嗯,可能一進來大部分人都會以爲,爲何還會有人重複造輪子,GitHub第三方客戶端都已經爛大街啦。確實,一開始我本身也是這麼以爲的,也問過本身是否真的有意義再去作這樣一個項目。思考再三,如下緣由也決定了我願意去作一個讓本身滿意的GitHub第三方客戶端。javascript
對於時常關注GitHub Trending列表的筆者來講,迫切須要一個更簡單的方式隨時隨地去跟隨GitHub最新的技術潮流;css
已有的一些GitHub小程序客戶端顏值與功能並不能知足筆者的要求;html
據說iOS開發沒人要了,掌握一門新的開發技能,又未嘗不可?前端
其實也沒那麼多緣由,既然想作,那就去作,開心最重要。vue
GitHub:github.com/huangjianke…,多是目前顏值最高的GitHub小程序客戶端,歡迎starjava
數據來源:GitHub API v3git
目前實現的功能有:github
實時查看Trending小程序
顯示用戶列表微信小程序
倉庫和用戶的搜索
倉庫:詳情展現、README.md展現、Star/Unstar、Fork、Contributors展現、查看倉庫文件內容
開發者:Follow/Unfollow、顯示用戶的followers/following
Issue:查看issue列表、新增issue、新增issue評論
分享倉庫、開發者
...
Gitter的初衷並非想把網頁端全部功能照搬到小程序上,由於那樣的體驗並不會很友好,好比說,筆者本身也不想在手機上閱讀代碼,那將會是一件很痛苦的事。
在保證用戶體驗的前提下,讓用戶用更簡單的方式獲得本身想要的,這是一件有趣的事。
第一次以爲,在茫茫前端的世界裏,本身是那麼眇小。
當決定去作這個項目的時候,就開始了快馬加鞭的技術選型,但擺在本身面前的選擇是那麼的多,也不得不感慨,前端的世界,真的很精彩。
原生開發:基本上一開始就放棄了,開發體驗很不友好;
mpvue:用Vue的方式去開發小程序,我的以爲文檔並非很齊全,加上近期維護比較少,多是趨於穩定了?
Taro:用React的方式去開發小程序,Taro團隊的小夥伴維護真的很勤快,也很耐心的解答你們疑問,文檔也比較齊全,開發體驗也很棒,還能夠一鍵生成多端運行的代碼(暫沒嘗試)
貨比三家,通過一段時間的嘗試及踩坑,綜合本身目前的能力,最終肯定了Gitter的技術選型:
Taro + Taro UI + Redux + 雲開發 Node.js
其實,做爲一名Coder,曾經一直想找個UI設計師妹子作老婆的(確定有和我同樣想法的Coder),多搭配啊。如今想一想,code不是生活的所有,如今的我同樣很幸福。
話回正題,沒有設計師老婆頁面設計怎麼辦?畢竟筆者想要的是一款高顏值的GitHub小程序。
嗯,不慌,默默的拿出了筆者沉寂已久的Photoshop和Sketch。不敢說本身的設計能力如何,Gitter的設計至少是能讓筆者本身心情愉悅的,假若哪位設計愛好者想對Gitter的設計進行改良,歡迎歡迎,十二分的歡迎!
Talk is cheap. Show me the code.
做爲一篇技術性文章,怎可能少得了代碼。
在這裏主要寫寫幾個踩坑點,做爲一個前端小白,相信各位讀者均是筆者的前輩,還望多多指教!
進入開發階段沒多久,就遇到了第一個坑。GitHub竟然沒有提供Trending列表的API!!!
也沒有過多的去想GitHub爲何不提供這個API,只想着怎麼去儘快填好這個坑。一開始嘗試使用Scrapy寫一個爬蟲對網頁端的Trending列表信息進行定時爬取及存儲供小程序端使用,但最終仍是放棄了這個作法,由於筆者並無服務器與已經備案好的域名,小程序的雲開發也只支持Node.js的部署。
開源的力量仍是強大,最終找到了github-trending-api,稍做修改,成功部署到小程序雲開發後臺,在此,感謝原做者的努力。
async function fetchRepositories({ language = '', since = 'daily', } = {}) {
const url = `${GITHUB_URL}/trending/${language}?since=${since}`;
const data = await fetch(url);
const $ = cheerio.load(await data.text());
return (
$('.repo-list li')
.get()
// eslint-disable-next-line complexity
.map(repo => {
const $repo = $(repo);
const title = $repo
.find('h3')
.text()
.trim();
const relativeUrl = $repo
.find('h3')
.find('a')
.attr('href');
const currentPeriodStarsString =
$repo
.find('.float-sm-right')
.text()
.trim() || /* istanbul ignore next */ '';
const builtBy = $repo
.find('span:contains("Built by")')
.parent()
.find('[data-hovercard-type="user"]')
.map((i, user) => {
const altString = $(user)
.children('img')
.attr('alt');
const avatarUrl = $(user)
.children('img')
.attr('src');
return {
username: altString
? altString.slice(1)
: /* istanbul ignore next */ null,
href: `${GITHUB_URL}${user.attribs.href}`,
avatar: removeDefaultAvatarSize(avatarUrl),
};
})
.get();
const colorNode = $repo.find('.repo-language-color');
const langColor = colorNode.length
? colorNode.css('background-color')
: null;
const langNode = $repo.find('[itemprop=programmingLanguage]');
const lang = langNode.length
? langNode.text().trim()
: /* istanbul ignore next */ null;
return omitNil({
author: title.split(' / ')[0],
name: title.split(' / ')[1],
url: `${GITHUB_URL}${relativeUrl}`,
description:
$repo
.find('.py-1 p')
.text()
.trim() || /* istanbul ignore next */ '',
language: lang,
languageColor: langColor,
stars: parseInt(
$repo
.find(`[href="${relativeUrl}/stargazers"]`)
.text()
.replace(',', '') || /* istanbul ignore next */ 0,
10
),
forks: parseInt(
$repo
.find(`[href="${relativeUrl}/network"]`)
.text()
.replace(',', '') || /* istanbul ignore next */ 0,
10
),
currentPeriodStars: parseInt(
currentPeriodStarsString.split(' ')[0].replace(',', '') ||
/* istanbul ignore next */ 0,
10
),
builtBy,
});
})
);
}
複製代碼
async function fetchDevelopers({ language = '', since = 'daily' } = {}) {
const data = await fetch(
`${GITHUB_URL}/trending/developers/${language}?since=${since}`
);
const $ = cheerio.load(await data.text());
return $('.explore-content li')
.get()
.map(dev => {
const $dev = $(dev);
const relativeUrl = $dev.find('.f3 a').attr('href');
const name = getMatchString(
$dev
.find('.f3 a span')
.text()
.trim(),
/^\((.+)\)$/i
);
$dev.find('.f3 a span').remove();
const username = $dev
.find('.f3 a')
.text()
.trim();
const $repo = $dev.find('.repo-snipit');
return omitNil({
username,
name,
url: `${GITHUB_URL}${relativeUrl}`,
avatar: removeDefaultAvatarSize($dev.find('img').attr('src')),
repo: {
name: $repo
.find('.repo-snipit-name span.repo')
.text()
.trim(),
description:
$repo
.find('.repo-snipit-description')
.text()
.trim() || /* istanbul ignore next */ '',
url: `${GITHUB_URL}${$repo.attr('href')}`,
},
});
});
}
複製代碼
// 雲函數入口函數
exports.main = async (event, context) => {
const { type, language, since } = event
let res = null;
let date = new Date()
if (type === 'repositories') {
const cacheKey = `repositories::${language || 'nolang'}::${since || 'daily'}`;
const cacheData = await db.collection('repositories').where({
cacheKey: cacheKey
}).orderBy('cacheDate', 'desc').get()
if (cacheData.data.length !== 0 &&
((date.getTime() - cacheData.data[0].cacheDate) < 1800 * 1000)) {
res = JSON.parse(cacheData.data[0].content)
} else {
res = await fetchRepositories({ language, since });
await db.collection('repositories').add({
data: {
cacheDate: date.getTime(),
cacheKey: cacheKey,
content: JSON.stringify(res)
}
})
}
} else if (type === 'developers') {
const cacheKey = `developers::${language || 'nolang'}::${since || 'daily'}`;
const cacheData = await db.collection('developers').where({
cacheKey: cacheKey
}).orderBy('cacheDate', 'desc').get()
if (cacheData.data.length !== 0 &&
((date.getTime() - cacheData.data[0].cacheDate) < 1800 * 1000)) {
res = JSON.parse(cacheData.data[0].content)
} else {
res = await fetchDevelopers({ language, since });
await db.collection('developers').add({
data: {
cacheDate: date.getTime(),
cacheKey: cacheKey,
content: JSON.stringify(res)
}
})
}
}
return {
data: res
}
}
複製代碼
嗯,這是一個大坑。
在作技術調研的時候,發現小程序端Markdown解析主要有如下方案:
wxParse:做者最後一次提交已經是兩年前了,通過本身的嘗試,也確實發現已經不適合如README.md的解析
wemark:一款很優秀的微信小程序Markdown渲染庫,但通過筆者嘗試以後,發現對README.md的解析並不完美
towxml:目前發現是微信小程序最完美的Markdown渲染庫,已經能近乎完美的對README.md進行解析並展現
在Markdown解析這一塊,最終採用的也是towxml,但發如今解析性能這一塊,目前並非很優秀,對一些比較大的數據解析也超出了小程序所能承受的範圍,還好貼心的做者(sbfkcel)提供了服務端的支持,在此感謝做者的努力!
const Towxml = require('towxml');
const towxml = new Towxml();
// 雲函數入口函數
exports.main = async (event, context) => {
const { func, type, content } = event
let res
if (func === 'parse') {
if (type === 'markdown') {
res = await towxml.toJson(content || '', 'markdown');
} else {
res = await towxml.toJson(content || '', 'html');
}
}
return {
data: res
}
}
複製代碼
import Taro, { Component } from '@tarojs/taro'
import PropTypes from 'prop-types'
import { View, Text } from '@tarojs/components'
import { AtActivityIndicator } from 'taro-ui'
import './markdown.less'
import Towxml from '../towxml/main'
const render = new Towxml()
export default class Markdown extends Component {
static propTypes = {
md: PropTypes.string,
base: PropTypes.string
}
static defaultProps = {
md: null,
base: null
}
constructor(props) {
super(props)
this.state = {
data: null,
fail: false
}
}
componentDidMount() {
this.parseReadme()
}
parseReadme() {
const { md, base } = this.props
let that = this
wx.cloud.callFunction({
// 要調用的雲函數名稱
name: 'parse',
// 傳遞給雲函數的event參數
data: {
func: 'parse',
type: 'markdown',
content: md,
}
}).then(res => {
let data = res.result.data
if (base && base.length > 0) {
data = render.initData(data, {base: base, app: this.$scope})
}
that.setState({
fail: false,
data: data
})
}).catch(err => {
console.log('cloud', err)
that.setState({
fail: true
})
})
}
render() {
const { data, fail } = this.state
if (fail) {
return (
<View className='fail' onClick={this.parseReadme.bind(this)}> <Text className='text'>load failed, try it again?</Text> </View>
)
}
return (
<View>
{
data ? (
<View>
<import src='../towxml/entry.wxml' />
<template is='entry' data='{{...data}}' />
</View>
) : (
<View className='loading'>
<AtActivityIndicator size={20} color='#2d8cf0' content='loading...' />
</View>
)
}
</View>
)
}
}
複製代碼
其實,筆者在該項目中,對Redux的使用並很少。一開始,筆者以爲全部的接口請求都應該經過Redux操做,後面才發現,並非全部的操做都必須使用Redux,最後,在本項目中,只有獲取我的信息的時候使用了Redux。
// 獲取我的信息
export const getUserInfo = createApiAction(USERINFO, (params) => api.get('/user', params))
複製代碼
export function createApiAction(actionType, func = () => {}) {
return (
params = {},
callback = { success: () => {}, failed: () => {} },
customActionType = actionType,
) => async (dispatch) => {
try {
dispatch({ type: `${customActionType }_request`, params });
const data = await func(params);
dispatch({ type: customActionType, params, payload: data });
callback.success && callback.success({ payload: data })
return data
} catch (e) {
dispatch({ type: `${customActionType }_failure`, params, payload: e })
callback.failed && callback.failed({ payload: e })
}
}
}
複製代碼
getUserInfo() {
if (hasLogin()) {
userAction.getUserInfo().then(()=>{
Taro.hideLoading()
Taro.stopPullDownRefresh()
})
} else {
Taro.hideLoading()
Taro.stopPullDownRefresh()
}
}
const mapStateToProps = (state, ownProps) => {
return {
userInfo: state.user.userInfo
}
}
export default connect(mapStateToProps)(Index)
複製代碼
export default function user (state = INITIAL_STATE, action) {
switch (action.type) {
case USERINFO:
return {
...state,
userInfo: action.payload.data
}
default:
return state
}
}
複製代碼
目前,筆者對Redux仍是處於只知其一;不知其二的狀態,嗯,學習的路還很長。
當Gitter第一個版本經過審覈的時候,心情是很激動的,就像本身的孩子同樣,看着他一點一點的長大,筆者也很享受這樣一個項目從無到有的過程,在此,對那些幫助過筆者的人一併表示感謝。
固然,目前功能和體驗上可能有些不大完善,也但願你們能提供一些寶貴的意見,Gitter走向完美的路上但願有你!
最後,但願Gitter小程序能對你有所幫助!