Added basic UI

This commit is contained in:
mdnapo 2024-09-15 22:25:14 +02:00
parent 8d1069e477
commit 23324a2b53
56 changed files with 15501 additions and 29 deletions

View File

@ -0,0 +1,43 @@
using DevDisciples.Json.Tools.API.Requests;
using Microsoft.AspNetCore.Mvc;
namespace DevDisciples.Json.Tools.API.Controllers;
[ApiController]
[Route("api/[controller]")]
public class TransformController : ControllerBase
{
[HttpPost("uglify")]
public IActionResult Uglify([FromBody] UglifyRequest request)
{
var context = new JsonFormatter.Context { Beautify = false };
var result = JsonFormatter.Format(request.Source, context);
return Ok(new { Result = result });
}
[HttpPost("prettify")]
public IActionResult Prettify([FromBody] PrettifyRequest request)
{
var context = new JsonFormatter.Context { Beautify = true, IndentSize = request.IndentSize };
var result = JsonFormatter.Format(request.Source, context);
return Ok(new { Result = result });
}
[HttpPost("json2csharp")]
public IActionResult Json2CSharp([FromBody] Json2CsharpRequest request)
{
var context = new Json2CSharpTranslator.Context
{
RootClassName = request.RootClassName,
Namespace = request.Namespace,
};
var result = Json2CSharpTranslator.Translate(request.Source, context);
return Ok(new { Result = result });
}
}

View File

@ -12,4 +12,8 @@
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.4.0"/>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DevDisciples.Json.Tools\DevDisciples.Json.Tools.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,46 @@
using DevDisciples.Parsing;
using Microsoft.AspNetCore.Diagnostics;
using Microsoft.AspNetCore.Mvc;
namespace DevDisciples.Json.Tools.API;
public class GlobalExceptionHandler : IExceptionHandler
{
public const int ParsingExceptionStatusCode = 499;
private readonly ILogger<GlobalExceptionHandler> _logger;
public GlobalExceptionHandler(ILogger<GlobalExceptionHandler> logger)
{
_logger = logger;
}
public async ValueTask<bool> TryHandleAsync(
HttpContext httpContext,
Exception exception,
CancellationToken cancellationToken
)
{
switch (exception)
{
case ParsingException:
_logger.LogError(exception, "An exception occurred: {Message}", exception.Message);
var problem = new ProblemDetails
{
Status = ParsingExceptionStatusCode,
Title = "Parsing Exception",
Detail = exception.Message
};
httpContext.Response.StatusCode = problem.Status.Value;
await httpContext.Response.WriteAsJsonAsync(problem, cancellationToken);
return true;
default:
return false;
}
}
}

View File

@ -1,8 +1,23 @@
using DevDisciples.Json.Tools.API;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddControllers();
builder.Services.AddExceptionHandler<GlobalExceptionHandler>();
builder.Services.AddProblemDetails();
builder.Services.AddCors(opts =>
{
opts.AddPolicy("default", opts =>
{
opts
.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod();
});
});
builder.Services.AddSwaggerGen();
var app = builder.Build();
@ -14,31 +29,12 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI();
}
app.UseExceptionHandler();
app.UseHttpsRedirection();
var summaries = new[]
{
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
};
app.UseCors("default");
app.MapGet("/weatherforecast", () =>
{
var forecast = Enumerable.Range(1, 5).Select(index =>
new WeatherForecast
(
DateOnly.FromDateTime(DateTime.Now.AddDays(index)),
Random.Shared.Next(-20, 55),
summaries[Random.Shared.Next(summaries.Length)]
))
.ToArray();
return forecast;
})
.WithName("GetWeatherForecast")
.WithOpenApi();
app.MapControllers();
app.Run();
record WeatherForecast(DateOnly Date, int TemperatureC, string? Summary)
{
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556);
}
app.Run();

View File

