Gitter - 高顏值GitHub小程序客戶端誕生記

0. 前言

嗯,可能一進來大部分人都會覺得,爲什麼還會有人重複造輪子,GitHub第三方客戶端都已經爛大街啦。確實,一開始我自己也是這麼覺得的,也問過自己是否真的有意義再去做這樣一個項目。思考再三,以下原因也決定了我願意去做一個讓自己滿意的GitHub第三方客戶端。

  • 對於時常關注GitHub Trending列表的筆者來說,迫切需要一個更簡單的方式隨時隨地去跟隨GitHub最新的技術潮流;
  • 已有的一些GitHub小程序客戶端顏值與功能並不能滿足筆者的要求;
  • 聽說iOS開發沒人要了,掌握一門新的開發技能,又何嘗不可?
  • 其實也沒那麼多原因,既然想做,那就去做,開心最重要。

1. Gitter

Gitter

目前實現的功能有:

  • 實時查看Trending
  • 顯示用戶列表
  • 倉庫和用戶的搜索
  • 倉庫:詳情展示、README.md展示、Star/Unstar、Fork、Contributors展示、查看倉庫文件內容
  • 開發者:Follow/Unfollow、顯示用戶的followers/following
  • Issue:查看issue列表、新增issue、新增issue評論
  • 分享倉庫、開發者
  • ...

Gitter的初衷並不是想把網頁端所有功能照搬到小程序上,因爲那樣的體驗並不會很友好,比如說,筆者自己也不想在手機上閱讀代碼,那將會是一件很痛苦的事。

在保證用戶體驗的前提下,讓用戶用更簡單的方式得到自己想要的,這是一件有趣的事。

2. 探索篇

技術選型

第一次覺得,在茫茫前端的世界裏,自己是那麼渺小。

當決定去做這個項目的時候,就開始了馬不停蹄的技術選型,但擺在自己面前的選擇是那麼的多,也不得不感慨,前端的世界,真的很精彩。

  • 原生開發:基本上一開始就放棄了,開發體驗很不友好;
  • WePY:之前用這個框架已經開發過一個小程序,詩詞墨客,不得不說,坑是真多,用過的都知道;
  • mpvue:用Vue的方式去開發小程序,個人覺得文檔並不是很齊全,加上近期維護比較少,可能是趨於穩定了?
  • Taro:用React的方式去開發小程序,Taro團隊的小夥伴維護真的很勤快,也很耐心的解答大家疑問,文檔也比較齊全,開發體驗也很棒,還可以一鍵生成多端運行的代碼(暫沒嘗試)

貨比三家,經過一段時間的嘗試及採坑,綜合自己目前的能力,最終確定了Gitter的技術選型:

Taro + Taro UI + Redux + 雲開發 Node.js

頁面設計

其實,作爲一名Coder,曾經一直想找個UI設計師妹子做老婆的(肯定有和我一樣想法的Coder),多搭配啊。現在想想,code不是生活的全部,現在的我一樣很幸福。

話回正題,沒有設計師老婆頁面設計怎麼辦?畢竟筆者想要的是一款高顏值的GitHub小程序。
嗯,不慌,默默的拿出了筆者沉寂已久的Photoshop和Sketch。不敢說自己的設計能力如何,Gitter的設計至少是能讓筆者自己心情愉悅的,倘若哪位設計愛好者想對Gitter的設計進行改良,歡迎歡迎,十二分的歡迎!

3. 開發篇

Talk is cheap. Show me the code.

作爲一篇技術性文章,怎可能少得了代碼。
在這裏主要寫寫幾個採坑點,作爲一個前端小白,相信各位讀者均是筆者的前輩,還望多多指教!

Trending

進入開發階段沒多久,就遇到了第一個坑。GitHub居然沒有提供Trending列表的API!!!
也沒有過多的去想GitHub爲什麼不提供這個API,只想着怎麼去儘快填好這個坑。一開始嘗試使用Scrapy寫一個爬蟲對網頁端的Trending列表信息進行定時爬取及存儲供小程序端使用,但最終還是放棄了這個做法,因爲筆者並沒有服務器與已經備案好的域名,小程序的雲開發也只支持Node.js的部署。

開源的力量還是強大,最終找到了github-trending-api,稍作修改,成功部署到小程序雲開發後臺,在此,感謝原作者的努力。

  • 爬取Trending Repositories
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,
        });
      })
  );
}
  • 爬取Trending Developers
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')}`,
        },
      });
    });
}
  • Trending列表雲函數
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解析

嗯,這是一個大坑。
在做技術調研的時候,發現小程序端Markdown解析主要有以下方案:

  • wxParse:作者最後一次提交已是兩年前了,經過自己的嘗試,也確實發現已經不適合如README.md的解析
  • wemark:一款很優秀的微信小程序Markdown渲染庫,但經過筆者嘗試之後,發現對README.md的解析並不完美
  • towxml:目前發現是微信小程序最完美的Markdown渲染庫,已經能近乎完美的對README.md進行解析並展示

在Markdown解析這一塊,最終採用的也是towxml,但發現在解析性能這一塊,目前並不是很優秀,對一些比較大的數據解析也超出了小程序所能承受的範圍,還好貼心的作者(sbfkcel)提供了服務端的支持,在此感謝作者的努力!

最近這個項目🔥了,只能說跟不上年輕人的節奏了。
Dress

  • Markdown解析雲函數
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
  }
}
  • markdown.js組件
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,最後,在本項目中,只有獲取個人信息的時候使用了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還是處於一知半解的狀態,嗯,學習的路還很長。

4. 結語篇

當Gitter第一個版本通過審覈的時候,心情是很激動的,就像自己的孩子一樣,看着他一點一點的長大,筆者也很享受這樣一個項目從無到有的過程,在此,對那些幫助過筆者的人一併表示感謝。

當然,目前功能和體驗上可能有些不大完善,也希望大家能提供一些寶貴的意見,Gitter走向完美的路上希望有你!

最後,希望Gitter小程序能對你有所幫助!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章