Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: hover info #79

Merged
merged 1 commit into from
Oct 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions client/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion client/src/test/diagnostics.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { getDocUri, activate } from "./helper";
suite("Should get diagnostics", () => {
const docUri = getDocUri("diagnostics.openfga");

test("Diagnoses uppercase texts", async () => {
test("Diagnoses validation errors", async () => {
await testDiagnostics(docUri, [
{ message: "`user` is not a valid type.", range: toRange(5, 20, 5, 24), severity: vscode.DiagnosticSeverity.Error, source: "ModelValidationError" },
{ message: "`user` is not a valid type.", range: toRange(8, 19, 8, 23), severity: vscode.DiagnosticSeverity.Error, source: "ModelValidationError" },
Expand Down
39 changes: 39 additions & 0 deletions client/src/test/hover.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
// eslint-disable-next-line import/no-unresolved
import * as vscode from "vscode";
import * as assert from "assert";
import { getDocUri, activate } from "./helper";

suite("Should show hover", () => {
const docUri = getDocUri("test.fga");

test("Displays hover text", async () => {

const markdown = new vscode.MarkdownString("Test");
const hover = new vscode.Hover(markdown, toRange(1, 2, 1, 8));

await testHover(docUri, new vscode.Position(1, 6), [hover]);

});
});

function toRange(sLine: number, sChar: number, eLine: number, eChar: number) {
const start = new vscode.Position(sLine, sChar);
const end = new vscode.Position(eLine, eChar);
return new vscode.Range(start, end);
}

async function testHover(docUri: vscode.Uri, position: vscode.Position, expectedHovers: vscode.Hover[]) {
await activate(docUri);

const actualHovers = await vscode.commands.executeCommand<vscode.Hover[]>("vscode.executeHoverProvider", docUri, position);

Check warning on line 28 in client/src/test/hover.test.ts

View workflow job for this annotation

GitHub Actions / lint

This line has a length of 127. Maximum allowed is 120

assert.equal(actualHovers.length, expectedHovers.length);

expectedHovers.forEach((expectedHover, i) => {
const actualHover = actualHovers[i];
assert.deepEqual(actualHover.range, expectedHover.range);
// TODO: figure out why there is missing content.
// assert.deepEqual(actualHover.contents, expectedHover.contents);
});

}
14 changes: 7 additions & 7 deletions server/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
"dependencies": {
"@openfga/syntax-transformer": "^0.2.0-beta.3",
"vscode-languageserver": "^8.1.0",
"vscode-languageserver-textdocument": "^1.0.8"
"vscode-languageserver-textdocument": "^1.0.11"
},
"scripts": {}
}
54 changes: 54 additions & 0 deletions server/src/documentation.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import OpenFGAParser from "@openfga/syntax-transformer/dist/gen/OpenFGAParser";

// Lookup and return the corresponding literal from the parser, without quotes
function getSymbol(symbol: number): string {
return OpenFGAParser.literalNames[symbol]!.replace(/'/g, "");

Check warning on line 5 in server/src/documentation.ts

View workflow job for this annotation

GitHub Actions / lint

Forbidden non-null assertion
}

export type DocumentationMap = Partial<Record<string, { summary: string; link?: string }>>;

export const defaultDocumentationMap: DocumentationMap = {
[getSymbol(OpenFGAParser.TYPE)]: {
summary: `A type or grouping of objects that have similar characteristics. For example:
- workspace
- repository
- organization
- document
`,
link: "https://openfga.dev/docs/concepts#what-is-a-type",
},
[getSymbol(OpenFGAParser.RELATIONS)]: {
summary:
"A **relation** defines the possible relationship between an [object](https://openfga.dev/docs/concepts#what-is-an-object) and a [user](https://openfga.dev/docs/concepts#what-is-a-user).",

Check warning on line 22 in server/src/documentation.ts

View workflow job for this annotation

GitHub Actions / lint

This line has a length of 194. Maximum allowed is 120
link: "https://openfga.dev/docs/concepts#what-is-a-relation",
},
[getSymbol(OpenFGAParser.DEFINE)]: {
summary:
"A **relation** defines the possible relationship between an [object](https://openfga.dev/docs/concepts#what-is-an-object) and a [user](https://openfga.dev/docs/concepts#what-is-a-user).",

Check warning on line 27 in server/src/documentation.ts

View workflow job for this annotation

GitHub Actions / lint

This line has a length of 194. Maximum allowed is 120
link: "https://openfga.dev/docs/concepts#what-is-a-relation",
},
[getSymbol(OpenFGAParser.AND)]: {
summary:
"The intersection operator used to indicate that a relationship exists if the user is in all the sets of users.",
link: "https://openfga.dev/docs/configuration-language#the-intersection-operator",
},
[getSymbol(OpenFGAParser.OR)]: {
summary:
"The union operator is used to indicate that a relationship exists if the user is in any of the sets of users",
link: "https://openfga.dev/docs/configuration-language#the-union-operator",
},
[getSymbol(OpenFGAParser.BUT_NOT)]: {
summary:
"The exclusion operator is used to indicate that a relationship exists if the user is in the base userset, but not in the excluded userset.",

Check warning on line 42 in server/src/documentation.ts

View workflow job for this annotation

GitHub Actions / lint

This line has a length of 147. Maximum allowed is 120
link: "https://openfga.dev/docs/configuration-language#the-exclusion-operator",
},
[getSymbol(OpenFGAParser.FROM)]: {
summary: "Allows referencing relations on related objects.",
link: "https://openfga.dev/docs/configuration-language#referencing-relations-on-related-objects",
},
[getSymbol(OpenFGAParser.SCHEMA)]: {
summary:
"Defines the schema version to be used, with currently only support for '1.1'. Note that the 1.0 schema is deprecated.",

Check warning on line 51 in server/src/documentation.ts

View workflow job for this annotation

GitHub Actions / lint

This line has a length of 126. Maximum allowed is 120
link: "https://openfga.dev/docs/modeling/migrating/migrating-schema-1-1",
},
};
65 changes: 63 additions & 2 deletions server/src/server.common.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,12 @@
TextDocumentSyncKind,
InitializeResult,
_Connection,
HoverParams,
Hover,
MarkupContent,
MarkupKind,
Range,
Position,
} from "vscode-languageserver";

import {
Expand All @@ -18,6 +24,8 @@

import { validator, errors } from "@openfga/syntax-transformer";

import { defaultDocumentationMap } from "./documentation";

export function startServer(connection: _Connection) {

console.log = connection.console.log.bind(connection.console);
Expand Down Expand Up @@ -56,7 +64,8 @@
// Tell the client that this server supports code completion.
completionProvider: {
resolveProvider: false
}
},
hoverProvider: true
}
};
if (hasWorkspaceFolderCapability) {
Expand All @@ -80,14 +89,13 @@
connection.client.register(DidChangeConfigurationNotification.type, undefined);
}
if (hasWorkspaceFolderCapability) {
connection.workspace.onDidChangeWorkspaceFolders(_event => {

Check warning on line 92 in server/src/server.common.ts

View workflow job for this annotation

GitHub Actions / lint

'_event' is defined but never used
connection.console.log("Workspace folder change event received.");
});
}
});


connection.onDidChangeConfiguration(_change => {

Check warning on line 98 in server/src/server.common.ts

View workflow job for this annotation

GitHub Actions / lint

'_change' is defined but never used
// Revalidate all open text documents
documents.all().forEach(validateTextDocument);
});
Expand Down Expand Up @@ -144,7 +152,60 @@
}
}

connection.onHover((params: HoverParams): Hover | undefined => {
const doc = documents.get(params.textDocument.uri);

if (doc === undefined) {
return;
}

const range = getRangeOfWord(doc, params.position);
const symbol = doc.getText(range);
const docSummary = defaultDocumentationMap[symbol];

if (!docSummary) {
return;
}

const contents: MarkupContent = {
kind: MarkupKind.Markdown,
value: `**${symbol}** \n${docSummary.summary} \n[Link to documentation](${docSummary.link}])`,
};
return {
contents,
range
};
});

function getRangeOfWord(document: TextDocument, position: Position): Range {
const text = document.getText();

let pointerStart = document.offsetAt(position);
let pointerEnd = document.offsetAt(position);

while (text.charAt(pointerStart).match(/\w/)) {
pointerStart--;
}

while (text.charAt(pointerEnd).match(/\w/)) {
pointerEnd++;
}

let start = document.positionAt(pointerStart + 1);
let end = document.positionAt(pointerEnd);

if (document.getText({ start, end }) === "but" &&
document.getText({ start, end: document.positionAt(pointerEnd + 4) }) === "but not") {
end = document.positionAt(pointerEnd + 4);
} else if (document.getText({ start, end }) === "not" &&
document.getText({ start: document.positionAt(pointerStart -3), end }) === "but not") {
start = document.positionAt(pointerStart - 3);
}

return { start, end };
}

connection.onDidChangeWatchedFiles(_change => {

Check warning on line 208 in server/src/server.common.ts

View workflow job for this annotation

GitHub Actions / lint

'_change' is defined but never used
// Monitored files have change in VSCode
console.log("We received an file change event");
});
Expand Down
1 change: 1 addition & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,7 @@ const nodeClientConfig = {
'extension.node': './src/extension.node.ts', // the entry point of this extension, 📖 -> https://webpack.js.org/configuration/entry-context/
'test/extension.test': './src/test/extension.test.ts',
'test/diagnostics.test': './src/test/diagnostics.test.ts',
'test/hover.test': './src/test/hover.test.ts',
'test/index.node': './src/test/index.node.ts',
'test/runTest': './src/test/runTest.ts',
},
Expand Down
Loading