@ -14,7 +14,7 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5238",
"applicationUrl": "http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
@ -24,7 +24,7 @@
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "https://localhost:7137;http://localhost:5238",
"applicationUrl": "https://localhost:5001;http://localhost:5000",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

View File

@ -0,0 +1,7 @@
namespace DevDisciples.Json.Tools.API.Requests;
public class Json2CsharpRequest : TransformRequest
{
public string RootClassName { get; set; } = Json2CSharpTranslator.Context.DefaultRootClassName;
public string Namespace { get; set; } = Json2CSharpTranslator.Context.DefaultNamespace;
}

View File

@ -0,0 +1,6 @@
namespace DevDisciples.Json.Tools.API.Requests;
public class PrettifyRequest : TransformRequest
{
public int IndentSize { get; set; } = JsonFormatter.Context.DefaultIndentSize;
}

View File

@ -0,0 +1,6 @@
namespace DevDisciples.Json.Tools.API.Requests;
public abstract class TransformRequest
{
public string Source { get; set; } = string.Empty;
}

View File

@ -0,0 +1,5 @@
namespace DevDisciples.Json.Tools.API.Requests;
public class UglifyRequest : TransformRequest
{
}

View File

@ -0,0 +1,16 @@
# Editor configuration, see https://editorconfig.org
root = true
[*]
charset = utf-8
indent_style = space
indent_size = 2
insert_final_newline = true
trim_trailing_whitespace = true
[*.ts]
quote_type = single
[*.md]
max_line_length = off
trim_trailing_whitespace = false

42
DevDisciples.Json.Tools.App/.gitignore vendored Normal file
View File

@ -0,0 +1,42 @@
# See https://docs.github.com/get-started/getting-started-with-git/ignoring-files for more about ignoring files.
# Compiled output
/dist
/tmp
/out-tsc
/bazel-out
# Node
/node_modules
npm-debug.log
yarn-error.log
# IDEs and editors
.idea/
.project
.classpath
.c9/
*.launch
.settings/
*.sublime-workspace
# Visual Studio Code
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.history/*
# Miscellaneous
/.angular/cache
.sass-cache/
/connect.lock
/coverage
/libpeerconnection.log
testem.log
/typings
# System files
.DS_Store
Thumbs.db

View File

@ -0,0 +1,27 @@
# DevDisciplesJsonToolsApp
This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 18.2.4.
## Development server
Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Code scaffolding
Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Build
Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Running unit tests
Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Running end-to-end tests
Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Further help
To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.dev/tools/cli) page.

View File

@ -0,0 +1,110 @@
{
"$schema": "./node_modules/@angular/cli/lib/config/schema.json",
"version": 1,
"newProjectRoot": "projects",
"projects": {
"DevDisciples.Json.Tools.App": {
"projectType": "application",
"schematics": {
"@schematics/angular:component": {
"style": "scss"
}
},
"root": "",
"sourceRoot": "src",
"prefix": "app",
"architect": {
"build": {
"builder": "@angular-devkit/build-angular:application",
"options": {
"outputPath": "dist/dev-disciples.json.tools.app",
"index": "src/index.html",
"browser": "src/main.ts",
"polyfills": [
"zone.js"
],
"tsConfig": "tsconfig.app.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "public"
},
{ "glob": "**/*",
"input": "node_modules/monaco-editor",
"output": "/assets/monaco/"
}
],
"styles": [
"src/styles.scss"
],
"scripts": []
},
"configurations": {
"production": {
"budgets": [
{
"type": "initial",
"maximumWarning": "500kB",
"maximumError": "1MB"
},
{
"type": "anyComponentStyle",
"maximumWarning": "2kB",
"maximumError": "4kB"
}
],
"outputHashing": "all"
},
"development": {
"optimization": false,
"extractLicenses": false,
"sourceMap": true
}
},
"defaultConfiguration": "production"
},
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"configurations": {
"production": {
"buildTarget": "DevDisciples.Json.Tools.App:build:production"
},
"development": {
"buildTarget": "DevDisciples.Json.Tools.App:build:development"
}
},
"defaultConfiguration": "development"
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n"
},
"test": {
"builder": "@angular-devkit/build-angular:karma",
"options": {
"polyfills": [
"zone.js",
"zone.js/testing"
],
"tsConfig": "tsconfig.spec.json",
"inlineStyleLanguage": "scss",
"assets": [
{
"glob": "**/*",
"input": "public"
},
{ "glob": "**/*",
"input": "node_modules/monaco-editor",
"output": "/assets/monaco/"
}
],
"styles": [
"src/styles.scss"
],
"scripts": []
}
}
}
}
}
}

