Skip to content

Commit

Permalink
整理代码
Browse files Browse the repository at this point in the history
  • Loading branch information
sumneko committed Jul 5, 2024
1 parent 653dcb8 commit d9c3fd7
Show file tree
Hide file tree
Showing 4 changed files with 104 additions and 133 deletions.
2 changes: 1 addition & 1 deletion src/editorTable/EXCEL/test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import * as y3 from 'y3-helper';

export async function test() {
let table = y3.table.open('单位');
let table = y3.table.openTable('单位');
let obj = await table.get(134218426);
}
114 changes: 81 additions & 33 deletions src/editorTable/editorTable.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,31 +26,44 @@ type MapShape = {
[key: string]: any,
};

export class FieldInfo {
name: string;

constructor(public tableName: Table.NameCN, public field: string) {
const nameEN = Table.name.fromCN[tableName];
const languageKey = `code_explorer_${nameEN}_${field}`;
this.name = y3.language.get(languageKey) ?? field;
}
}

export class EditorObject {
private _raw?: ObjectShape;
private _name?: string;
private _json: string;
constructor(public key: number, public uri: vscode.Uri, json: string) {
this._json = json;
public json?: string;
public uri?: vscode.Uri;
constructor(public tableName: Table.NameCN, public key: number) {
}

public get raw(): ObjectShape {
public get raw(): ObjectShape | undefined {
if (!this._raw) {
if (!this.json) {
return;
}
this._raw = JSON.parse(this.json);
}
return this._raw!;
}

public get name(): string {
if (!this._name) {
let name = this.json.match(/"name"\s*:\s*(\-?\d*)/);
let name = this.json?.match(/"name"\s*:\s*(\-?\d*)/);
if (name && name[1]) {
let id = parseInt(name[1]);
if (!isNaN(id)) {
this._name = y3.language.get(id);
}
} else {
let name = this.raw.name;
let name = this.raw?.name;
if (typeof name === 'string') {
this._name = name;
} else if (typeof name === 'number') {
Expand All @@ -64,11 +77,10 @@ export class EditorObject {
return this._name;
}

public get json(): string {
return this._json;
}

public async rename(name: string): Promise<boolean> {
if (!this.uri || !this.json) {
return false;
}
let strKey = await y3.language.keyOf(name, true);
let raw: ObjectShape = JSON.parse(this.json);
raw.name = strKey;
Expand All @@ -77,11 +89,16 @@ export class EditorObject {
if (!suc) {
return false;
}
this.json = newJson;
this._name = name;
this._json = newJson;
this._raw = raw;
return true;
}

public getFieldInfo(field: string) {
let table = openTable(this.tableName);
return table.getFieldInfo(field);
}
}

async function loadObject(tableName: Table.NameCN, key: number) {
Expand All @@ -92,31 +109,15 @@ async function loadObject(tableName: Table.NameCN, key: number) {
}
await y3.language.ready();
try {
return new EditorObject(key, uri, file.string);
let obj = new EditorObject(tableName, key);
obj.uri = uri;
obj.json = file.string;
return obj;
} catch {
return null;
}
}

function getFileKey(fileName: string): number|undefined {
if (!fileName.toLowerCase().endsWith('.json')) {
return;
}
let keyStr = fileName.slice(0, -5).split('/').pop();
if (!keyStr) {
return;
}
// 确保只有数字
if (!/^\d+$/.test(keyStr)) {
return;
}
let key = parseInt(keyStr);
if (isNaN(key)) {
return;
}
return key;
}

interface CreateOptions {
/**
* 新对象的名称,如果不填则使用默认名称
Expand Down Expand Up @@ -229,7 +230,7 @@ export class EditorTable<N extends Table.NameCN> extends vscode.Disposable {
let templateJson: string;
if (options?.copyFrom) {
let obj = await this.get(options.copyFrom);
if (!obj) {
if (!obj || !obj.json) {
return undefined;
}
templateJson = obj.json;
Expand Down Expand Up @@ -258,6 +259,14 @@ export class EditorTable<N extends Table.NameCN> extends vscode.Disposable {
return await this.get(key);
}

private _fieldInfoCache: { [field: string]: FieldInfo } = {};
public getFieldInfo(field: string) {
if (!this._fieldInfoCache[field]) {
this._fieldInfoCache[field] = new FieldInfo(this.nameCN, field);
}
return this._fieldInfoCache[field];
}

private _listActions: ['create' | 'delete', number][] = [];
private resortList() {
if (this._listActions.length === 0) {
Expand Down Expand Up @@ -350,8 +359,47 @@ export class EditorTable<N extends Table.NameCN> extends vscode.Disposable {

let editorTables: { [key: string]: any } = {};

export function open<N extends Table.NameCN>(tableName: N): EditorTable<N> {
export function openTable<N extends Table.NameCN>(tableName: N): EditorTable<N> {
let table = editorTables[tableName]
?? (editorTables[tableName] = new EditorTable(tableName));
return table;
}

export function getFileKey(fileName: string): number | undefined {
if (!fileName.toLowerCase().endsWith('.json')) {
return;
}
let keyStr = fileName.slice(0, -5).split('/').pop();
if (!keyStr) {
return;
}
// 确保只有数字
if (!/^\d+$/.test(keyStr)) {
return;
}
let key = parseInt(keyStr);
if (isNaN(key)) {
return;
}
return key;
}

export async function getObject(uri: vscode.Uri): Promise<EditorObject | undefined> {
const nameEN = uri.path.match(/([^\/]+)\/[^\/]+\.json$/)?.[1];
if (!nameEN || !(nameEN in Table.name.toCN)) {
return;
}
const key = getFileKey(uri.path);
if (!key) {
return;
}
const file = await y3.fs.readFile(uri);
if (!file) {
return;
}
const nameCN = Table.name.toCN[nameEN as Table.NameEN];
const obj = new EditorObject(nameCN, key);
obj.uri = uri;
obj.json = file.string;
return obj;
}
111 changes: 17 additions & 94 deletions src/editorTable/objectSymbol.ts
Original file line number Diff line number Diff line change
@@ -1,107 +1,30 @@
import * as vscode from 'vscode';
import * as fs from 'fs';
import * as path from 'path';
import { isPathValid, getFileNameByVscodeUri } from '../utility';
import * as y3 from 'y3-helper';
import { Table } from '../constants';
import { EditorObject } from './editorTable';

/**
* 提供物编数据的Json文件内的中英文字段搜索的DocumentSymbolProvider
*/
export class GoEditorTableDocumentSymbolProvider implements vscode.DocumentSymbolProvider {
private englishKeyToChineseKey: any;
constructor(private zhlanguageJson: any = undefined ) {
let englishKeyToChineseKeyJsonPath = path.join(__dirname, "../../config/englishKeyToChineseKey.json");
if (isPathValid(englishKeyToChineseKeyJsonPath)) {
try {
this.englishKeyToChineseKey = JSON.parse(fs.readFileSync(englishKeyToChineseKeyJsonPath, 'utf8'));
}
catch (error) {
vscode.window.showErrorMessage("读取和解析" + englishKeyToChineseKeyJsonPath + "时失败,错误为:" + error);
}
}
else {
vscode.window.showErrorMessage("在以下路径找不到englishKeyToChineseKey.json:\n"+englishKeyToChineseKeyJsonPath);
}
}
public provideDocumentSymbols(
document: vscode.TextDocument, token: vscode.CancellationToken):
Thenable<vscode.SymbolInformation[]> {
let res: vscode.SymbolInformation[] = [];
if (token.isCancellationRequested) {
return Promise.resolve(res);
}
res=this.getEditorTableJsonDocumentSymbols(document);
let objectMap: { [key: string]: EditorObject | null } = {};

return Promise.resolve(res);
}
private getEditorTableJsonDocumentSymbols(document: vscode.TextDocument): vscode.SymbolInformation[] {
let res: vscode.SymbolInformation[] = [];
const keyToLine: { [key: string]: number } = {};
let editorTableJsonData:any = JSON.parse(document.getText());
for (let i = 0; i < document.lineCount; i++){
let line = document.lineAt(i).text;
const matches = line.match(/"\s*([^"]+)"\s*(?=:)/g);// 正则表达式匹配双引号内,且后缀为':'的字符串,视为Json的键
if (matches) {
matches.forEach(match => {
match = match.substring(1, match.length - 1);
keyToLine[match] = i;
});
};
}
let fileName: string = getFileNameByVscodeUri(vscode.Uri.file(document.fileName));
let chineseName = this.zhlanguageJson[editorTableJsonData['name']];
let finalFileName = fileName;
if (chineseName !== undefined && typeof chineseName === 'string') {
finalFileName = chineseName + "(" + fileName.substring(0, fileName.length - 5) + ")";//这是一个单位(134219828)"的格式
}
for (let key in keyToLine) {
let name = key;
let kind: vscode.SymbolKind;

if (typeof editorTableJsonData[key] === typeof []) {
kind = vscode.SymbolKind.Array;
export class Provider implements vscode.DocumentSymbolProvider {
async provideDocumentSymbols(document: vscode.TextDocument) {
const uri = document.uri;
if (objectMap[uri.path] === undefined) {
objectMap[uri.path] = await y3.table.getObject(uri) ?? null;
}
else if (typeof editorTableJsonData[key]===typeof {} ) {
kind = vscode.SymbolKind.Module;
let object = objectMap[uri.path];
if (object === null) {
return;
}
else if (typeof editorTableJsonData[key] === typeof true) {
kind = vscode.SymbolKind.Boolean;
}
else if (!isNaN(editorTableJsonData[key])) {
kind = vscode.SymbolKind.Number;
}
else if (typeof editorTableJsonData[key] === typeof "") {
kind = vscode.SymbolKind.String;
}
else {
kind = vscode.SymbolKind.Module;
}

let uri: vscode.Uri = document.uri;
let location: vscode.Location = new vscode.Location(document.uri, new vscode.Position(keyToLine[key], 0));
let containerName = finalFileName;
if (key in this.englishKeyToChineseKey) {
// todo:获得字段对应的中文名
name = this.englishKeyToChineseKey[key] + '(' + key + ')';
let symbolInformation: vscode.SymbolInformation = new vscode.SymbolInformation(
name,
kind,
containerName,
location
);
res.push(symbolInformation);
}

}

return res;
return undefined;
}
}

export function init() {

vscode.languages.registerDocumentSymbolProvider({
scheme: 'file',
language: 'json',
}, new GoEditorTableDocumentSymbolProvider());

}, new Provider());
vscode.workspace.onDidChangeTextDocument((e) => {
delete objectMap[e.document.uri.path];
});
}
10 changes: 5 additions & 5 deletions src/editorTable/treeView.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class FileNode extends vscode.TreeItem {

public object?: editorTable.EditorObject;
public update(): void | Promise<void> {
let table = editorTable.open(this.tableName);
let table = editorTable.openTable(this.tableName);
this.object = table.fetch(this.key);
if (this.object) {
this.label = `${this.object.name}(${this.key})`;
Expand Down Expand Up @@ -48,7 +48,7 @@ class DirNode extends vscode.TreeItem {
) {
super(`${tableName}(加载中...)`);

this.table = editorTable.open(tableName);
this.table = editorTable.openTable(tableName);
this.resourceUri = this.table.uri;
this.id = tableName;
}
Expand All @@ -68,7 +68,7 @@ class DirNode extends vscode.TreeItem {

public async getChildren(): Promise<FileNode[]> {
let nodes: FileNode[] = [];
let table = editorTable.open(this.tableName);
let table = editorTable.openTable(this.tableName);
let keys = await table.getList();
for (const key of keys) {
nodes.push(new FileNode(this, this.tableName, key));
Expand Down Expand Up @@ -192,7 +192,7 @@ class TreeView extends vscode.Disposable {

// 删除
vscode.commands.registerCommand("y3-helper.deleteEditorTableItem", (fileNode: FileNode) => {
let table = editorTable.open(fileNode.tableName);
let table = editorTable.openTable(fileNode.tableName);
table.delete(fileNode.key);
});

Expand Down Expand Up @@ -277,7 +277,7 @@ class TreeView extends vscode.Disposable {
return;
}

let table = editorTable.open(tableName);
let table = editorTable.openTable(tableName);
let newKey = await vscode.window.showInputBox({
prompt: 'key',
value: (await table.makeNewKey()).toString(),
Expand Down

0 comments on commit d9c3fd7

Please sign in to comment.