Skip to content

Commit

Permalink
Extracted HoverProvider as own class. Updated Changelog. (#178)
Browse files Browse the repository at this point in the history
Signed-off-by: Jerome Luckenbach <github@luckenba.ch>
  • Loading branch information
Confectrician authored Nov 11, 2019
1 parent 38b3a17 commit 2686ee3
Show file tree
Hide file tree
Showing 4 changed files with 133 additions and 69 deletions.
3 changes: 2 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [0.6.0] - 2019-11-tba

### Added
- Add hover provider with rest api integration (#146)
- Add hover provider with rest api integration (#146, #178)
- Add/Move to an azure build pipeline environment (#148, #150, #166)
- Add support for webpack (#155)
- Added output channel for better user interaction (#156)
Expand All @@ -22,6 +22,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Clean Readme and introduce docs folder (#149)
- Refactor language config files (#154)
- Make TreeView visible when `restApi` is available to benefit from it in `JSR223` developing (#154)
- Made some commands directly accessible in things explorer (#177)

### Fixed
- Fix https lsp problems (#139)
Expand Down
116 changes: 116 additions & 0 deletions client/src/HoverProvider/HoverProvider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import { Hover } from 'vscode'
import { MarkdownString } from 'vscode'

import * as utils from '../Utils'
import * as request from 'request-promise-native'

/**
* Handles hover actions in editor windows.
* Provides additional information for existing items through rest api.
*
* @author Jerome Luckenbach - Initial contribution
*/
export class HoverProvider {

/**
* Only allow a single provider to exist at a time.
*/
private static _currentProvider: HoverProvider | undefined

/**
*
*/
private knownItems:String[]

/**
*
*/
private lastItemsUpdate : Number;

/**
* Only allow the class to call the constructor
*/
public constructor(){
this.updateItems()
}

/**
* Checks hovered editor area for existing openHAB Items and provides some live data from rest api if aan item name is found.
*
* @param hoveredText The currently hovered text part
* @returns A thenable [Hover](Hover) object with live information or null if no item is found
*/
public getRestHover(hoveredText) : Thenable<Hover>|null {
console.log(`Checking if => ${hoveredText} <= is a knownItem now`)
if(this.knownItems.includes(hoveredText)){
return new Promise((resolve, reject) => {
console.log(`Requesting => ${utils.getHost()}/rest/items/${hoveredText} <= now`)

request(`${utils.getHost()}/rest/items/${hoveredText}`)
.then((response) => {
let result = JSON.parse(response)

if(!result.error) {
let resultText = new MarkdownString()

// Show Member Information for Group Items too
if(result.type === "Group"){
resultText.appendCodeblock(`Item ${result.name} | ${result.state}`, 'openhab')
resultText.appendMarkdown(`##### Members:`)

result.members.forEach( (member, key, result) => {
resultText.appendCodeblock(`Item ${member.name} | ${member.state}`, 'openhab')

// No newline after the last member information
if(!Object.is(result.length - 1, key)){
resultText.appendText(`\n`)
}
});
}
else{
resultText.appendCodeblock(`${result.state}`, 'openhab');
}

resolve(new Hover(resultText))
}
})
.catch(() => reject(false))
});
}
else {
console.log(`That's no openHAB item. Waiting for the next hover.`)
return null
}
}

/**
* Update known Items array and store the last time it has been updated.
*/
private updateItems() : Boolean {

request(`${utils.getHost()}/rest/items/`)
.then((response) => {
// Clear prossible existing array
this.knownItems = new Array<String>()

let result = JSON.parse(response)

result.forEach(item => {
this.knownItems.push(item.name)
});

this.lastItemsUpdate = Date.now()

return true
})
.catch((error) => {
console.log(`Failed to update Items for HoverProvider`)
console.log(error)

utils.appendToOutput(`Could not reload items for HoverProvider`)

return false
});
return false
}
}
73 changes: 8 additions & 65 deletions client/src/Utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ let extensionOutput: OutputChannel = null

/**
* Humanize function adapter from the previously included underscore.string library
*
*
* @param str The string to convert
*/
export function humanize(str: string) : string {
Expand Down Expand Up @@ -64,64 +64,7 @@ export function getHost() {
}

/**
* Checks hovered editor area for existing openHAB Items and provides some live data from rest api if aan item name is found.
*
* @param hoveredText The currently hovered text part
* @returns A thenable [Hover](Hover) object with live information or null if no item is found
*/
export function getRestHover(hoveredText) : Thenable<Hover>|null {
return new Promise((resolve, reject) => {

console.log(`Requesting => ${getHost()}/rest/items/${hoveredText} <= now`)

request(`${getHost()}/rest/items/${hoveredText}`)
.then((response) => {

let result = JSON.parse(response)

if(!result.error) {

let resultText = new MarkdownString()

if(result.type === "Group"){

resultText.appendCodeblock(`Item ${result.name} | ${result.state}`, 'openhab');
resultText.appendMarkdown(`##### Members:`)

result.members.forEach( (member, key, result) => {

resultText.appendCodeblock(`Item ${member.name} | ${member.state}`, 'openhab')

// No newline after the last member information
if(!Object.is(result.length - 1, key)){
resultText.appendText(`\n`)
}

});

}
else{

resultText.appendCodeblock(`${result.state}`, 'openhab');

}

resolve(new Hover(resultText))

}
else {

console.log(`That's no openHAB item. Waiting for the next hover.`)
resolve(null)

}
})
.catch(() => reject(false))
})
}

/**
* Returns the current simple mode status retreived via rest api
* Returns the current simple mode status retreived via rest api
*/
export function getSimpleModeState(): Thenable<Boolean> {
return new Promise((resolve, reject) => {
Expand All @@ -147,7 +90,7 @@ export function getSitemaps(): Thenable<any[]> {

/**
* Opens an external browser with the given url.
*
*
* @param url The url to navigate to
*/
export function openBrowser(url) {
Expand All @@ -166,7 +109,7 @@ export function openBrowser(url) {

/**
* Opens a vscode Webview panel aside, with the given data.
*
*
* @param extensionPath The path of this extension
* @param query The query to append. Defaults to the basic ui node.
* @param title The title, that will be shown for the UI tab.
Expand All @@ -178,13 +121,13 @@ export function openUI(extensionPath: string, query: string = "/basicui/app", ti
PreviewPanel.createOrShow(
extensionPath,
(title !== undefined) ? title : undefined,
srcPath
srcPath
);
}

/**
* Handle a occuring request error.
*
*
* @param err The current error
*/
export async function handleRequestError(err) {
Expand All @@ -208,11 +151,11 @@ export async function handleRequestError(err) {
/**
* This will send a message frmo the extension to its output channel.
* If the channel isn't existing already, it will be created during method run.
*
*
* @param message The message to append to the extensions output Channel
*/
export function appendToOutput(message: string){

if(!extensionOutput) { extensionOutput = window.createOutputChannel("openHAB Extension") }

extensionOutput.appendLine(message)
Expand Down
10 changes: 7 additions & 3 deletions client/src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,14 @@ import { RemoteLanguageClientProvider } from './LanguageClient/RemoteLanguageCli
import { Item } from './ItemsExplorer/Item'
import { Thing } from './ThingsExplorer/Thing'
import { Channel } from './ThingsExplorer/Channel'
import { HoverProvider } from './HoverProvider/HoverProvider';

import * as _ from 'lodash'
import * as ncp from 'copy-paste'
import * as path from 'path'

let _extensionPath: string;
let ohStatusBarItem: StatusBarItem;
let _extensionPath: string
let ohStatusBarItem: StatusBarItem

/**
* Initializes the openHAB extension
Expand Down Expand Up @@ -139,6 +140,7 @@ async function init(disposables: Disposable[], config, context): Promise<void> {
const itemsExplorer = new ItemsExplorer()
const thingsExplorer = new ThingsExplorer()
const itemsCompletion = new ItemsCompletion()
const ohHoverProvider = new HoverProvider()

disposables.push(window.registerTreeDataProvider('openhabItems', itemsExplorer))
disposables.push(window.registerTreeDataProvider('openhabThings', thingsExplorer))
Expand Down Expand Up @@ -171,6 +173,7 @@ async function init(disposables: Disposable[], config, context): Promise<void> {
disposables.push(commands.registerCommand('openhab.command.things.copyUID', (query) =>
ncp.copy(query.UID || query.uid)))


disposables.push(languages.registerHoverProvider({ language: 'openhab', scheme: 'file'}, {

provideHover(document, position, token){
Expand All @@ -183,7 +186,8 @@ async function init(disposables: Disposable[], config, context): Promise<void> {
return null
}

return utils.getRestHover(hoveredText)
// Will return null or the hover content
return ohHoverProvider.getRestHover(hoveredText)
}
})

Expand Down

0 comments on commit 2686ee3

Please sign in to comment.