Skip to content

Commit

Permalink
feat(recently colsed tab): add recently closed tab search
Browse files Browse the repository at this point in the history
  • Loading branch information
crown committed Jun 4, 2018
1 parent e3f72ac commit 89a3d1a
Show file tree
Hide file tree
Showing 13 changed files with 143 additions and 160 deletions.
1 change: 0 additions & 1 deletion package.json
Expand Up @@ -60,7 +60,6 @@
"postcss-url": "^7.2.1",
"pre-commit": "^1.2.2",
"rimraf": "^2.6.0",
"sass-loader": "^6.0.6",
"semver": "^5.3.0",
"shelljs": "^0.7.6",
"stylus": "^0.54.5",
Expand Down
67 changes: 50 additions & 17 deletions src/api/chrome-api.js
@@ -1,20 +1,20 @@
import _ from "lodash-es"
import util from '../util/index'

const chrome = window.chrome

function queryBM(arr) {
// 多个查询只需要在第一编查询出来的结果上进行去重即可, 不必再去查询第二遍
return new Promise(resolve => {
if (!arr.length) resolve([])
const len = arr.length
if (!len) resolve([])
else {
chrome.bookmarks.search(arr[0], rep => {
const tmp = []
for (let index = 0; index < rep.length; index += 1) {
const item = rep[index]
// 当不是多个单词查询时, isRight 默认为true, 否则才会进行的后面的多个单词匹配
const isRight = arr.length === 1 || arr.every(item1 => new RegExp(`${item1}`, 'gi').test(`${item.url} ${item.title}`))
// 去重 + 去除无效数据
if (!item.dateGroupModified && isRight) {
// 去除无效数据并去重
if (!item.dateGroupModified && (len === 1 || util.isEachEligible(arr, `${item.url} ${item.title}`))) {
tmp.push({
type: 'bookmark',
title: item.title ? item.title : item.url, // title 不能为空
Expand All @@ -31,8 +31,9 @@ function queryBM(arr) {
function queryTab(arr) {
// 同上面的 queryBM 方法
return new Promise(resolve => {
const len = arr.length
// tab 检索时默认出现所有的tab页
if (arr.length === 0) arr.push('')
if (len === 0) arr.push('')
chrome.tabs.query({
windowId: chrome.windows.WINDOW_ID_CURRENT,
windowType: 'normal'
Expand All @@ -45,8 +46,7 @@ function queryTab(arr) {
* length === 0: 默认出现所有所有 tab 页
* length === 1 : 不需要进行后面的多个单词匹配
*/
const isRight = arr.length < 2 || arr.every(item1 => new RegExp(`${item1}`, 'gi').test(`${item.url} ${item.title}`))
if (isRight) {
if (len < 2 || util.isEachEligible(arr, `${item.url} ${item.title}`)) {
tmp.push({
type: 'tab',
title: item.title,
Expand Down Expand Up @@ -87,15 +87,8 @@ function getConfig() {
* @param {JSON} config
*/
function setConfig(config) {
return new Promise(resolve => {
chrome.storage.sync.set({
crown: JSON.stringify(config)
}, () =>
resolve({
error: false,
msg: `配置已更新为 ${JSON.stringify(config)}`
})
)
chrome.storage.sync.set({
crown: JSON.stringify(config)
})
}

Expand Down Expand Up @@ -153,6 +146,44 @@ function listenMsg(callback) {
chrome.runtime.onMessage.addListener(callback)
}

function queryRecentLyClosed(arr) {
return new Promise(resolve => {
const len = arr.length
if (len === 0) arr.push('')
chrome.sessions.getRecentlyClosed({
maxResults: 25
}, (rep) => {
const tmp = []
for (let index = 0; index < rep.length; index += 1) {
const item = rep[index].tab
// 只取 tab 类型, 不要 win 类型
if (item) {
/**
* length === 0: 默认出现所有所有 最近关闭的标签页
* length === 1 : 不需要进行后面的多个单词匹配
*/
if (len < 2 || util.isEachEligible(arr, `${item.url} ${item.title}`)) {
tmp.push({
type: 'closedTab',
title: item.title,
subtitle: item.url,

id: item.sessionId,
})
}
}
}
resolve(tmp)
})

})

}

function restoreRecentTab(sessionId) {
chrome.sessions.restore(sessionId)
}

export default {
findActiveTab,
getConfig,
Expand All @@ -165,4 +196,6 @@ export default {
setConfig,
updateTabStatus,
openNewTab,
queryRecentLyClosed,
restoreRecentTab
}
1 change: 1 addition & 0 deletions src/assets/close.svg
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
33 changes: 19 additions & 14 deletions src/background/default-setting.js
Expand Up @@ -2,24 +2,29 @@

export default {
// 不同项目的搜索设置
itemSetting: [
itemSetting: {
/**
* @param
* isDefault: 在不指定 keyword 的情况下是否进入搜索队列
* isSearch: 是否搜索该栏目下的内容
* keyword: 搜索的关键字
* keyword: 搜索触发的关键字
*/
{
type: 'bookmark',
isSearch: true,
// 书签
bookmark: {
isDefault: true,
keyword: 'bm'
}, {
type: 'tab',
isSearch: true,
keyword: 'bm',
desc: 'Bookmarks'
},
// 当前标签页
tab: {
isDefault: true,
keyword: 't'
}
]
keyword: 't',
desc: 'Tabs'
},
// 最近关闭的标签页
closedTab: {
isDefault: false,
keyword: 'rc',
desc: 'Recently Closed Tabs'
},
}

}
53 changes: 27 additions & 26 deletions src/background/filter-search-data.js
@@ -1,13 +1,14 @@
import async from "async-es"

import chromeAPI from '../api/chrome-api'
import util from '../util/index'

let setting
let setting = {}

chromeAPI
.getConfig()
.then(oSetting => {
setting = oSetting
.then(rep => {
setting = rep
})
.catch(() => {
throw new Error('get setting error in filter-data.js')
Expand All @@ -18,17 +19,16 @@ chrome.storage.onChanged.addListener(changes => {
if (changes.crown) setting = JSON.parse(changes.crown.newValue)
})

// 从配置中检索相关关键字
// 匹配相关关键字列表
function searchKeyword(arr) {
return new Promise(resolve => {
const temp = []
setting.itemSetting.forEach(item => {
if (arr.every(item1 =>
new RegExp(`${item1}`, 'gi').test(`${item.type} ${item.keyword}`))) {
Object.values(setting.itemSetting).forEach(item => {
if (util.isEachEligible(arr, `${item.desc} ${item.keyword}`)) {
temp.push({
type: 'keyword',
title: `Search ${item.type}`,
subtitle: `Search ${item.type} for "..."`,
title: `Search ${item.desc}`,
subtitle: `Search ${item.desc} for "..."`,
keyword: item.keyword
})
}
Expand All @@ -40,23 +40,21 @@ function searchKeyword(arr) {
// 获取需要检索的队列数组
function filterKeyword(strArr) {
let tmp = []
for (let idx = 0; idx < setting.itemSetting.length; idx += 1) {
const item = setting.itemSetting[idx]
if (item.isSearch) {
if (item.keyword === strArr[0]) {
// 搜索单个子列
tmp = [{
type: item.type,
strArr: strArr.slice(1)
}]
break
} else if (item.isDefault)
tmp.push({
type: item.type,
strArr
})
}
}
Object.values(setting.itemSetting).some(item => {
if (item.keyword === strArr[0]) {
// 搜索单个子列
tmp = [{
type: item.type,
strArr: strArr.slice(1)
}]
return true
} else if (item.isDefault)
tmp.push({
type: item.type,
strArr
})
return false
})
// 不管是默认搜索还是单项的搜索, 都要出现 keyowrd 类别的提示(如果有对应的话)
return [{
type: 'keyword',
Expand All @@ -76,6 +74,9 @@ function searchFromType(item, callback) {
case 'tab':
chromeAPI.queryTab(item.strArr).then(tmp => callback(null, tmp))
break
case 'closedTab':
chromeAPI.queryRecentLyClosed(item.strArr).then(tmp => callback(null, tmp))
break

default:
break
Expand Down
3 changes: 3 additions & 0 deletions src/background/handle-selected-item.js
Expand Up @@ -8,6 +8,9 @@ function handleSelectedItem(item) {
case 'tab':
chromeAPI.updateTabStatus(item.id)
break
case 'closedTab':
chromeAPI.restoreRecentTab(item.id)
break

default:
break
Expand Down
21 changes: 9 additions & 12 deletions src/background/index.js
Expand Up @@ -9,25 +9,22 @@ import handleSelectedItem from './handle-selected-item'

import util from '../util'

chromeAPI.getConfig()

// init extension setting if
chromeAPI
.getConfig()
.then(data => util.Echo('init getConfig', data))
.catch(error => {
util.Echo('set config', error)
chromeAPI.setConfig(defaultSetting).then(status => {
console.log(status)
})
.catch(() => {
chromeAPI.setConfig(defaultSetting)
})

chromeAPI.listenCommand(async command => {
// find current tab, then send a message to show(or insert) extension dom
chromeAPI.listenCommand(command => {
// custom command
if (command === 'open-in-current-page') {
const oTab = await chromeAPI.findActiveTab()
chromeAPI.sendMsgInTab(oTab.id, {
type: 'openExtension'
// find current tab, then send a message to show(or insert) extension dom
chromeAPI.findActiveTab().then(oTab => {
chromeAPI.sendMsgInTab(oTab.id, {
type: 'openExtension'
})
})
}
})
Expand Down
14 changes: 2 additions & 12 deletions src/background/omnibox.js
Expand Up @@ -2,21 +2,11 @@ import _ from 'lodash-es'

import filterSearchData from './filter-search-data'
import handleSelectedItem from './handle-selected-item'

import util from '../util/index'

// 缓存搜索结果
let SearchResults = []

/**
* https://stackoverflow.com/questions/35802159/chrome-omnibox-special-characters-throw-error
* handle a error about (omnibox description xmlParseEntityRef: no name)
*/
function encodeXml(s) {
const dom = document.createElement('div')
dom.textContent = s
return dom.innerHTML
}

function setSuggestion(decs) {
/**
* The supported tags are
Expand Down Expand Up @@ -44,7 +34,7 @@ function hanldeStr(str, suggest) {
if (item.type !== 'keyword') {
results.push({
content: `${item.title} @index=${results.length+1}`,
description: `<match>${item.type}</match>: ${`${encodeXml(item.title)} - <url>${encodeXml(item.subtitle)}</url>`.replace(regex, '<match>$&</match>')}`
description: `<match>${item.type}</match>: ${`${util.encodeXml(item.title)} - <url>${util.encodeXml(item.subtitle)}</url>`.replace(regex, '<match>$&</match>')}`
})

SearchResults.push(item)
Expand Down
4 changes: 1 addition & 3 deletions src/components/FormSetting/index.vue
Expand Up @@ -46,9 +46,7 @@ export default {
watch: {
setting: {
handler(val) {
chromeAPI.setConfig(val).then(status => {
console.log(status)
})
chromeAPI.setConfig(val)
},
deep: true
}
Expand Down
3 changes: 3 additions & 0 deletions src/components/SearchList/search-list.styl
Expand Up @@ -38,6 +38,9 @@
&.keyword
background: url('../../assets/keyword.svg') center / 34px no-repeat

&.recentlyClosed
background: url('../../assets/close.svg') center / 34px no-repeat

.key-enter
display: none
flex-shrink: 0
Expand Down
23 changes: 22 additions & 1 deletion src/util/index.js
Expand Up @@ -10,6 +10,27 @@ function Echo(...args) {
}
}

/**
* https://stackoverflow.com/questions/35802159/chrome-omnibox-special-characters-throw-error
* handle a error about (omnibox description xmlParseEntityRef: no name)
*/
function encodeXml(str) {
const dom = document.createElement('div')
dom.textContent = str
return dom.innerHTML
}

/**
* Whether each is eligible
* @param {Array} arr
* @param {String} testedStr
*/
function isEachEligible(arr, testedStr) {
return arr.every(item => new RegExp(`${item}`, 'gi').test(testedStr))
}

export default {
Echo
Echo,
encodeXml,
isEachEligible
}
2 changes: 1 addition & 1 deletion static/manifest.json
Expand Up @@ -46,7 +46,7 @@
"omnibox": {
"keyword": "c"
},
"permissions": ["bookmarks", "chrome://favicon/", "tabs", "storage", "<all_urls>"],
"permissions": ["bookmarks", "sessions", "tabs", "storage", "<all_urls>"],
"version": "2.0.0",
"web_accessible_resources": [
"img/*"
Expand Down

0 comments on commit 89a3d1a

Please sign in to comment.