Skip to content

Commit

Permalink
refactor: type import, format
Browse files Browse the repository at this point in the history
  • Loading branch information
pd4d10 committed Jan 12, 2019
1 parent 0213b7d commit 1a864b1
Show file tree
Hide file tree
Showing 14 changed files with 86 additions and 60 deletions.
2 changes: 1 addition & 1 deletion .prettierrc
@@ -1,5 +1,5 @@
{
"printWidth": 120,
"printWidth": 100,
"singleQuote": true,
"semi": false,
"trailingComma": "all"
Expand Down
30 changes: 18 additions & 12 deletions src/background/adapter.ts
@@ -1,16 +1,22 @@
import { createService } from './services'
import TsService from './services/typescript'
import * as types from '../types'
import { MultiFileService } from './services/base'
import { TsService } from './services/typescript'
import { MultipleFileService } from './services/base'
import {
ContentMessage,
BackgroundMessage,
MessageType,
BackgroundMessageOfOccurrence,
BackgroundMessageOfQuickInfo,
} from '../types'

const TIMEOUT = 1000 * 60 * 5 // 5min

export default abstract class Adapter {
services: { [file: string]: MultiFileService } = {}
services: { [file: string]: MultipleFileService } = {}
ts = new TsService()

abstract addListener(
cb: (message: types.ContentMessage, sendResponse: (message: types.BackgroundMessage) => void) => void,
cb: (message: ContentMessage, sendResponse: (message: BackgroundMessage) => void) => void,
): void
abstract addTabUpdateListener(): void

Expand All @@ -23,7 +29,7 @@ export default abstract class Adapter {
return path.replace(/.*\.(.*?)$/, '$1')
}

handleMessage = (message: types.ContentMessage, sendResponse: (message: types.BackgroundMessage) => void) => {
handleMessage = (message: ContentMessage, sendResponse: (message: BackgroundMessage) => void) => {
// const { file, codeUrl, tabSize } = message
let service
const ext = this.getExtension(message.file)
Expand All @@ -49,10 +55,10 @@ export default abstract class Adapter {
// return
// }

let response: types.BackgroundMessage
let response: BackgroundMessage

switch (message.type) {
case types.Message.service: {
case MessageType.service: {
response = {} // Trigger for Safari

// chrome.browserAction.setIcon({
Expand All @@ -64,7 +70,7 @@ export default abstract class Adapter {

break
}
case types.Message.occurrence: {
case MessageType.occurrence: {
const info = {
file: message.file,
line: message.position.y,
Expand All @@ -73,18 +79,18 @@ export default abstract class Adapter {
response = {
occurrences: service.getOccurrences(info),
info: message.meta ? service.getDefinition(info) : undefined,
} as types.BackgroundMessageOfOccurrence
} as BackgroundMessageOfOccurrence
break
}
case types.Message.quickInfo: {
case MessageType.quickInfo: {
const info = {
file: message.file,
line: message.position.y,
character: message.position.x,
}
response = {
data: service.getQuickInfo(info),
} as types.BackgroundMessageOfQuickInfo
} as BackgroundMessageOfQuickInfo
break
}
default:
Expand Down
16 changes: 8 additions & 8 deletions src/background/services/base.ts
@@ -1,9 +1,9 @@
import * as $t from '../../types'
import { ContentMessage, PositionInfo, Occurrence, Definition, QuickInfo } from '../../types'

abstract class BaseService {
abstract getOccurrences(info: $t.PositionInfo): $t.Occurrence[] | void
abstract getDefinition(info: $t.PositionInfo): $t.Definition | void
abstract getQuickInfo(info: $t.PositionInfo): $t.QuickInfo | void
abstract getOccurrences(info: PositionInfo): Occurrence[] | void
abstract getDefinition(info: PositionInfo): Definition | void
abstract getQuickInfo(info: PositionInfo): QuickInfo | void

async fetchWithCredentials(url: string, isJson = false) {
const res = await fetch(url, { credentials: 'same-origin' })
Expand All @@ -13,25 +13,25 @@ abstract class BaseService {
return await res[isJson ? 'json' : 'text']()
}

async fetchCode(message: $t.ContentMessage) {
async fetchCode(message: ContentMessage) {
const code = await this.fetchWithCredentials(message.codeUrl)
return code.replace(/\t/g, ' '.repeat(message.tabSize))
}
}

export abstract class MultiFileService extends BaseService {}
export abstract class MultipleFileService extends BaseService {}

export abstract class SingleFileService extends BaseService {
file: string
abstract createService(code: string): void

constructor(message: $t.ContentMessage) {
constructor(message: ContentMessage) {
super()
this.file = message.file
this.fetchCodeAndCreateService(message)
}

async fetchCodeAndCreateService(message: $t.ContentMessage) {
async fetchCodeAndCreateService(message: ContentMessage) {
const code = await this.fetchCode(message)
this.createService(code)
}
Expand Down
12 changes: 7 additions & 5 deletions src/background/services/css.ts
@@ -1,6 +1,6 @@
import * as cssService from 'vscode-css-languageservice'
import * as ls from 'vscode-languageserver-types'
import { MultiFileService, SingleFileService } from './base'
import { SingleFileService } from './base'
import { PositionInfo } from '../../types'

abstract class BaseService extends SingleFileService {
Expand All @@ -17,10 +17,12 @@ abstract class BaseService extends SingleFileService {
}

getOccurrences(info: PositionInfo) {
return this.service.findDocumentHighlights(this.document, info, this.stylesheet).map(highlight => ({
range: highlight.range.start,
width: highlight.range.end.character - highlight.range.start.character,
}))
return this.service
.findDocumentHighlights(this.document, info, this.stylesheet)
.map(highlight => ({
range: highlight.range.start,
width: highlight.range.end.character - highlight.range.start.character,
}))
}

getDefinition(info: PositionInfo) {
Expand Down
4 changes: 2 additions & 2 deletions src/background/services/index.ts
@@ -1,6 +1,6 @@
import { CSSService, LESSService, SCSSService } from './css'
import SimpleService from './simple'
import * as types from '../../types'
import { ContentMessage } from '../../types'
// import VueService from './vue'

function getServiceByFileName(ext: string) {
Expand All @@ -18,7 +18,7 @@ function getServiceByFileName(ext: string) {
}
}

export function createService(ext: string, message: types.ContentMessage) {
export function createService(ext: string, message: ContentMessage) {
const Service = getServiceByFileName(ext)
return new Service(message)
}
7 changes: 6 additions & 1 deletion src/background/services/simple.ts
Expand Up @@ -5,7 +5,12 @@ import { PositionInfo } from '../../types'
const tokenRegex = /[A-Za-z0-9_]/

// Find all positions of substring
function findAllPositions(str: string, substr: string, res: number[] = [], offset: number = 0): number[] {
function findAllPositions(
str: string,
substr: string,
res: number[] = [],
offset: number = 0,
): number[] {
const idx = str.slice(offset).indexOf(substr)
if (idx === -1) return res

Expand Down
21 changes: 12 additions & 9 deletions src/background/services/typescript.ts
@@ -1,9 +1,9 @@
import * as ts from 'typescript'
import { MultiFileService } from './base'
import ts from 'typescript'
import { MultipleFileService } from './base'
import * as path from 'path'
import stdLibs from './node-libs.json'
import { without, uniq } from 'lodash-es'
import * as types from '../../types'
import { ContentMessage, PositionInfo } from '../../types'

const defaultLibName = '//lib.d.ts'

Expand All @@ -21,7 +21,7 @@ interface Files {

// FIXME: Very slow when click type `string`
// TODO: Go to definition for third party libs
export default class TSService extends MultiFileService {
export class TsService extends MultipleFileService {
private service?: ts.LanguageService
private getSourceFile(file: string) {
// This is necesarry because createService is asynchronous
Expand Down Expand Up @@ -65,7 +65,10 @@ export default class TSService extends MultiFileService {
const prefix = 'https://unpkg.com'
try {
// Find typings file path
const { types, typings } = await this.fetchWithCredentials(path.join(prefix, name, 'package.json'), true)
const { types, typings } = await this.fetchWithCredentials(
path.join(prefix, name, 'package.json'),
true,
)
if (types || typings) {
return await this.fetchWithCredentials(path.join(prefix, name, types || typings))
}
Expand Down Expand Up @@ -98,7 +101,7 @@ export default class TSService extends MultiFileService {
}

// Notice that this method is asynchronous
async createService(message: types.ContentMessage) {
async createService(message: ContentMessage) {
if (this.files[message.file]) return

const defaultLib = await import('../../ts-lib')
Expand Down Expand Up @@ -162,7 +165,7 @@ export default class TSService extends MultiFileService {
// return sourceFile.getPositionOfLineAndCharacter(line, character)
// }

getOccurrences(info: types.PositionInfo) {
getOccurrences(info: PositionInfo) {
const instance = this.getSourceFile(info.file)
if (instance) {
// After upgrading to typescript@2.5
Expand Down Expand Up @@ -191,7 +194,7 @@ export default class TSService extends MultiFileService {
}
}

getDefinition(info: types.PositionInfo) {
getDefinition(info: PositionInfo) {
const instance = this.getSourceFile(info.file)
if (this.service && instance) {
let position: number
Expand All @@ -210,7 +213,7 @@ export default class TSService extends MultiFileService {
}
}

getQuickInfo(info: types.PositionInfo) {
getQuickInfo(info: PositionInfo) {
const instance = this.getSourceFile(info.file)
if (this.service && instance) {
let position: number
Expand Down
3 changes: 2 additions & 1 deletion src/chrome/background.ts
Expand Up @@ -15,7 +15,8 @@ class ChromeAdapter extends Adapter {
addTabUpdateListener() {
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status !== 'complete') return
const code = 'var injected = window.octohintInjected; window.octohintInjected = true; injected;'
const code =
'var injected = window.octohintInjected; window.octohintInjected = true; injected;'
chrome.tabs.executeScript(tabId, { code }, res => {
if (chrome.runtime.lastError || res[0]) return
chrome.tabs.executeScript(tabId, { file: 'dist/content-script.js' })
Expand Down
3 changes: 2 additions & 1 deletion src/chrome/options.tsx
Expand Up @@ -64,7 +64,8 @@ class Options extends Component<{}, { origins: string[]; temp: string }> {
<div style={{ lineHeight: '1.8' }}>
<form onSubmit={this.handleAdd}>
<p>
Add permissions here if your GitHub/Gitlab/Bitbucket is hosted on a different site. If it doesn't work, see{' '}
Add permissions here if your GitHub/Gitlab/Bitbucket is hosted on a different site. If
it doesn't work, see{' '}
<a href="https://developer.chrome.com/extensions/match_patterns">Match Patterns</a>
</p>
<table>
Expand Down
4 changes: 2 additions & 2 deletions src/content-script/adapter.ts
@@ -1,5 +1,5 @@
import * as types from '../types'
import Renderer from './renderer'
import { SendMessageToBackground } from '../types'

const $ = (selector: string) => document.querySelector(selector)
const $$ = (selector: string) => document.querySelectorAll(selector)
Expand Down Expand Up @@ -115,7 +115,7 @@ const GitLabRenderer: RendererParams = {
export default abstract class Adapter {
prevContainer?: Element | null

abstract getSendMessage(): types.SendMessageToBackground
abstract getSendMessage(): SendMessageToBackground
sendMessage = this.getSendMessage()

constructor() {
Expand Down
15 changes: 10 additions & 5 deletions src/content-script/app.tsx
@@ -1,7 +1,7 @@
import { h, Component } from 'preact'
import Portal from 'preact-portal'
import { debounce } from 'lodash-es'
import { Definition, Occurrence, QuickInfo, Message } from '../types'
import { Definition, Occurrence, QuickInfo, MessageType } from '../types'

const colors = {
lineBg: '#fffbdd',
Expand Down Expand Up @@ -72,7 +72,7 @@ export default class App extends Component<any, AppState> {

const response = await this.props.sendMessage({
file: this.props.fileName,
type: Message.occurrence,
type: MessageType.occurrence,
position,
meta: isMacOS ? e.metaKey : e.ctrlKey,
codeUrl: this.props.codeUrl,
Expand All @@ -84,7 +84,10 @@ export default class App extends Component<any, AppState> {
if (response.info) {
window.scrollTo(
0,
this.props.offsetTop + this.props.padding.top + response.info.line * this.props.line.height - 80,
this.props.offsetTop +
this.props.padding.top +
response.info.line * this.props.line.height -
80,
) // TODO: Magic number
}

Expand All @@ -109,7 +112,7 @@ export default class App extends Component<any, AppState> {
const { data } = await this.props.sendMessage({
file: this.props.fileName,
codeUrl: this.props.codeUrl,
type: Message.quickInfo,
type: MessageType.quickInfo,
position,
})
this.setState({ quickInfo: data })
Expand Down Expand Up @@ -145,7 +148,9 @@ export default class App extends Component<any, AppState> {
<div
style={{
position: 'absolute',
background: occurrence.isWriteAccess ? colors.occurrenceWrite : colors.occurrenceRead,
background: occurrence.isWriteAccess
? colors.occurrenceWrite
: colors.occurrenceRead,
width: occurrence.width * this.props.fontWidth,
height: this.props.line.height,
top: occurrence.range.line * this.props.line.height,
Expand Down
8 changes: 4 additions & 4 deletions src/content-script/renderer.tsx
@@ -1,7 +1,7 @@
import { render, h } from 'preact'
import * as types from '../types'
import { RendererParams } from './adapter'
import App from './app'
import { ContentMessage, BackgroundMessage, MessageType } from '../types'

interface Padding {
left: number
Expand Down Expand Up @@ -30,10 +30,10 @@ export default class Renderer {
offsetTop: number
codeUrl: string

sendMessage: (data: types.ContentMessage, cb: (message: types.BackgroundMessage) => void) => void
sendMessage: (data: ContentMessage, cb: (message: BackgroundMessage) => void) => void

constructor(
sendMessage: (data: types.ContentMessage, cb: (message: types.BackgroundMessage) => void) => void,
sendMessage: (data: ContentMessage, cb: (message: BackgroundMessage) => void) => void,
renderParams: RendererParams,
) {
this.sendMessage = sendMessage
Expand Down Expand Up @@ -73,8 +73,8 @@ export default class Renderer {
// Create service on page load
this.sendMessage(
{
type: MessageType.service,
file: this.fileName,
type: types.Message.service,
codeUrl: this.codeUrl,
tabSize,
},
Expand Down

0 comments on commit 1a864b1

Please sign in to comment.