14458
DevDisciples.Json.Tools.App/package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,42 @@
{
"name": "dev-disciples.json.tools.app",
"version": "0.0.0",
"scripts": {
"ng": "ng",
"start": "ng serve",
"build": "ng build",
"watch": "ng build --watch --configuration development",
"test": "ng test"
},
"private": true,
"dependencies": {
"@angular/animations": "^18.2.0",
"@angular/cdk": "^18.2.4",
"@angular/common": "^18.2.0",
"@angular/compiler": "^18.2.0",
"@angular/core": "^18.2.0",
"@angular/forms": "^18.2.0",
"@angular/material": "^18.2.4",
"@angular/platform-browser": "^18.2.0",
"@angular/platform-browser-dynamic": "^18.2.0",
"@angular/router": "^18.2.0",
"monaco-editor": "^0.50.0",
"ngx-monaco-editor-v2": "^18.1.0",
"rxjs": "~7.8.0",
"tslib": "^2.3.0",
"zone.js": "~0.14.10"
},
"devDependencies": {
"@angular-devkit/build-angular": "^18.2.4",
"@angular/cli": "^18.2.4",
"@angular/compiler-cli": "^18.2.0",
"@types/jasmine": "~5.1.0",
"jasmine-core": "~5.2.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.2.0",
"karma-coverage": "~2.2.0",
"karma-jasmine": "~5.1.0",
"karma-jasmine-html-reporter": "~2.1.0",
"typescript": "~5.5.2"
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 15 KiB

View File

@ -0,0 +1 @@
<app-layout></app-layout>

View File

@ -0,0 +1,23 @@
import { TestBed } from '@angular/core/testing';
import { AppComponent } from './app.component';
describe('AppComponent', () => {
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [AppComponent],
}).compileComponents();
});
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});
it('should render title', () => {
const fixture = TestBed.createComponent(AppComponent);
fixture.detectChanges();
const compiled = fixture.nativeElement as HTMLElement;
expect(compiled.querySelector('h1')?.textContent).toContain('Hello, DevDisciples.Json.Tools.App');
});
});

View File

@ -0,0 +1,13 @@
import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import {LayoutComponent} from "./layout/layout.component";
@Component({
selector: 'app-root',
standalone: true,
imports: [RouterOutlet, LayoutComponent],
templateUrl: './app.component.html',
styleUrl: './app.component.scss'
})
export class AppComponent {
}

View File

@ -0,0 +1,16 @@
import {ApplicationConfig, importProvidersFrom, provideZoneChangeDetection} from '@angular/core';
import { provideRouter } from '@angular/router';
import { routes } from './app.routes';
import { provideAnimationsAsync } from '@angular/platform-browser/animations/async';
import {MonacoEditorModule} from "ngx-monaco-editor-v2";
import {HttpClientModule, provideHttpClient} from "@angular/common/http";
export const appConfig: ApplicationConfig = {
providers: [
provideZoneChangeDetection({ eventCoalescing: true }),
provideRouter(routes), provideAnimationsAsync(),
importProvidersFrom(MonacoEditorModule.forRoot()),
provideHttpClient(),
]
};

View File

