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

Document formatting provider added #78

Merged
merged 18 commits into from
Sep 9, 2021
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
Next Next commit
update notes service added
fixed withProgress calls
  • Loading branch information
pmahend1 committed Sep 9, 2021
commit 8b2c116f6857a4e9115c0c227904ce8dc7dad835
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -180,9 +180,12 @@
"vscode-test": "^1.4.0"
},
"dependencies": {
"@types/compare-versions": "^3.3.0",
"compare-versions": "^3.6.0",
"electron-edge-js": "file:./lib/electron-edge-js",
"electron-edge-js-mac": "file:./lib/electron-edge-js-mac",
"fs": "^0.0.1-security",
"install": "^0.13.0"
"install": "^0.13.0",
"path": "^0.12.7"
}
}
153 changes: 75 additions & 78 deletions src/extension.ts
Original file line number Diff line number Diff line change
@@ -1,122 +1,119 @@
/* eslint-disable @typescript-eslint/naming-convention */
// imports
// imports
import * as vscode from "vscode";
import * as fs from "fs";
import { DocumentHelper } from "./documentHelper";
import { Formatter } from "./formatter";
import { LocalStorage } from "./localstorage";
import { PrettyXmlFormattingEditProvider } from "./prettyXmlFormattingEditProvider";
import { NotificationService } from "./notificationService";

let formatter: Formatter;
let localStorage : LocalStorage;
let notificationService: NotificationService;

