Skip to content

Commit

Permalink
updates
Browse files Browse the repository at this point in the history
  • Loading branch information
Jason Williams committed Aug 7, 2020
1 parent cfbfd32 commit 17a8905
Show file tree
Hide file tree
Showing 7 changed files with 124 additions and 27 deletions.
3 changes: 2 additions & 1 deletion .vscode/launch.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,8 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": ["--extensionDevelopmentPath=${workspaceFolder}"],
"outFiles": ["${workspaceFolder}/out/**/*.js"]
"outFiles": ["${workspaceFolder}/out/**/*.js"],
"sourceMaps": true
},
{
"name": "Extension Tests",
Expand Down
15 changes: 14 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,18 @@
"out": true // set this to false to include "out" folder in search results
},
// Turn off tsc task auto detection since we have the necessary tasks as npm scripts
"typescript.tsc.autoDetect": "off"
"typescript.tsc.autoDetect": "off",
"cSpell.words": [
"anki",
"arial",
"frontmatter",
"jasew",
"plugin",
"vscode",
"vscode anki plugin"
],
"cSpell.ignoreWords": [
"initialised",
"uninitialised"
]
}
68 changes: 53 additions & 15 deletions src/AnkiCardProvider.ts
Original file line number Diff line number Diff line change
@@ -1,27 +1,50 @@
import { join } from "path";
import * as vscode from "vscode";
import {
TreeItemCollapsibleState,
TreeItem,
ExtensionContext,
TreeDataProvider,
window,
Uri,
} from "vscode";
import { AnkiService } from "./AnkiService";
import { IContext } from "./extension";
import { AnkiFS } from "./fileSystemProvider";