@ -0,0 +1,13 @@
import { Routes } from '@angular/router';
import {AppComponent} from "./app.component";
import {HomeComponent} from "./home/home.component";
import {PrettifyComponent} from "./prettify/prettify.component";
import {UglifyComponent} from "./uglify/uglify.component";
import {Json2CsharpComponent} from "./json2csharp/json2-csharp.component";
export const routes: Routes = [
{ path: 'home', component: HomeComponent },
{ path: 'prettify', component: PrettifyComponent },
{ path: 'uglify', component: UglifyComponent },
{ path: 'json2csharp', component: Json2CsharpComponent },
];

View File

@ -0,0 +1 @@
<p>home works!</p>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { HomeComponent } from './home.component';
describe('HomeComponent', () => {
let component: HomeComponent;
let fixture: ComponentFixture<HomeComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [HomeComponent]
})
.compileComponents();
fixture = TestBed.createComponent(HomeComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,12 @@
import { Component } from '@angular/core';
@Component({
selector: 'app-home',
standalone: true,
imports: [],
templateUrl: './home.component.html',
styleUrl: './home.component.scss'
})
export class HomeComponent {
}

View File

@ -0,0 +1,15 @@
<main>
<section id="left">
<h3>Input</h3>
<ngx-monaco-editor (ngModelChange)="handleInputChange($event)"
[options]="inputOptions"
[(ngModel)]="input">
</ngx-monaco-editor>
</section>
<section id="right">
<h3>Output</h3>
<ngx-monaco-editor [options]="outputOptions"
[(ngModel)]="output">
</ngx-monaco-editor>
</section>
</main>

View File

@ -0,0 +1,12 @@
main {
display: flex;
flex-direction: row;
#left {
flex: .5;
}
#right {
flex: .5;
}
}

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { InputOutputComponent } from './input-output.component';
describe('InputOutputComponent', () => {
let component: InputOutputComponent;
let fixture: ComponentFixture<InputOutputComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [InputOutputComponent]
})
.compileComponents();
fixture = TestBed.createComponent(InputOutputComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,25 @@
import {Component, EventEmitter, Input, Output} from '@angular/core';
import {EditorComponent} from "ngx-monaco-editor-v2";
import {FormsModule} from "@angular/forms";
@Component({
selector: 'app-input-output',
standalone: true,
imports: [
EditorComponent,
FormsModule
],
templateUrl: './input-output.component.html',
styleUrl: './input-output.component.scss'
})
export class InputOutputComponent {
@Input() input!: string;
@Input() inputOptions!: any;
@Output() onInputChange = new EventEmitter();
@Input() output!: string;
@Input() outputOptions!: any;
handleInputChange($event: string) {
this.onInputChange.emit($event);
}
}

View File

@ -0,0 +1,16 @@
import { TestBed } from '@angular/core/testing';
import { JsonTransformService } from './json-transform.service';
describe('JsonTransformService', () => {
let service: JsonTransformService;
beforeEach(() => {
TestBed.configureTestingModule({});
service = TestBed.inject(JsonTransformService);
});
it('should be created', () => {
expect(service).toBeTruthy();
});
});

View File

@ -0,0 +1,25 @@
import {Injectable} from '@angular/core';
import {HttpClient, HttpResponse} from "@angular/common/http";
import {Observable} from "rxjs";
@Injectable({
providedIn: 'root'
})
export class JsonTransformService {
private url: string = "https://localhost:5001";
constructor(private http: HttpClient) {
}
public prettify(source: string): Observable<HttpResponse<any>> {
return this.http.post(`${this.url}/api/transform/prettify`, {source: source}, {observe: "response"});
}
public uglify(source: string): Observable<HttpResponse<any>> {
return this.http.post(`${this.url}/api/transform/uglify`, {source: source}, {observe: "response"});
}
public json2csharp(source: string): Observable<HttpResponse<any>> {
return this.http.post(`${this.url}/api/transform/json2csharp`, {source: source}, {observe: "response"});
}
}

View File

@ -0,0 +1,8 @@
<h1>JSON to C#</h1>
<app-input-output [input]="input"
[inputOptions]="inputOptions"
(onInputChange)="handleInputChange($event)"
[output]="output"
[outputOptions]="outputOptions">
</app-input-output>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Json2CsharpComponent } from './json2-csharp.component';
describe('Json2csharpComponent', () => {
let component: Json2CsharpComponent;
let fixture: ComponentFixture<Json2CsharpComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [Json2CsharpComponent]
})
.compileComponents();
fixture = TestBed.createComponent(Json2CsharpComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,55 @@
import {Component, OnInit} from '@angular/core';
import {InputOutputComponent} from "../input-output/input-output.component";
import {JsonTransformService} from "../json-transform.service";
@Component({
selector: 'app-json2csharp',
standalone: true,
imports: [
InputOutputComponent
],
templateUrl: './json2-csharp.component.html',
styleUrl: './json2-csharp.component.scss'
})
export class Json2CsharpComponent implements OnInit {
input: string = JSON.stringify({first_name: "John", last_name: "Doe"}, null, 2);
inputOptions = {theme: 'vs-dark', language: 'json', readOnly: false};
output: string = JSON.stringify({first_name: "John", last_name: "Doe"});
outputOptions = {theme: 'vs-dark', language: 'csharp', readOnly: true};
constructor(private service: JsonTransformService) {
}
ngOnInit(): void {
this.service
.json2csharp(this.input)
.subscribe(response => {
console.log(response);
if (response.status === 200) {
this.output = response.body.result;
} else if (response.status === 499) {
this.output = response.body.detail;
}
});
}
handleInputChange($event: any) {
console.log($event);
this.service
.json2csharp($event)
.subscribe({
next: response => {
console.log(response);
this.output = response.body.result;
},
error: response => {
console.log(response)
if (response.status === 499) {
this.output = response.error.detail;
console.log(response.error.detail);
}
}
});
}
}

View File

@ -0,0 +1,25 @@
<mat-sidenav-container class="sidenav-container">
<mat-sidenav #drawer class="sidenav" mode="side" opened>
<mat-toolbar>Menu</mat-toolbar>
<mat-nav-list>
<mat-list-item routerLink="/home">Home</mat-list-item>
<mat-list-item routerLink="/prettify">Prettify</mat-list-item>
<mat-list-item routerLink="/uglify">Uglify</mat-list-item>
<mat-list-item routerLink="/json2csharp">JSON to C#</mat-list-item>
</mat-nav-list>
</mat-sidenav>
<mat-sidenav-content>
<mat-toolbar color="primary">
<button mat-icon-button (click)="drawer.toggle()">
<mat-icon>menu</mat-icon>
</button>
<span>JSON Transform</span>
</mat-toolbar>
<div class="content">
<!-- Add your dashboard content here -->
<router-outlet></router-outlet>
</div>
</mat-sidenav-content>
</mat-sidenav-container>

View File

@ -0,0 +1,11 @@
.sidenav-container {
height: 100%;
}
.sidenav {
width: 250px;
}
.content {
padding: 16px;
}

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { LayoutComponent } from './layout.component';
describe('LayoutComponent', () => {
let component: LayoutComponent;
let fixture: ComponentFixture<LayoutComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [LayoutComponent]
})
.compileComponents();
fixture = TestBed.createComponent(LayoutComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,27 @@
import { Component } from '@angular/core';
import {MatSidenavContainer, MatSidenavModule} from "@angular/material/sidenav";
import {MatToolbarModule} from "@angular/material/toolbar";
import {MatListItem, MatNavList} from "@angular/material/list";
import {RouterLink, RouterOutlet} from "@angular/router";
import {MatIconButton} from "@angular/material/button";
import {MatIconModule} from "@angular/material/icon";
@Component({
selector: 'app-layout',
standalone: true,
imports: [
MatSidenavContainer,
MatToolbarModule,
MatNavList,
MatListItem,
MatSidenavModule,
RouterLink,
MatIconButton,
MatIconModule,
RouterOutlet
],
templateUrl: './layout.component.html',
styleUrl: './layout.component.scss'
})
export class LayoutComponent {
}

View File

@ -0,0 +1,8 @@
<h1>JSON Prettify</h1>
<app-input-output [input]="input"
[inputOptions]="inputOptions"
(onInputChange)="handleInputChange($event)"
[output]="output"
[outputOptions]="outputOptions">
</app-input-output>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { PrettifyComponent } from './prettify.component';
describe('PrettifyComponent', () => {
let component: PrettifyComponent;
let fixture: ComponentFixture<PrettifyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [PrettifyComponent]
})
.compileComponents();
fixture = TestBed.createComponent(PrettifyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,46 @@
import {Component} from '@angular/core';
import {EditorComponent} from "ngx-monaco-editor-v2";
import {FormsModule} from "@angular/forms";
import {InputOutputComponent} from "../input-output/input-output.component";
import {JsonTransformService} from "../json-transform.service";
@Component({
selector: 'app-prettify',
standalone: true,
imports: [
EditorComponent,
FormsModule,
InputOutputComponent
],
templateUrl: './prettify.component.html',
styleUrl: './prettify.component.scss'
})
export class PrettifyComponent {
input: string = JSON.stringify({first_name: "John", last_name: "Doe"});
inputOptions = {theme: 'vs-dark', language: 'json', readOnly: false};
output: string = JSON.stringify({first_name: "John", last_name: "Doe"}, null, 2);
outputOptions = {theme: 'vs-dark', language: 'json', readOnly: true};
error: string = "";
constructor(private service: JsonTransformService) {
}
handleInputChange($event: any) {
console.log($event);
this.service
.prettify($event)
.subscribe({
next: response => {
console.log(response);
this.output = response.body.result;
},
error: response => {
console.log(response)
if (response.status === 499) {
this.output = response.error.detail;
console.log(response.error.detail);
}
}
});
}
}

View File

@ -0,0 +1,8 @@
<h1>JSON Uglify</h1>
<app-input-output [input]="input"
[inputOptions]="inputOptions"
(onInputChange)="handleInputChange($event)"
[output]="output"
[outputOptions]="outputOptions">
</app-input-output>

View File

@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { UglifyComponent } from './uglify.component';
describe('UglifyComponent', () => {
let component: UglifyComponent;
let fixture: ComponentFixture<UglifyComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [UglifyComponent]
})
.compileComponents();
fixture = TestBed.createComponent(UglifyComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should create', () => {
expect(component).toBeTruthy();
});
});

