1
0
mirror of https://github.com/h3poteto/whalebird-desktop synced 2025-02-02 18:36:56 +01:00

Merge pull request #990 from h3poteto/iss-985

refs #985 Cache hashtags
This commit is contained in:
AkiraFukushima 2019-08-07 22:04:50 +09:00 committed by GitHub
commit 486bd8ba08
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 232 additions and 111 deletions

32
src/main/cache/hashtag.ts vendored Normal file
View File

@ -0,0 +1,32 @@
import Datastore from 'nedb'
import { LocalTag } from '~/src/types/localTag'
export default class HashtagCache {
private db: Datastore
constructor(path: string) {
this.db = new Datastore({
filename: path,
autoload: true
})
this.db.ensureIndex({ fieldName: 'tagName', unique: true }, _ => {})
}
listTags(): Promise<Array<LocalTag>> {
return new Promise((resolve, reject) => {
this.db.find<LocalTag>({}, (err, docs) => {
if (err) return reject(err)
resolve(docs)
})
})
}
insertHashtag(tag: string): Promise<LocalTag> {
return new Promise(resolve => {
// Ignore error for unique constraints.
this.db.insert({ tagName: tag }, (_, doc) => {
resolve(doc)
})
})
}
}

View File

@ -40,6 +40,7 @@ import { LocalTag } from '~/src/types/localTag'
import { UnreadNotification as UnreadNotificationConfig } from '~/src/types/unreadNotification'
import { Notify } from '~/src/types/notify'
import { StreamingError } from '~/src/errors/streamingError'
import HashtagCache from './cache/hashtag'
/**
* Context menu
@ -100,6 +101,12 @@ unreadNotification.initialize().catch((err: Error) => log.error(err))
const preferencesDBPath = process.env.NODE_ENV === 'production' ? userData + './db/preferences.json' : 'preferences.json'
/**
* Cache path
*/
const hashtagCachePath = process.env.NODE_ENV === 'production' ? userData + '/cache/hashtag.db' : 'cache/hashtag.db'
const hashtagCache = new HashtagCache(hashtagCachePath)
const soundBasePath =
process.env.NODE_ENV === 'development' ? path.join(__dirname, '../../build/sounds/') : path.join(process.resourcesPath!, 'build/sounds/')
@ -457,6 +464,10 @@ ipcMain.on('start-all-user-streamings', (event: Event, accounts: Array<LocalAcco
if (!event.sender.isDestroyed()) {
event.sender.send(`update-start-all-user-streamings-${id}`, update)
}
// Cache hashtag
update.tags.map(async tag => {
await hashtagCache.insertHashtag(tag.name)
})
},
(notification: RemoteNotification) => {
const preferences = new Preferences(preferencesDBPath)
@ -984,6 +995,19 @@ ipcMain.on('update-unread-notification', (event: Event, config: UnreadNotificati
})
})
// Cache
ipcMain.on('get-cache-hashtags', async (event: Event) => {
const tags = await hashtagCache.listTags()
event.sender.send('response-get-cache-hashtags', tags)
})
ipcMain.on('insert-cache-hashtags', (event: Event, tags: Array<string>) => {
tags.map(async name => {
await hashtagCache.insertHashtag(name)
})
event.sender.send('response-insert-cache-hashtag')
})
// Application control
ipcMain.on('relaunch', () => {
app.relaunch()

View File

@ -1,55 +1,52 @@
<template>
<div class="status">
<textarea
v-model="status"
ref="status"
v-shortkey="openSuggest ? {up: ['arrowup'], down: ['arrowdown'], enter: ['enter'], esc: ['esc']} : {linux: ['ctrl', 'enter'], mac: ['meta', 'enter'], left: ['arrowleft'], right: ['arrowright']}"
@shortkey="handleKey"
@paste="onPaste"
v-on:input="startSuggest"
:placeholder="$t('modals.new_toot.status')"
role="textbox"
contenteditable="true"
aria-multiline="true"
autofocus>
</textarea>
<el-popover
placement="bottom-start"
width="300"
trigger="manual"
v-model="openSuggest">
<ul class="suggest-list">
<li
v-for="(item, index) in filteredSuggestion"
:key="index"
@click="insertItem(item)"
@shortkey="insertItem(item)"
@mouseover="highlightedIndex = index"
:class="{'highlighted': highlightedIndex === index}">
<span v-if="item.image">
<img :src="item.image" class="icon" />
</span>
<span v-if="item.code">
{{ item.code }}
</span>
{{ item.name }}
</li>
</ul>
</el-popover>
<div v-click-outside="hideEmojiPicker">
<el-button type="text" class="emoji-selector" @click="toggleEmojiPicker">
<icon name="regular/smile" scale="1.2"></icon>
</el-button>
<div v-if="openEmojiPicker" class="emoji-picker">
<picker
set="emojione"
:autoFocus="true"
:custom="pickerEmojis"
@select="selectEmoji"
/>
<div class="status">
<textarea
v-model="status"
ref="status"
v-shortkey="
openSuggest
? { up: ['arrowup'], down: ['arrowdown'], enter: ['enter'], esc: ['esc'] }
: { linux: ['ctrl', 'enter'], mac: ['meta', 'enter'], left: ['arrowleft'], right: ['arrowright'] }
"
@shortkey="handleKey"
@paste="onPaste"
v-on:input="startSuggest"
:placeholder="$t('modals.new_toot.status')"
role="textbox"
contenteditable="true"
aria-multiline="true"
autofocus
>
</textarea>
<el-popover placement="bottom-start" width="300" trigger="manual" :value="openSuggest">
<ul class="suggest-list">
<li
v-for="(item, index) in filteredSuggestion"
:key="index"
@click="insertItem(item)"
@shortkey="insertItem(item)"
@mouseover="highlightedIndex = index"
:class="{ highlighted: highlightedIndex === index }"
>
<span v-if="item.image">
<img :src="item.image" class="icon" />
</span>
<span v-if="item.code">
{{ item.code }}
</span>
{{ item.name }}
</li>
</ul>
</el-popover>
<div v-click-outside="hideEmojiPicker">
<el-button type="text" class="emoji-selector" @click="toggleEmojiPicker">
<icon name="regular/smile" scale="1.2"></icon>
</el-button>
<div v-if="openEmojiPicker" class="emoji-picker">
<picker set="emojione" :autoFocus="true" :custom="pickerEmojis" @select="selectEmoji" />
</div>
</div>
</div>
</div>
</template>
<script>
@ -80,13 +77,9 @@ export default {
default: false
}
},
data () {
data() {
return {
openSuggest: false,
highlightedIndex: 0,
startIndex: null,
matchWord: null,
filteredSuggestion: [],
openEmojiPicker: false
}
},
@ -96,21 +89,23 @@ export default {
}),
...mapState('TimelineSpace/Modals/NewToot/Status', {
filteredAccounts: state => state.filteredAccounts,
filteredHashtags: state => state.filteredHashtags
filteredHashtags: state => state.filteredHashtags,
openSuggest: state => state.openSuggest,
startIndex: state => state.startIndex,
matchWord: state => state.matchWord,
filteredSuggestion: state => state.filteredSuggestion
}),
...mapGetters('TimelineSpace/Modals/NewToot/Status', [
'pickerEmojis'
]),
...mapGetters('TimelineSpace/Modals/NewToot/Status', ['pickerEmojis']),
status: {
get: function () {
get: function() {
return this.value
},
set: function (value) {
set: function(value) {
this.$emit('input', value)
}
}
},
mounted () {
mounted() {
// When change account, the new toot modal is recreated.
// So can not catch open event in watch.
this.$refs.status.focus()
@ -119,9 +114,9 @@ export default {
}
},
watch: {
opened: function (newState, oldState) {
opened: function(newState, oldState) {
if (!oldState && newState) {
this.$nextTick(function () {
this.$nextTick(function() {
this.$refs.status.focus()
if (this.fixCursorPos) {
this.$refs.status.setSelectionRange(0, 0)
@ -134,7 +129,7 @@ export default {
}
},
methods: {
async startSuggest (e) {
async startSuggest(e) {
const currentValue = e.target.value
// Start suggest after user stop writing
setTimeout(async () => {
@ -143,7 +138,7 @@ export default {
}
}, 700)
},
async suggest (e) {
async suggest(e) {
// e.target.sectionStart: Cursor position
// e.target.value: current value of the textarea
const [start, word] = suggestText(e.target.value, e.target.selectionStart)
@ -165,36 +160,32 @@ export default {
return false
}
},
async suggestAccount (start, word) {
async suggestAccount(start, word) {
try {
await this.$store.dispatch('TimelineSpace/Modals/NewToot/Status/searchAccount', word)
this.openSuggest = true
this.startIndex = start
this.matchWord = word
this.filteredSuggestion = this.filteredAccounts
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeOpenSuggest', true)
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeStartIndex', start)
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeMatchWord', word)
this.$store.commit('TimelineSpace/Modasl/NewToot/Status/filteredSuggestionFromAccounts')
return true
} catch (err) {
console.log(err)
return false
}
},
async suggestHashtag (start, word) {
async suggestHashtag(start, word) {
try {
await this.$store.dispatch('TimelineSpace/Modals/NewToot/Status/searchHashtag', word)
this.openSuggest = true
this.startIndex = start
this.matchWord = word
this.filteredSuggestion = this.filteredHashtags
await this.$store.dispatch('TimelineSpace/Modals/NewToot/Status/suggestHashtag', { word: word, start: start })
return true
} catch (err) {
console.log(err)
return false
}
},
suggestEmoji (start, word) {
suggestEmoji(start, word) {
// Find native emojis
const filteredEmojiName = emojilib.ordered.filter(emoji => `:${emoji}`.includes(word))
const filteredNativeEmoji = filteredEmojiName.map((name) => {
const filteredNativeEmoji = filteredEmojiName.map(name => {
return {
name: `:${name}:`,
code: emojilib.lib[name].char
@ -204,29 +195,32 @@ export default {
const filteredCustomEmoji = this.customEmojis.filter(emoji => emoji.name.includes(word))
const filtered = filteredNativeEmoji.concat(filteredCustomEmoji)
if (filtered.length > 0) {
this.openSuggest = true
this.startIndex = start
this.matchWord = word
this.filteredSuggestion = filtered.filter((e, i, array) => {
return (array.findIndex(ar => e.name === ar.name) === i)
})
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeOpenSuggest', true)
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeStartIndex', start)
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeMatchWord', word)
this.$store.commit(
'TimelineSpace/Modals/NewToot/Status/changeFilteredSuggestion',
filtered.filter((e, i, array) => {
return array.findIndex(ar => e.name === ar.name) === i
})
)
} else {
this.closeSuggest()
}
return true
},
closeSuggest () {
closeSuggest() {
if (this.openSuggest) {
this.openSuggest = false
this.startIndex = null
this.matchWord = null
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeOpenSuggest', false)
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeStartIndex', null)
this.$store.commit('TimelineSpace/Modals/NewToot/Status/changeMatchWord', null)
this.highlightedIndex = 0
this.filteredSuggestion = []
this.$store.commit('TimelineSpace/Modals/NewToot/Status/clearFilteredSuggestion')
this.$store.commit('TimelineSpace/Modals/NewToot/Status/clearFilteredAccounts')
this.$store.commit('TimelineSpace/Modals/NewToot/Status/clearFilteredHashtags')
}
},
suggestHighlight (index) {
suggestHighlight(index) {
if (index < 0) {
this.highlightedIndex = 0
} else if (index >= this.filteredSuggestion.length) {
@ -235,7 +229,7 @@ export default {
this.highlightedIndex = index
}
},
insertItem (item) {
insertItem(item) {
if (item.code) {
const str = `${this.status.slice(0, this.startIndex - 1)}${item.code} ${this.status.slice(this.startIndex + this.matchWord.length)}`
this.status = str
@ -245,14 +239,14 @@ export default {
}
this.closeSuggest()
},
selectCurrentItem () {
selectCurrentItem() {
const item = this.filteredSuggestion[this.highlightedIndex]
this.insertItem(item)
},
onPaste (e) {
onPaste(e) {
this.$emit('paste', e)
},
handleKey (event) {
handleKey(event) {
const current = event.target.selectionStart
switch (event.srcKey) {
case 'up':
@ -281,13 +275,13 @@ export default {
return true
}
},
toggleEmojiPicker () {
toggleEmojiPicker() {
this.openEmojiPicker = !this.openEmojiPicker
},
hideEmojiPicker () {
hideEmojiPicker() {
this.openEmojiPicker = false
},
selectEmoji (emoji) {
selectEmoji(emoji) {
const current = this.$refs.status.selectionStart
if (emoji.native) {
this.status = `${this.status.slice(0, current)}${emoji.native} ${this.status.slice(current)}`

View File

@ -1,31 +1,48 @@
import { ipcRenderer } from 'electron'
import Mastodon, { Account, Tag, Response, Results } from 'megalodon'
import { Module, MutationTree, ActionTree, GetterTree } from 'vuex'
import { RootState } from '@/store/index'
import { LocalTag } from '~/src/types/localTag'
interface Suggest {
type Suggest = {
name: string
image: string | null
}
interface SuggestAccount extends Suggest {}
type SuggestAccount = Suggest
interface SuggestHashtag extends Suggest {}
type SuggestHashtag = Suggest
export type StatusState = {
filteredAccounts: Array<SuggestAccount>
filteredHashtags: Array<SuggestHashtag>
openSuggest: boolean
startIndex: number | null
matchWord: string | null
filteredSuggestion: Array<Suggest>
}
const state = (): StatusState => ({
filteredAccounts: [],
filteredHashtags: []
filteredHashtags: [],
openSuggest: false,
startIndex: null,
matchWord: null,
filteredSuggestion: []
})
export const MUTATION_TYPES = {
UPDATE_FILTERED_ACCOUNTS: 'updateFilteredAccounts',
CLEAR_FILTERED_ACCOUNTS: 'clearFilteredAccounts',
UPDATE_FILTERED_HASHTAGS: 'updateFilteredHashtags',
CLEAR_FILTERED_HASHTAGS: 'clearFilteredHashtags'
APPEND_FILTERED_HASHTAGS: 'appendFilteredHashtags',
CLEAR_FILTERED_HASHTAGS: 'clearFilteredHashtags',
CHANGE_OPEN_SUGGEST: 'changeOpenSuggest',
CHANGE_START_INDEX: 'changeStartIndex',
CHANGE_MATCH_WORD: 'changeMatchWord',
FILTERED_SUGGESTION_FROM_HASHTAGS: 'filteredSuggestionFromHashtags',
FILTERED_SUGGESTION_FROM_ACCOUNTS: 'filteredSuggestionFromAccounts',
CLEAR_FILTERED_SUGGESTION: 'clearFilteredSuggestion',
CHANGE_FILTERED_SUGGESTION: 'changeFilteredSuggestion'
}
const mutations: MutationTree<StatusState> = {
@ -38,17 +55,44 @@ const mutations: MutationTree<StatusState> = {
[MUTATION_TYPES.CLEAR_FILTERED_ACCOUNTS]: state => {
state.filteredAccounts = []
},
[MUTATION_TYPES.UPDATE_FILTERED_HASHTAGS]: (state, tags: Array<Tag>) => {
state.filteredHashtags = tags.map(t => ({
[MUTATION_TYPES.APPEND_FILTERED_HASHTAGS]: (state, tags: Array<Tag>) => {
const appended = tags.map(t => ({
name: `#${t}`,
image: null
}))
state.filteredHashtags = appended.filter((elem, index, self) => self.indexOf(elem) === index)
},
[MUTATION_TYPES.CLEAR_FILTERED_HASHTAGS]: state => {
state.filteredHashtags = []
},
[MUTATION_TYPES.CHANGE_OPEN_SUGGEST]: (state, value: boolean) => {
state.openSuggest = value
},
[MUTATION_TYPES.CHANGE_START_INDEX]: (state, index: number | null) => {
state.startIndex = index
},
[MUTATION_TYPES.CHANGE_MATCH_WORD]: (state, word: string | null) => {
state.matchWord = word
},
[MUTATION_TYPES.FILTERED_SUGGESTION_FROM_HASHTAGS]: state => {
state.filteredSuggestion = state.filteredHashtags
},
[MUTATION_TYPES.FILTERED_SUGGESTION_FROM_ACCOUNTS]: state => {
state.filteredSuggestion = state.filteredAccounts
},
[MUTATION_TYPES.CLEAR_FILTERED_SUGGESTION]: state => {
state.filteredSuggestion = []
},
[MUTATION_TYPES.CHANGE_FILTERED_SUGGESTION]: (state, suggestion: Array<Suggest>) => {
state.filteredSuggestion = suggestion
}
}
type WordStart = {
word: string
start: number
}
const actions: ActionTree<StatusState, RootState> = {
searchAccount: async ({ commit, rootState }, word: string) => {
const client = new Mastodon(rootState.TimelineSpace.account.accessToken!, rootState.TimelineSpace.account.baseURL + '/api/v1')
@ -57,12 +101,39 @@ const actions: ActionTree<StatusState, RootState> = {
if (res.data.accounts.length === 0) throw new Error('Empty')
return res.data.accounts
},
searchHashtag: async ({ commit, rootState }, word: string) => {
const client = new Mastodon(rootState.TimelineSpace.account.accessToken!, rootState.TimelineSpace.account.baseURL + '/api/v1')
const res: Response<Results> = await client.get<Results>('/search', { q: word })
commit(MUTATION_TYPES.UPDATE_FILTERED_HASHTAGS, res.data.hashtags)
if (res.data.hashtags.length === 0) throw new Error('Empty')
return res.data.hashtags
suggestHashtag: async ({ commit, rootState }, wordStart: WordStart) => {
commit(MUTATION_TYPES.CLEAR_FILTERED_HASHTAGS)
commit(MUTATION_TYPES.FILTERED_SUGGESTION_FROM_HASHTAGS)
const { word, start } = wordStart
const searchCache = () => {
return new Promise(resolve => {
const target = word.replace('#', '')
ipcRenderer.once('response-get-cache-hashtags', (_, tags: Array<LocalTag>) => {
const mached = tags.filter(tag => tag.tagName.includes(target)).map(tag => tag.tagName)
commit(MUTATION_TYPES.APPEND_FILTERED_HASHTAGS, mached)
if (mached.length === 0) throw new Error('Empty')
commit(MUTATION_TYPES.CHANGE_OPEN_SUGGEST, true)
commit(MUTATION_TYPES.CHANGE_START_INDEX, start)
commit(MUTATION_TYPES.CHANGE_MATCH_WORD, word)
commit(MUTATION_TYPES.FILTERED_SUGGESTION_FROM_HASHTAGS)
resolve(mached)
})
ipcRenderer.send('get-cache-hashtags')
})
}
const searchAPI = async () => {
const client = new Mastodon(rootState.TimelineSpace.account.accessToken!, rootState.TimelineSpace.account.baseURL + '/api/v1')
const res: Response<Results> = await client.get<Results>('/search', { q: word })
commit(MUTATION_TYPES.APPEND_FILTERED_HASHTAGS, res.data.hashtags)
ipcRenderer.send('insert-cache-hashtags', res.data.hashtags)
if (res.data.hashtags.length === 0) throw new Error('Empty')
commit(MUTATION_TYPES.CHANGE_OPEN_SUGGEST, true)
commit(MUTATION_TYPES.CHANGE_START_INDEX, start)
commit(MUTATION_TYPES.CHANGE_MATCH_WORD, word)
commit(MUTATION_TYPES.FILTERED_SUGGESTION_FROM_HASHTAGS)
return res.data.hashtags
}
await Promise.all([searchCache(), searchAPI()])
}
}