export class AnkiCardProvider implements vscode.TreeDataProvider<Dependency> {
export class AnkiCardProvider implements TreeDataProvider<Dependency> {
private ankiService: AnkiService;
private context: vscode.ExtensionContext;
private context: ExtensionContext;
private ankiFS: AnkiFS;
private state: any;

constructor(extContext: IContext) {
this.ankiService = extContext.ankiService;
this.context = extContext.context;
if (!extContext?.getAnkiFS || !extContext.getAnkiState) {
throw new Error("Anki Error: initialised AnkiFS/AnkiState is required");
}

this.state = extContext.getAnkiState();
this.ankiFS = extContext.getAnkiFS();
}

getTreeItem(element: Dependency): vscode.TreeItem {
getTreeItem(element: Dependency): TreeItem {
return element;
}

async getChildren(element?: Dependency) {
// get children of Deck
if (element) {
// as cards don't have children element would be a Deck or templates folder
if (element.uri === "anki:/templates") {
return this.getAllModels();
}

if (element.uri.match(new RegExp("anki:/templates/w+"))) {
const uri = element.uri;
const model = element.uri.replace("anki:/templates/", "");
this.getModelTemplates(model);
}

let cards;
try {
cards = await this.ankiService.findCards(`\"deck:${element.label}\"`);
Expand All @@ -31,35 +54,43 @@ export class AnkiCardProvider implements vscode.TreeDataProvider<Dependency> {
return new Dependency(
v.question,
v.id?.toString() ?? i.toString(),
vscode.TreeItemCollapsibleState.None,
`anki:/${v.deckName}/${v.question}`
TreeItemCollapsibleState.None,
`anki:/decks/${v.deckName}/${v.id?.toString()}`
);
});
}

// Top level, get decks
/** Top level */

// Create top level directories in the virtual file system.
this.ankiFS.createDirectory(Uri.parse("anki:/templates"));
this.ankiFS.createDirectory(Uri.parse("anki:/decks"));
let decks;

try {
decks = await this.ankiService.deckNamesAndIds();
} catch (e) {
vscode.window.showErrorMessage("Failed to get any Anki Decks");
window.showErrorMessage("Failed to get any Anki Decks");
return;
}

const deps = decks.map((v, i) => {
// Create a directory for this deck in the file system
// this.ankiService.getDeckNameFromId(v.id?.toString() || "", this.state);
this.ankiFS.createDirectory(Uri.parse(`anki:/decks/${v.id?.toString()}`));
return new Dependency(
v.name,
v.id?.toString(10) || i.toString(),
vscode.TreeItemCollapsibleState.Collapsed,
`anki:/decks/${v.name}`,
TreeItemCollapsibleState.Collapsed,
`anki:/decks/${v.id?.toString(10)}`,
this.getIconPath("deck")
);
});

const templates = new Dependency(
"__Templates__",
"000000",
vscode.TreeItemCollapsibleState.Collapsed,
TreeItemCollapsibleState.Collapsed,
"anki:/templates",
this.getIconPath("collection")
);
Expand All @@ -75,11 +106,14 @@ export class AnkiCardProvider implements vscode.TreeDataProvider<Dependency> {

let templateDeps: Dependency[] = [];
for (const [key, value] of Object.entries(models)) {
// Add all the models to the file system as folders
// Normally I would use id here but the API queries are done by name
this.ankiFS.createDirectory(Uri.parse(`anki:/templates/${key}`));
templateDeps.push(
new Dependency(
key,
value.toString(),
vscode.TreeItemCollapsibleState.Collapsed,
TreeItemCollapsibleState.Collapsed,
`anki:/templates/${key}`,
this.getIconPath("noteType")
)
Expand All @@ -89,6 +123,10 @@ export class AnkiCardProvider implements vscode.TreeDataProvider<Dependency> {
return templateDeps;
}

async getModelTemplates(model: string) {
console.log(model);
}

getIconPath(iconName: string): object {
return {
light: join(
Expand All @@ -111,11 +149,11 @@ export class AnkiCardProvider implements vscode.TreeDataProvider<Dependency> {
}
}

class Dependency extends vscode.TreeItem {
class Dependency extends TreeItem {
constructor(
public readonly label: string,
public readonly id: string,
public readonly collapsibleState: vscode.TreeItemCollapsibleState,
public readonly collapsibleState: TreeItemCollapsibleState,
public uri: string,
public iconPath?: any
) {
Expand Down
15 changes: 15 additions & 0 deletions src/AnkiService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { Deck } from "./models/Deck";
import { Card } from "./models/Card";
import { getLogger } from "./logger";
import { CONSTANTS } from "./constants";
import { IAnkiState } from "./state";

interface IResponse {
result: any;
Expand Down Expand Up @@ -67,6 +68,17 @@ export class AnkiService {
return response;
}

// Tries to convert a deck name from an ID
async getDeckNameFromId(id: string, state: IAnkiState) {
// If values are already there use them
const deckNameAndIds =
state.api.deckNamesAndIds ?? (await this.deckNamesAndIds());

Object.entries(deckNameAndIds).filter((v) => {
console.log(v);
});
}

/**
* Will not overwrite a deck that exists with the same name.
*/
Expand Down Expand Up @@ -102,6 +114,9 @@ export class AnkiService {
return await this.invoke("modelNamesAndIds");
}

async modelTemplates(modelName: string): Promise<object> {
return await this.invoke("modelTemplates", { modelName });
}
async updateModelTemplate(model: any) {
return await this.invoke("updateModelTemplates", {
model: {
Expand Down
10 changes: 8 additions & 2 deletions src/extension.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import { createOrUpdateTemplate } from "./manageTemplate";
import semver from "semver";
import { subscriptions } from "./subscriptions";
import { AnkiFS, initFilesystem } from "./fileSystemProvider";
import { initState, getAnkiState } from "./state";

require("./resources/vscodeAnkiPlugin.scss");

Expand All @@ -36,7 +37,8 @@ export interface IContext {
context: ExtensionContext;
logger: IVSCodeExtLogger;
config: IConfig;
ankiFS?: AnkiFS;
getAnkiFS?: () => AnkiFS;
getAnkiState?: () => any;
}

// this method is called when your extension is activated
Expand Down Expand Up @@ -96,7 +98,11 @@ export function activate(context: ExtensionContext) {

subscriptions(extContext);

// initFilesystem(extContext);
// FileSystem needs to be initiated before the TreeView Api
initFilesystem(extContext);

initState();
extContext.getAnkiState = getAnkiState;

// Register TreeView API
window.registerTreeDataProvider("decks", new AnkiCardProvider(extContext));
Expand Down
18 changes: 10 additions & 8 deletions src/fileSystemProvider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,17 @@ import * as path from "path";
import * as vscode from "vscode";
import { IContext } from "./extension";

let _ankiFs;
let _ankiFs: AnkiFS;
let _initialised = false;

const getAnkiFS = (): AnkiFS => {
if (_initialised !== true) {
throw new Error("Trying to access an uninitialised file system!");
}

return _ankiFs;
};

export class File implements vscode.FileStat {
type: vscode.FileType;
ctime: number;
Expand Down Expand Up @@ -169,7 +177,6 @@ export class AnkiFS implements vscode.FileSystemProvider {

export const initFilesystem = (ctx: IContext) => {
_ankiFs = new AnkiFS();
ctx.ankiFS = _ankiFs;
_initialised = true;

ctx.context.subscriptions.push(
Expand All @@ -178,10 +185,5 @@ export const initFilesystem = (ctx: IContext) => {
})
);

_ankiFs.createDirectory(vscode.Uri.parse("anki:/notes"));
_ankiFs.writeFile(
vscode.Uri.parse(`anki:/notes/something`),
Buffer.from("let a:number = true; console.log(a);"),
{ create: true, overwrite: true }
);
ctx.getAnkiFS = getAnkiFS;
};
22 changes: 22 additions & 0 deletions src/state.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
let _ankiState: any;
let _initialised = false;

export interface IAnkiState {
api: {
deckNamesAndIds: { [key: string]: number }[];
};
}

_ankiState = {};

export const initState = () => {
_initialised = true;
};

export const getAnkiState = (): IAnkiState => {
if (!_initialised) {
throw new Error("Anki State not initialised");
}

return _ankiState;
};

0 comments on commit 17a8905

Please sign in to comment.