View File

@ -0,0 +1,41 @@
import {Component} from '@angular/core';
import {JsonTransformService} from "../json-transform.service";
import {InputOutputComponent} from "../input-output/input-output.component";
@Component({
selector: 'app-uglify',
standalone: true,
imports: [
InputOutputComponent
],
templateUrl: './uglify.component.html',
styleUrl: './uglify.component.scss'
})
export class UglifyComponent {
input: string = JSON.stringify({first_name: "John", last_name: "Doe"}, null, 2);
inputOptions = {theme: 'vs-dark', language: 'json', readOnly: false};
output: string = JSON.stringify({first_name: "John", last_name: "Doe"});
outputOptions = {theme: 'vs-dark', language: 'json', readOnly: true};
constructor(private service: JsonTransformService) {
}
handleInputChange($event: any) {
console.log($event);
this.service
.uglify($event)
.subscribe({
next: response => {
console.log(response);
this.output = response.body.result;
},
error: response => {
console.log(response)
if (response.status === 499) {
this.output = response.error.detail;
console.log(response.error.detail);
}
}
});
}
}

View File

@ -0,0 +1,15 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>DevDisciplesJsonToolsApp</title>
<base href="/">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="icon" type="image/x-icon" href="favicon.ico">
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;500&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body class="mat-typography">
<app-root></app-root>
</body>
</html>