//extension activate
export function activate(context: vscode.ExtensionContext)
{
try
{
formatter = new Formatter(context);
localStorage = new LocalStorage();
localStorage.hasShownUpdateNotification = false;
//prettify command definition
var progressOptions = {
location: vscode.ProgressLocation.Notification,
title: "Pretty XML",
cancellable: false
};


try
{
var localStorageJson = fs.readFileSync('prettXmlData.json', {encoding : 'utf8'});
if(localStorageJson)
{
localStorage = JSON.parse(localStorageJson);
}
}
catch (error)
{
localStorage = new LocalStorage();
localStorage.hasShownUpdateNotification = false;
try
{
let fileText :string = JSON.stringify(localStorage);
fs.writeFileSync("prettXmlData.json", fileText);
}
catch (error)
{

}
notificationService = new NotificationService(context);

}

var progressOptions = {
location: vscode.ProgressLocation.Notification,
title: "Pretty XML",
cancellable: false,
};

if(localStorage.hasShownUpdateNotification === false)
{
vscode.window.showInformationMessage('Now you can use Pretty XML as default document formatter.\nSet Pretty XML as default XML formatter and use press formatting keybinds');
localStorage.hasShownUpdateNotification = true;

try
{
let fileText :string = JSON.stringify(localStorage);
fs.writeFileSync("prettXmlData.json", fileText);
}
catch (error)
{

}
}

let prettifyXmlCommand = vscode.commands.registerTextEditorCommand("prettyxml.prettifyxml" ,
() =>
notificationService.notifyWhatsNewInUpdate();

let prettifyXmlCommand = vscode.commands.registerTextEditorCommand("prettyxml.prettifyxml",
() => vscode.window.withProgress(progressOptions, (progress, token) =>
{
vscode.window.withProgress(progressOptions,async (progress) =>
var promise = new Promise<string>((resolve) =>
{
progress.report({ message: "Formatting..." });
var formattedText = await formatter.formatXml();
DocumentHelper.replaceDocumentText(formattedText);
progress.report({ message: "Formatting...", increment: 0 });

setTimeout(() =>
{
progress.report({ message: "Formatting...", increment: 25 });

}, 100);

setTimeout(async () =>
{
var formattedText = await formatter.formatXml();
progress.report({ message: "Formatting...", increment: 75 });
resolve(formattedText);

DocumentHelper.replaceDocumentText(formattedText);
progress.report({ message: "Formatting...", increment: 100 });

}, 250);
});
});

return promise;
}));

let minimizeXmlCommand = vscode.commands.registerTextEditorCommand("prettyxml.minimizexml",
() =>
() => vscode.window.withProgress(progressOptions, (progress) =>
{
vscode.window.withProgress(progressOptions, async (progress) =>
var promise = new Promise<string>((resolve) =>
{
progress.report({ message: "Minimizing..." });
var minimizedText = await formatter.minimizeXml();
DocumentHelper.replaceDocumentText(minimizedText);
progress.report({ message: "Minimizing...", increment: 0 });

setTimeout(() =>
{
progress.report({ message: "Minimizing...", increment: 25 });
}, 100);

setTimeout(async () =>
{
var minimizedText = await formatter.minimizeXml();
progress.report({ message: "Minimizing...", increment: 75 });
resolve(minimizedText);

DocumentHelper.replaceDocumentText(minimizedText);
progress.report({ message: "Minimizing...", increment: 100 });
}, 250);
});
});

vscode.workspace.onDidSaveTextDocument(async () =>
{
let prettyXmlConfig = vscode.workspace.getConfiguration('prettyxml.settings');
let formatOnSave = prettyXmlConfig.get<boolean>('formatOnSave') ?? false;
if(formatOnSave)
return promise;
}));


vscode.workspace.onDidSaveTextDocument(async () =>
{
let prettyXmlConfig = vscode.workspace.getConfiguration("prettyxml.settings");
let formatOnSave = prettyXmlConfig.get<boolean>("formatOnSave") ?? false;
if (formatOnSave)
{
var formattedText = await formatter.formatXml();
DocumentHelper.replaceDocumentText(formattedText);
}
});

const xmlXsdDocSelector = [ ...DocumentHelper.createLanguageDocumentFilters("xml"), ...DocumentHelper.createLanguageDocumentFilters("xsd") ];
const xmlXsdDocSelector = [
...DocumentHelper.createLanguageDocumentFilters("xml"),
...DocumentHelper.createLanguageDocumentFilters("xsd"),
];
const xmlFormattingEditProvider = new PrettyXmlFormattingEditProvider(formatter);

let languageProvider = vscode.languages.registerDocumentFormattingEditProvider(xmlXsdDocSelector, xmlFormattingEditProvider);

//subscribe commands
context.subscriptions.push(prettifyXmlCommand, minimizeXmlCommand, languageProvider);
context.subscriptions.push(
prettifyXmlCommand,
minimizeXmlCommand,
languageProvider
);
}
catch (exception)
{
let errorMessage = (exception as Error)?.message;
vscode.window.showErrorMessage(errorMessage);
console.log(exception);
console.error(exception);
}
}


//extension deactivate
export function deactivate()
{

}
export function deactivate() { }
9 changes: 8 additions & 1 deletion src/formatter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,14 @@ export class Formatter
try
{
this.loadSettings();

// for (let i = 0; i < 40000; i++)
// {
// for (let index = 0; index < 500000; index++)
// {

// }
// }

var docText = DocumentHelper.getDocumentText();
let formattedString: string = "";

Expand Down
4 changes: 0 additions & 4 deletions src/localstorage.ts

This file was deleted.

6 changes: 6 additions & 0 deletions src/newReleaseNotifications.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
[
{
"version": "1.0.0",
"updateNotes": "Now you can set Pretty XML as your default XML formatter.\n You can use formatting keybind to format once you set it as default."
}
]
104 changes: 104 additions & 0 deletions src/notificationService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import * as vscode from "vscode";
import * as compareVersions from "compare-versions";
import * as fs from "fs";
import { UpdateNote } from "./updateNote";
import * as path from "path";
export class NotificationService
{
private context: vscode.ExtensionContext;
public readonly storageKeyPrefix: string;

private lastNotifiedDateKey: string;
constructor(context: vscode.ExtensionContext)
{
this.context = context;
this.storageKeyPrefix = this.context.extension.id + ".";
this.lastNotifiedDateKey = `${this.storageKeyPrefix}lastNotifiedDate`;
}

private checkIfEligibletToShowUpdateNote(): boolean
{
let shouldDisplay: boolean = true;
try
{
const versionKey = `${this.storageKeyPrefix}version`;
const currentVersion = this.context.extension.packageJSON.version;
var lastVersionShown = this.context.globalState.get(versionKey) as string;


if(lastVersionShown)
{
if (compareVersions.compare(currentVersion, lastVersionShown, '='))
{
var minus15days = new Date();
minus15days.setDate(minus15days.getDate() - 15);

var lastNotifiedDate = this.context.globalState.get(this.lastNotifiedDateKey) as Date;
let dateEligible = lastNotifiedDate === undefined || lastNotifiedDate === null || lastNotifiedDate < minus15days;
shouldDisplay = dateEligible;
}
else
{
shouldDisplay = true;
}
}
else
{
shouldDisplay = true;
this.context.globalState.update(versionKey, currentVersion);
}

}
catch (error)
{
console.error(error);
shouldDisplay = true;
}
return shouldDisplay;
}

private getUpdateNotes(version: string)
{
let updateNotes: string = "";
try
{
let filePath = path.join(this.context.extensionPath , "src","newReleaseNotifications.json");
var content = fs.readFileSync(filePath, { "encoding": "utf8" });
let releaseNotes: UpdateNote[] = JSON.parse(content);
var currentUpdateNote = releaseNotes.find((x) => { return x.version === version; });

if (currentUpdateNote)
{
updateNotes = currentUpdateNote.updateNotes;
}

}
catch (error)
{
console.error(error);
}
return updateNotes;
}

public notifyWhatsNewInUpdate(): void
{
try
{
let shouldDisplay: boolean = this.checkIfEligibletToShowUpdateNote();
if (shouldDisplay)
{
var currentVersion = this.context.extension.packageJSON.version;
var notes = this.getUpdateNotes(currentVersion);
if (notes !== "")
{
vscode.window.showInformationMessage(notes);
this.context.globalState.update(this.lastNotifiedDateKey, new Date());
}
}
}
catch (error)
{
console.error(error);
}
}
}
5 changes: 5 additions & 0 deletions src/updateNote.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export class UpdateNote
{
public version: string = "";
public updateNotes: string = "";
}
Loading