View File

@ -0,0 +1,6 @@
import { bootstrapApplication } from '@angular/platform-browser';
import { appConfig } from './app/app.config';
import { AppComponent } from './app/app.component';
bootstrapApplication(AppComponent, appConfig)
.catch((err) => console.error(err));

View File

@ -0,0 +1,40 @@
// Custom Theming for Angular Material
// For more information: https://material.angular.io/guide/theming
@use '@angular/material' as mat;
// Plus imports for other components in your app.
// Include the common styles for Angular Material. We include this here so that you only
// have to load a single css file for Angular Material in your app.
// Be sure that you only ever include this mixin once!
@include mat.core();
// Define the theme object.
$DevDisciples-Json-Tools-App-theme: mat.define-theme((
color: (
theme-type: light,
primary: mat.$azure-palette,
tertiary: mat.$blue-palette,
),
density: (
scale: 0,
)
));
// Include theme styles for core and each component used in your app.
// Alternatively, you can import and @include the theme mixins for each component
// that you are using.
:root {
@include mat.all-component-themes($DevDisciples-Json-Tools-App-theme);
}
// Comment out the line below if you want to use the pre-defined typography utility classes.
// For more information: https://material.angular.io/guide/typography#using-typography-styles-in-your-application.
// @include mat.typography-hierarchy($DevDisciples.Json.Tools.App-theme);
// Comment out the line below if you want to use the deprecated `color` inputs.
// @include mat.color-variants-backwards-compatibility($DevDisciples.Json.Tools.App-theme);
/* You can add global styles to this file, and also import other style files */
html, body { height: 100%; }
body { margin: 0; font-family: Roboto, "Helvetica Neue", sans-serif; }

View File

@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/app",
"types": []
},
"files": [
"src/main.ts"
],
"include": [
"src/**/*.d.ts"
]
}

View File

@ -0,0 +1,33 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"compileOnSave": false,
"compilerOptions": {
"outDir": "./dist/out-tsc",
"strict": true,
"noImplicitOverride": true,
"noPropertyAccessFromIndexSignature": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"skipLibCheck": true,
"isolatedModules": true,
"esModuleInterop": true,
"sourceMap": true,
"declaration": false,
"experimentalDecorators": true,
"moduleResolution": "bundler",
"importHelpers": true,
"target": "ES2022",
"module": "ES2022",
"lib": [
"ES2022",
"dom"
]
},
"angularCompilerOptions": {
"enableI18nLegacyMessageIdFormat": false,
"strictInjectionParameters": true,
"strictInputAccessModifiers": true,
"strictTemplates": true
}
}

View File

@ -0,0 +1,15 @@
/* To learn more about Typescript configuration file: https://www.typescriptlang.org/docs/handbook/tsconfig-json.html. */
/* To learn more about Angular compiler options: https://angular.dev/reference/configs/angular-compiler-options. */
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./out-tsc/spec",
"types": [
"jasmine"
]
},
"include": [
"src/**/*.spec.ts",
"src/**/*.d.ts"
]
}

View File

@ -20,8 +20,7 @@ public static partial class Json2CSharpTranslator
context.Classes.Add(SquashObjects(name, array.Elements, args));
type = context.Classes.Last().Name;
}
if (array.Elements.All(e => e is JsonString es && DateTime.TryParse(es.Value, out _)))
else if (array.Elements.All(e => e is JsonString es && DateTime.TryParse(es.Value, out _)))
{
type = "DateTime";
}

View File

@ -6,11 +6,13 @@ public static partial class JsonFormatter
{
public class Context
{
public const int DefaultIndentSize = 2;
protected int Depth { get; set; } = 0;
public StringBuilder Builder { get; set; } = new();
public bool Beautify { get; set; } = false;
public string Indent => new(' ', Depth);
public int IndentSize { get; set; } = 2;
public int IndentSize { get; set; } = DefaultIndentSize;
public string NewLine => Beautify ? "\n" : "";
public string Space => Beautify ? " " : "";