├── .editorconfig ├── .gitignore ├── LICENSE ├── README.md ├── angular.json ├── browserslist ├── debug.log ├── demo.gif ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.json ├── karma.conf.js ├── ngsw-config.json ├── package-lock.json ├── package.json ├── src ├── app │ ├── app-routing.module.ts │ ├── app.component.html │ ├── app.component.scss │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── json2serializers │ │ ├── case.enum.ts │ │ ├── indent-type.enum.ts │ │ ├── parser.spec.ts │ │ └── parser.ts │ ├── nodeviews │ │ ├── CodeMirror.ts │ │ └── index.ts │ ├── plugins │ │ ├── index.ts │ │ ├── input-rules.ts │ │ └── menu │ │ │ └── codemirror.ts │ └── schema.ts ├── assets │ ├── .gitkeep │ └── icons │ │ ├── icon-128x128.png │ │ ├── icon-144x144.png │ │ ├── icon-152x152.png │ │ ├── icon-192x192.png │ │ ├── icon-384x384.png │ │ ├── icon-512x512.png │ │ ├── icon-72x72.png │ │ └── icon-96x96.png ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── manifest.webmanifest ├── polyfills.ts ├── styles.scss └── test.ts ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events*.json 15 | speed-measure-plugin*.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Kutay Aslan 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Json2drfserializer 2 | 3 | Have you ever felt lazy to create drf serializers for handling a complex JSON data? If you do, this app is for you. 4 | 5 | ![](demo.gif) 6 | 7 | ## Development server 8 | 9 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 10 | 11 | ## Running tests 12 | 13 | Run `ng test` to execute the tests. 14 | 15 | ## Contributing 16 | Pull requests are welcome. For major changes, please open an issue first to discuss what you would like to change. 17 | 18 | ## License 19 | [MIT](https://choosealicense.com/licenses/mit/) 20 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "json2drfserializer": { 7 | "projectType": "application", 8 | "schematics": { 9 | "@schematics/angular:component": { 10 | "style": "scss" 11 | } 12 | }, 13 | "root": "", 14 | "sourceRoot": "src", 15 | "prefix": "app", 16 | "architect": { 17 | "build": { 18 | "builder": "@angular-devkit/build-angular:browser", 19 | "options": { 20 | "outputPath": "dist/json2drfserializer", 21 | "index": "src/index.html", 22 | "main": "src/main.ts", 23 | "polyfills": "src/polyfills.ts", 24 | "tsConfig": "tsconfig.app.json", 25 | "aot": true, 26 | "assets": [ 27 | "src/favicon.ico", 28 | "src/assets", 29 | "src/manifest.webmanifest" 30 | ], 31 | "styles": [ 32 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 33 | "src/styles.scss" 34 | ], 35 | "scripts": [] 36 | }, 37 | "configurations": { 38 | "production": { 39 | "fileReplacements": [ 40 | { 41 | "replace": "src/environments/environment.ts", 42 | "with": "src/environments/environment.prod.ts" 43 | } 44 | ], 45 | "optimization": true, 46 | "outputHashing": "all", 47 | "sourceMap": false, 48 | "extractCss": true, 49 | "namedChunks": false, 50 | "extractLicenses": true, 51 | "vendorChunk": false, 52 | "buildOptimizer": true, 53 | "budgets": [ 54 | { 55 | "type": "initial", 56 | "maximumWarning": "2mb", 57 | "maximumError": "5mb" 58 | }, 59 | { 60 | "type": "anyComponentStyle", 61 | "maximumWarning": "6kb", 62 | "maximumError": "10kb" 63 | } 64 | ], 65 | "serviceWorker": true, 66 | "ngswConfigPath": "ngsw-config.json" 67 | } 68 | } 69 | }, 70 | "serve": { 71 | "builder": "@angular-devkit/build-angular:dev-server", 72 | "options": { 73 | "browserTarget": "json2drfserializer:build" 74 | }, 75 | "configurations": { 76 | "production": { 77 | "browserTarget": "json2drfserializer:build:production" 78 | } 79 | } 80 | }, 81 | "extract-i18n": { 82 | "builder": "@angular-devkit/build-angular:extract-i18n", 83 | "options": { 84 | "browserTarget": "json2drfserializer:build" 85 | } 86 | }, 87 | "test": { 88 | "builder": "@angular-devkit/build-angular:karma", 89 | "options": { 90 | "main": "src/test.ts", 91 | "polyfills": "src/polyfills.ts", 92 | "tsConfig": "tsconfig.spec.json", 93 | "karmaConfig": "karma.conf.js", 94 | "assets": [ 95 | "src/favicon.ico", 96 | "src/assets", 97 | "src/manifest.webmanifest" 98 | ], 99 | "styles": [ 100 | "./node_modules/@angular/material/prebuilt-themes/indigo-pink.css", 101 | "src/styles.scss" 102 | ], 103 | "scripts": [] 104 | } 105 | }, 106 | "lint": { 107 | "builder": "@angular-devkit/build-angular:tslint", 108 | "options": { 109 | "tsConfig": [ 110 | "tsconfig.app.json", 111 | "tsconfig.spec.json", 112 | "e2e/tsconfig.json" 113 | ], 114 | "exclude": [ 115 | "**/node_modules/**" 116 | ] 117 | } 118 | }, 119 | "e2e": { 120 | "builder": "@angular-devkit/build-angular:protractor", 121 | "options": { 122 | "protractorConfig": "e2e/protractor.conf.js", 123 | "devServerTarget": "json2drfserializer:serve" 124 | }, 125 | "configurations": { 126 | "production": { 127 | "devServerTarget": "json2drfserializer:serve:production" 128 | } 129 | } 130 | }, 131 | "deploy": { 132 | "builder": "angular-cli-ghpages:deploy", 133 | "options": {} 134 | } 135 | } 136 | } 137 | }, 138 | "defaultProject": "json2drfserializer" 139 | } -------------------------------------------------------------------------------- /browserslist: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # You can see what browsers were selected by your queries by running: 6 | # npx browserslist 7 | 8 | > 0.5% 9 | last 2 versions 10 | Firefox ESR 11 | not dead 12 | not IE 9-11 # For IE 9-11 support, remove 'not'. -------------------------------------------------------------------------------- /debug.log: -------------------------------------------------------------------------------- 1 | [1128/174938.057:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 2 | [1129/093304.889:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 3 | [1129/100159.652:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 4 | [1129/115818.375:ERROR:directory_reader_win.cc(43)] FindFirstFile: The system cannot find the path specified. (0x3) 5 | -------------------------------------------------------------------------------- /demo.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/demo.gif -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | browserName: 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 31 | } 32 | }; -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('json2drfserializer app is running!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo(): Promise { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText(): Promise { 9 | return element(by.css('app-root .content span')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular-devkit/build-angular'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, './coverage/json2drfserializer'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /ngsw-config.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/service-worker/config/schema.json", 3 | "index": "/index.html", 4 | "assetGroups": [ 5 | { 6 | "name": "app", 7 | "installMode": "prefetch", 8 | "resources": { 9 | "files": [ 10 | "/favicon.ico", 11 | "/index.html", 12 | "/manifest.webmanifest", 13 | "/*.css", 14 | "/*.js" 15 | ] 16 | } 17 | }, { 18 | "name": "assets", 19 | "installMode": "lazy", 20 | "updateMode": "prefetch", 21 | "resources": { 22 | "files": [ 23 | "/assets/**", 24 | "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)" 25 | ] 26 | } 27 | } 28 | ] 29 | } 30 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "json2drfserializer", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~9.1.9", 15 | "@angular/cdk": "^9.2.4", 16 | "@angular/common": "~9.1.9", 17 | "@angular/compiler": "~9.1.9", 18 | "@angular/core": "~9.1.9", 19 | "@angular/forms": "~9.1.9", 20 | "@angular/material": "^9.2.4", 21 | "@angular/platform-browser": "~9.1.9", 22 | "@angular/platform-browser-dynamic": "~9.1.9", 23 | "@angular/router": "~9.1.9", 24 | "@angular/service-worker": "~9.1.9", 25 | "@types/prosemirror-commands": "^1.0.1", 26 | "@types/prosemirror-history": "^1.0.1", 27 | "@types/prosemirror-inputrules": "^1.0.2", 28 | "@types/prosemirror-keymap": "^1.0.2", 29 | "@types/prosemirror-model": "^1.7.2", 30 | "@types/prosemirror-schema-list": "^1.0.1", 31 | "@types/prosemirror-state": "^1.2.4", 32 | "@types/prosemirror-view": "^1.11.4", 33 | "bootstrap": "^4.5.0", 34 | "codemirror": "^5.54.0", 35 | "http-server": "^0.12.3", 36 | "lodash": "^4.17.20", 37 | "ngx-editor": "^5.0.0-alpha.7", 38 | "prosemirror-commands": "^1.1.4", 39 | "prosemirror-history": "^1.1.3", 40 | "prosemirror-inputrules": "^1.1.2", 41 | "prosemirror-keymap": "^1.1.4", 42 | "prosemirror-model": "^1.10.0", 43 | "prosemirror-schema-list": "^1.1.2", 44 | "prosemirror-state": "^1.3.3", 45 | "prosemirror-view": "^1.14.13", 46 | "rxjs": "~6.5.4", 47 | "tslib": "^1.10.0", 48 | "zone.js": "~0.10.2" 49 | }, 50 | "devDependencies": { 51 | "@angular-devkit/build-angular": "~0.901.7", 52 | "@angular/cli": "~9.1.7", 53 | "@angular/compiler-cli": "~9.1.9", 54 | "@types/jasmine": "~3.5.0", 55 | "@types/jasminewd2": "~2.0.3", 56 | "@types/node": "^12.11.1", 57 | "angular-cli-ghpages": "^1.0.0-rc.1", 58 | "codelyzer": "^5.1.2", 59 | "jasmine-core": "~3.5.0", 60 | "jasmine-spec-reporter": "~4.2.1", 61 | "karma": "~5.0.0", 62 | "karma-chrome-launcher": "~3.1.0", 63 | "karma-coverage-istanbul-reporter": "~2.1.0", 64 | "karma-jasmine": "~3.0.1", 65 | "karma-jasmine-html-reporter": "^1.4.2", 66 | "protractor": "~7.0.0", 67 | "ts-node": "~8.3.0", 68 | "tslint": "~6.1.0", 69 | "typescript": "~3.8.3" 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | 4 | 5 | const routes: Routes = []; 6 | 7 | @NgModule({ 8 | imports: [RouterModule.forRoot(routes)], 9 | exports: [RouterModule] 10 | }) 11 | export class AppRoutingModule { } 12 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | Generate DRF serializers from JSON 3 | 4 | 7 | 10 | 11 |
12 |
13 |
14 | 16 |
17 |
18 |
19 | 20 | Indent Type 21 | 22 | {{indentType.label}} 23 | 24 | 25 | 26 | Indent Size 27 | 28 | 29 | {{option}} 30 | 31 | 32 | 33 |
34 | 35 | JSON 36 | 38 | Copy your JSON here 39 | 40 |
41 |
42 |
43 | 44 | Name of the root serializer 45 | 46 | 47 | 48 | Follow "snake_case" convention for attributes 49 | 50 |
51 | 52 |
53 |
54 |
-------------------------------------------------------------------------------- /src/app/app.component.scss: -------------------------------------------------------------------------------- 1 | .spacer { 2 | flex: 1 1 auto; 3 | } 4 | ::ng-deep.NgxEditor{ 5 | height: 100%; 6 | .ProseMirror{ 7 | height: 100%; 8 | .CodeMirror { 9 | height: 95%; 10 | } 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | }); 7 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from '@angular/core'; 2 | import { JsonToSerializerParser } from './json2serializers/parser'; 3 | import { CaseEnum } from './json2serializers/case.enum'; 4 | import { IndentTypeEnum } from './json2serializers/indent-type.enum'; 5 | import { MatSelectChange } from '@angular/material/select'; 6 | import { SwUpdate } from '@angular/service-worker'; 7 | import { Subscription } from 'rxjs'; 8 | 9 | interface IndentTypeConfigs { 10 | key: IndentTypeEnum; 11 | label: string; 12 | options: number[]; 13 | } 14 | 15 | 16 | @Component({ 17 | selector: 'app-root', 18 | templateUrl: './app.component.html', 19 | styleUrls: ['./app.component.scss'] 20 | }) 21 | export class AppComponent implements OnInit, OnDestroy { 22 | jsonData: any = '{\n "name":"Ashlee Buckner",\n "age":27,\n "eyeColor":"green",\n "totalProfit":45.50,\n "parent":{\n "isActive":true,\n "name":"Kathleen Poole",\n "age":36,\n "eyeColor":"blue",\n "parent":{\n "name":"Tillman Ryan"\n }\n },\n "friends":[\n {"id":0,"name":"Gaines Mccall"},\n {"id":1,"name":"Gabrielle Reid"},\n {"id":2,"name":"Mcguire Macias"}\n ]\n}' 23 | serializer: any; 24 | 25 | parser: JsonToSerializerParser = new JsonToSerializerParser() 26 | isSnakeCasePreferred: boolean = true 27 | nameOfTheRootSerializer: string = "Root" 28 | 29 | indentTypes: IndentTypeConfigs[] = [ 30 | { 31 | key: IndentTypeEnum.SPACES, 32 | label: "Spaces", 33 | options: [ 34 | 1, 35 | 2, 36 | 3, 37 | 4, 38 | 5, 39 | 6, 40 | 7, 41 | 8 42 | ] 43 | }, 44 | { 45 | key: IndentTypeEnum.TABS, 46 | label: "Tabs", 47 | options: [ 48 | 1, 49 | 2 50 | ] 51 | } 52 | ] 53 | selectedIndentType: IndentTypeConfigs = this.indentTypes[1]; 54 | selectedIndentSize: number = this.selectedIndentType.options[0]; 55 | 56 | subscription: Subscription; 57 | 58 | constructor(private readonly updates: SwUpdate) { 59 | this.subscription = this.updates.available.subscribe(event => { 60 | this.updates.activateUpdate().then(() => document.location.reload()); 61 | }); 62 | } 63 | 64 | ngOnInit(): void { 65 | this.initSerializer() 66 | } 67 | 68 | ngOnDestroy(): void { 69 | this.subscription.unsubscribe(); 70 | } 71 | 72 | initSerializer() { 73 | let jsonParsed 74 | try { 75 | jsonParsed = JSON.parse(this.jsonData) 76 | } catch { 77 | alert("JSON is not valid") 78 | return 79 | } 80 | this.serializer = { 81 | type: "doc", 82 | content: [ 83 | { 84 | type: "code_block", 85 | content: [ 86 | { 87 | type: "text", 88 | text: this.parser.parse( 89 | jsonParsed, 90 | { 91 | preferredCaseForFields: (this.isSnakeCasePreferred ? CaseEnum.SNAKE_CASE : CaseEnum.NO_CHANGE), 92 | nameOfTheRootSerializer: this.nameOfTheRootSerializer, 93 | selectedIndentConfigs: { 94 | selectedIndentType: this.selectedIndentType.key, 95 | selectedIndentSize: this.selectedIndentSize 96 | } 97 | } 98 | ) 99 | } 100 | ] 101 | }, 102 | ] 103 | }; 104 | } 105 | 106 | setDefaultIdentSize(selectChange: MatSelectChange) { 107 | let selectedIdentTypeConfig: IndentTypeConfigs = selectChange.value 108 | switch (selectedIdentTypeConfig.key) { 109 | case IndentTypeEnum.SPACES: 110 | this.selectedIndentSize = selectedIdentTypeConfig.options[3] 111 | break; 112 | case IndentTypeEnum.TABS: 113 | this.selectedIndentSize = selectedIdentTypeConfig.options[0] 114 | break; 115 | } 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { FormsModule } from '@angular/forms'; 3 | import { MatButtonModule } from '@angular/material/button'; 4 | import { MatFormFieldModule } from '@angular/material/form-field'; 5 | import { MatIconModule } from '@angular/material/icon'; 6 | import { MatInputModule } from '@angular/material/input'; 7 | import { MatToolbarModule } from '@angular/material/toolbar'; 8 | import { MatCheckboxModule } from '@angular/material/checkbox'; 9 | import { MatCardModule } from '@angular/material/card'; 10 | import { BrowserModule } from '@angular/platform-browser'; 11 | import { MatSelectModule } from '@angular/material/select'; 12 | import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; 13 | import { ServiceWorkerModule } from '@angular/service-worker'; 14 | import { NgxEditorModule } from 'ngx-editor'; 15 | import { environment } from '../environments/environment'; 16 | import { AppRoutingModule } from './app-routing.module'; 17 | import { AppComponent } from './app.component'; 18 | import nodeviews from "./nodeviews"; 19 | import plugins from "./plugins"; 20 | import schema from "./schema"; 21 | 22 | @NgModule({ 23 | declarations: [ 24 | AppComponent 25 | ], 26 | imports: [ 27 | BrowserModule, 28 | AppRoutingModule, 29 | ServiceWorkerModule.register('ngsw-worker.js', { enabled: environment.production }), 30 | BrowserAnimationsModule, 31 | MatFormFieldModule, 32 | MatInputModule, 33 | MatToolbarModule, 34 | MatButtonModule, 35 | MatIconModule, 36 | MatSelectModule, 37 | MatCheckboxModule, 38 | MatCardModule, 39 | FormsModule, 40 | NgxEditorModule.forRoot({ 41 | schema, 42 | plugins, 43 | nodeViews: nodeviews 44 | })], 45 | providers: [], 46 | bootstrap: [AppComponent] 47 | }) 48 | export class AppModule { } 49 | -------------------------------------------------------------------------------- /src/app/json2serializers/case.enum.ts: -------------------------------------------------------------------------------- 1 | export enum CaseEnum { 2 | SNAKE_CASE = "snake_case", 3 | NO_CHANGE ="noChange" 4 | } 5 | -------------------------------------------------------------------------------- /src/app/json2serializers/indent-type.enum.ts: -------------------------------------------------------------------------------- 1 | export enum IndentTypeEnum { 2 | SPACES = "spaces", 3 | TABS = "tabs" 4 | } -------------------------------------------------------------------------------- /src/app/json2serializers/parser.spec.ts: -------------------------------------------------------------------------------- 1 | import { CaseEnum } from './case.enum' 2 | import { IndentTypeEnum } from './indent-type.enum' 3 | import { JsonToSerializerParser, ParsingConfigs } from "./parser" 4 | 5 | const parsingConfigs: ParsingConfigs = { 6 | preferredCaseForFields: CaseEnum.SNAKE_CASE, 7 | nameOfTheRootSerializer: "Example", 8 | selectedIndentConfigs: { 9 | selectedIndentType: IndentTypeEnum.SPACES, 10 | selectedIndentSize: 3 11 | } 12 | } 13 | 14 | describe('JsonToSerializerParser', () => { 15 | let parser: JsonToSerializerParser 16 | 17 | beforeAll(() => { 18 | parser = new JsonToSerializerParser() 19 | }) 20 | 21 | it('should be able to parse a simple json to drf serializer', () => { 22 | expect( 23 | parser.parse( 24 | { 25 | name: 'Kutay', 26 | isLazy: true, 27 | age: 80, 28 | }, 29 | parsingConfigs 30 | ) 31 | ).toBe( 32 | "from rest_framework import serializers\n\n" + 33 | "class ExampleSerializer(serializers.Serializer):\n" + 34 | " name = serializers.CharField()\n" + 35 | " is_lazy = serializers.BooleanField()\n" + 36 | " age = serializers.IntegerField()\n" 37 | ) 38 | }) 39 | 40 | it('should be able to parse a json with array to drf serializer', () => { 41 | expect( 42 | parser.parse( 43 | { 44 | scopeIds: [1, 2, 5, 9], 45 | }, 46 | parsingConfigs 47 | ) 48 | ).toBe( 49 | "from rest_framework import serializers\n\n" + 50 | "class ExampleSerializer(serializers.Serializer):\n" + 51 | " scope_ids = serializers.IntegerField(many=True)\n" 52 | ) 53 | }) 54 | 55 | it('should be able to parse a nested json to drf serializer', () => { 56 | expect( 57 | parser.parse( 58 | { 59 | name: "Kutay", 60 | age: 80, 61 | contactInfo: { 62 | github: "https://github.com/titans55", 63 | address: "World" 64 | }, 65 | }, 66 | parsingConfigs 67 | ) 68 | ).toBe( 69 | "from rest_framework import serializers\n\n" + 70 | "class ContactInfoSerializer(serializers.Serializer):\n" + 71 | " github = serializers.CharField()\n" + 72 | " address = serializers.CharField()\n\n" + 73 | "class ExampleSerializer(serializers.Serializer):\n" + 74 | " name = serializers.CharField()\n" + 75 | " age = serializers.IntegerField()\n" + 76 | " contact_info = ContactInfoSerializer()\n" 77 | ) 78 | }) 79 | 80 | 81 | it('should be able to parse a complex json to drf serializer', () => { 82 | expect( 83 | parser.parse( 84 | { 85 | name: "Ashlee Buckner", 86 | age: 27, 87 | eyeColor: "green", 88 | friends: [ 89 | { 90 | id: 0, 91 | name: "Gaines Mccall" 92 | }, 93 | { 94 | id: 1, 95 | name: "Gabrielle Reid" 96 | }, 97 | { 98 | id: 2, 99 | name: "Mcguire Macias" 100 | } 101 | ], 102 | parent: { 103 | name: "Kathleen Poole", 104 | isActive: true, 105 | age: 36, 106 | eyeColor: "blue", 107 | parent: { 108 | name: "Tillman Ryan", 109 | parent: { 110 | age: 32 111 | } 112 | } 113 | }, 114 | }, 115 | parsingConfigs 116 | ) 117 | ).toBe( 118 | "from rest_framework import serializers\n\n" + 119 | "class Parent2Serializer(serializers.Serializer):\n" + 120 | " age = serializers.IntegerField()\n\n" + 121 | "class Parent1Serializer(serializers.Serializer):\n" + 122 | " name = serializers.CharField()\n" + 123 | " parent = Parent2Serializer()\n\n" + 124 | "class ParentSerializer(serializers.Serializer):\n" + 125 | " name = serializers.CharField()\n" + 126 | " is_active = serializers.BooleanField()\n" + 127 | " age = serializers.IntegerField()\n" + 128 | " eye_color = serializers.CharField()\n" + 129 | " parent = Parent1Serializer()\n\n" + 130 | "class FriendsSerializer(serializers.Serializer):\n" + 131 | " id = serializers.IntegerField()\n" + 132 | " name = serializers.CharField()\n\n" + 133 | "class ExampleSerializer(serializers.Serializer):\n" + 134 | " name = serializers.CharField()\n" + 135 | " age = serializers.IntegerField()\n" + 136 | " eye_color = serializers.CharField()\n" + 137 | " friends = FriendsSerializer(many=True)\n" + 138 | " parent = ParentSerializer()\n" 139 | ) 140 | }) 141 | }) -------------------------------------------------------------------------------- /src/app/json2serializers/parser.ts: -------------------------------------------------------------------------------- 1 | import * as _ from 'lodash'; 2 | import { CaseEnum } from './case.enum'; 3 | import { IndentTypeEnum } from './indent-type.enum'; 4 | 5 | const PropertyPlaceholder = '{PP}' 6 | const SerializerClassPlaceholder = '{SCP}' 7 | 8 | export interface ParsingConfigs { 9 | preferredCaseForFields: CaseEnum 10 | nameOfTheRootSerializer: string 11 | selectedIndentConfigs: { 12 | selectedIndentType: IndentTypeEnum, 13 | selectedIndentSize: number 14 | } 15 | } 16 | 17 | export class JsonToSerializerParser { 18 | serializeNames: Array = [] 19 | preferredCaseForFields: CaseEnum 20 | nameOfTheRootSerializer: string 21 | indent: string 22 | 23 | constructor() { 24 | this.setIntentWithChar(IndentTypeEnum.SPACES, 4) 25 | } 26 | 27 | parse(obj: any, configs: ParsingConfigs) { 28 | this.setIntentWithChar( 29 | configs.selectedIndentConfigs.selectedIndentType, 30 | configs.selectedIndentConfigs.selectedIndentSize 31 | ) 32 | this.serializeNames = [] 33 | this.preferredCaseForFields = configs.preferredCaseForFields 34 | this.nameOfTheRootSerializer = configs.nameOfTheRootSerializer 35 | let code = this._parse(obj) 36 | code = code.replace(SerializerClassPlaceholder, "") 37 | return "from rest_framework import serializers\n\n" + code 38 | } 39 | 40 | private setIntentWithChar(indentType: IndentTypeEnum, numberOfIndentChars: number) { 41 | let indentChar: string = this.getIndentChar(indentType) 42 | let indentStr: string = "" 43 | for (let i = 0; i < numberOfIndentChars; i++) { 44 | indentStr = indentStr + indentChar 45 | } 46 | this.indent = indentStr 47 | } 48 | 49 | private isObject(obj: any): boolean { 50 | return typeof obj === 'object' && obj !== null && !Array.isArray(obj) 51 | } 52 | 53 | private _parse(obj: any, code?: string, serializerName?: string): string { 54 | if (!serializerName) { 55 | serializerName = this.nameOfTheRootSerializer 56 | } 57 | if (this.isObject(obj)) { 58 | if (!code) { 59 | code = 60 | `${SerializerClassPlaceholder}` + 61 | `class ${serializerName}Serializer(serializers.Serializer):\n` 62 | } 63 | for (let [key, value] of Object.entries(obj)) { 64 | if (value == null) { 65 | continue 66 | } 67 | if (this.isObject(value)) { 68 | let codeAndSerializerName = this.setSerializerClass(key, value, code) 69 | code = codeAndSerializerName.code 70 | serializerName = codeAndSerializerName.serializerName 71 | } else if (Array.isArray(value)) { 72 | if (!value.length) { 73 | continue 74 | } 75 | if (this.isObject(value[0])) { 76 | let codeAndSerializerName = this.setSerializerClass(key, value[0], code, 'many=True') 77 | code = codeAndSerializerName.code 78 | serializerName = codeAndSerializerName.serializerName 79 | } else { 80 | let serializerField: string = format(this._parse(value[0], code), 'many=True') 81 | code += `${this.indent}${this.changeCase(key)} = ${serializerField}\n` 82 | } 83 | } else { 84 | let serializerField: string = format(this._parse(value, code)) 85 | code += `${this.indent}${this.changeCase(key)} = ${serializerField}\n` 86 | } 87 | } 88 | 89 | } else { 90 | if (typeof obj === 'string' || obj instanceof String) { 91 | return `serializers.CharField(${PropertyPlaceholder})` 92 | } 93 | if (typeof obj === "boolean") { 94 | return `serializers.BooleanField(${PropertyPlaceholder})` 95 | } 96 | if (Number.isInteger(obj)) { 97 | return `serializers.IntegerField(${PropertyPlaceholder})` 98 | } 99 | if (!isNaN(obj) && obj.toString().indexOf('.') != -1) { 100 | return `serializers.DecimalField(${PropertyPlaceholder})` 101 | } 102 | return 'serializers.NoneField()' 103 | } 104 | 105 | return code 106 | } 107 | 108 | private getIndentChar(indentType: IndentTypeEnum): string { 109 | let indentChar: string; 110 | switch (indentType) { 111 | case IndentTypeEnum.SPACES: 112 | indentChar = " " 113 | break; 114 | case IndentTypeEnum.TABS: 115 | indentChar = "\t" 116 | break; 117 | } 118 | return indentChar 119 | } 120 | 121 | private setSerializerClass(key: string, value: any, code: string, property: string = '') { 122 | if (this.isObject(value) && Object.keys(value).length == 0) { 123 | return { 124 | code: code, 125 | serializeName: null 126 | } 127 | } 128 | let serializerName = this.buildSerializerName(key); 129 | this.serializeNames.push(serializerName) 130 | code += `${this.indent}${this.changeCase(key)} = ${serializerName}Serializer(${property})\n` 131 | let subObjClass = this._parse(value, null, serializerName) + "\n" 132 | code = code.replace(SerializerClassPlaceholder, subObjClass) 133 | return { 134 | code: code, 135 | serializerName: serializerName 136 | } 137 | } 138 | 139 | private buildSerializerName(key: string): string { 140 | let serializerName: string = _.startCase(key).replace(" ", ""); 141 | 142 | while (this.serializeNames.includes(serializerName)) { 143 | let lastCharOfSerializerName = serializerName.slice(-1) 144 | if (isNaN(lastCharOfSerializerName)) { 145 | serializerName += "1" 146 | } else { 147 | let number: number = parseInt(lastCharOfSerializerName) 148 | number += 1 149 | if (number < 10) { 150 | serializerName = serializerName.slice(0, -1) + number.toString() 151 | } else { 152 | serializerName += "0" 153 | } 154 | } 155 | } 156 | 157 | return serializerName.replace(" ", "") 158 | } 159 | 160 | private changeCase(value: string) { 161 | switch (this.preferredCaseForFields) { 162 | case CaseEnum.NO_CHANGE: 163 | break; 164 | case CaseEnum.SNAKE_CASE: 165 | value = _.snakeCase(value) 166 | break; 167 | } 168 | return value.replace(" ", "") 169 | } 170 | } 171 | 172 | 173 | 174 | function format(serializerField: string, property: string = "") { 175 | return serializerField.replace(PropertyPlaceholder, property) 176 | } -------------------------------------------------------------------------------- /src/app/nodeviews/CodeMirror.ts: -------------------------------------------------------------------------------- 1 | import { exitCode } from 'prosemirror-commands'; 2 | import { undo, redo } from 'prosemirror-history'; 3 | import { TextSelection, Selection } from 'prosemirror-state'; 4 | import { Node as ProsemirrorNode } from 'prosemirror-model'; 5 | import { EditorView } from 'prosemirror-view'; 6 | 7 | import CodeMirror from 'codemirror'; 8 | import 'codemirror/mode/javascript/javascript'; 9 | 10 | import schema from '../schema'; 11 | 12 | function computeChange(oldVal: string, newVal: string) { 13 | if (oldVal === newVal) { return null; } 14 | let start = 0; 15 | let oldEnd = oldVal.length; 16 | let newEnd = newVal.length; 17 | while (start < oldEnd && oldVal.charCodeAt(start) === newVal.charCodeAt(start)) { 18 | ++start; 19 | } 20 | while (oldEnd > start && newEnd > start && oldVal.charCodeAt(oldEnd - 1) === newVal.charCodeAt(newEnd - 1)) { 21 | oldEnd--; newEnd--; 22 | } 23 | return { from: start, to: oldEnd, text: newVal.slice(start, newEnd) }; 24 | } 25 | 26 | type GetPos = () => number; 27 | 28 | class CodeMirrorView { 29 | node: ProsemirrorNode; 30 | getPos: GetPos; 31 | incomingChanges: boolean; 32 | 33 | cm: CodeMirror; 34 | 35 | view: EditorView; 36 | dom: HTMLElement; 37 | updating: boolean; 38 | 39 | constructor(node: ProsemirrorNode, view: EditorView, getPos: GetPos) { 40 | // Store for later 41 | this.node = node; 42 | this.view = view; 43 | this.getPos = getPos; 44 | this.incomingChanges = false; 45 | 46 | // Create a CodeMirror instance 47 | this.cm = new CodeMirror(null, { 48 | value: this.node.textContent, 49 | lineNumbers: true, 50 | extraKeys: this.codeMirrorKeymap() 51 | }); 52 | 53 | // The editor's outer node is our DOM representation 54 | this.dom = this.cm.getWrapperElement(); 55 | // CodeMirror needs to be in the DOM to properly initialize, so 56 | // schedule it to update itself 57 | setTimeout(() => this.cm.refresh(), 20); 58 | 59 | // This flag is used to avoid an update loop between the outer and 60 | // inner editor 61 | this.updating = false; 62 | // Track whether changes are have been made but not yet propagated 63 | this.cm.on('beforeChange', () => this.incomingChanges = true); 64 | // Propagate updates from the code editor to ProseMirror 65 | this.cm.on('cursorActivity', () => { 66 | if (!this.updating && !this.incomingChanges) { this.forwardSelection(); } 67 | }); 68 | 69 | this.cm.on('changes', () => { 70 | if (!this.updating) { 71 | this.valueChanged(); 72 | this.forwardSelection(); 73 | } 74 | this.incomingChanges = false; 75 | }); 76 | 77 | this.cm.on('focus', () => this.forwardSelection()); 78 | } 79 | 80 | forwardSelection() { 81 | if (!this.cm.hasFocus()) { 82 | return; 83 | } 84 | 85 | const state = this.view.state; 86 | const selection = this.asProseMirrorSelection(state.doc); 87 | 88 | if (!selection.eq(state.selection)) { 89 | this.view.dispatch(state.tr.setSelection(selection)); 90 | } 91 | } 92 | 93 | asProseMirrorSelection(doc: ProsemirrorNode) { 94 | const offset = this.getPos() + 1; 95 | const anchor = this.cm.indexFromPos(this.cm.getCursor('anchor')) + offset; 96 | const head = this.cm.indexFromPos(this.cm.getCursor('head')) + offset; 97 | return TextSelection.create(doc, anchor, head); 98 | } 99 | 100 | setSelection(anchor: number, head: number) { 101 | this.cm.focus(); 102 | this.updating = true; 103 | this.cm.setSelection(this.cm.posFromIndex(anchor), this.cm.posFromIndex(head)); 104 | this.updating = false; 105 | } 106 | 107 | valueChanged() { 108 | const change = computeChange(this.node.textContent, this.cm.getValue()); 109 | if (change) { 110 | const start = this.getPos() + 1; 111 | const tr = this.view.state.tr.replaceWith( 112 | start + change.from, start + change.to, 113 | change.text ? schema.text(change.text) : null); 114 | this.view.dispatch(tr); 115 | } 116 | } 117 | codeMirrorKeymap() { 118 | const view = this.view; 119 | const mod = /Mac/.test(navigator.platform) ? 'Cmd' : 'Ctrl'; 120 | return CodeMirror.normalizeKeyMap({ 121 | Up: () => this.maybeEscape('line', -1), 122 | Left: () => this.maybeEscape('char', -1), 123 | Down: () => this.maybeEscape('line', 1), 124 | Right: () => this.maybeEscape('char', 1), 125 | [`${mod}-Z`]: () => undo(view.state, view.dispatch), 126 | [`Shift-${mod}-Z`]: () => redo(view.state, view.dispatch), 127 | [`${mod}-Y`]: () => redo(view.state, view.dispatch), 128 | 'Ctrl-Enter': () => { 129 | if (exitCode(view.state, view.dispatch)) { view.focus(); } 130 | } 131 | }); 132 | } 133 | 134 | maybeEscape(unit: string, dir: number) { 135 | const pos = this.cm.getCursor(); 136 | if (this.cm.somethingSelected() || 137 | pos.line !== (dir < 0 ? this.cm.firstLine() : this.cm.lastLine()) || 138 | (unit === 'char' && 139 | pos.ch !== (dir < 0 ? 0 : this.cm.getLine(pos.line).length))) { 140 | return CodeMirror.Pass; 141 | } 142 | 143 | this.view.focus(); 144 | const targetPos = this.getPos() + (dir < 0 ? 0 : this.node.nodeSize); 145 | const selection = Selection.near(this.view.state.doc.resolve(targetPos), dir); 146 | this.view.dispatch(this.view.state.tr.setSelection(selection).scrollIntoView()); 147 | this.view.focus(); 148 | } 149 | 150 | update(node: ProsemirrorNode) { 151 | if (node.type !== this.node.type) { return false; } 152 | this.node = node; 153 | const change = computeChange(this.cm.getValue(), node.textContent); 154 | if (change) { 155 | this.updating = true; 156 | this.cm.replaceRange(change.text, this.cm.posFromIndex(change.from), 157 | this.cm.posFromIndex(change.to)); 158 | this.updating = false; 159 | } 160 | return true; 161 | } 162 | } 163 | 164 | export default CodeMirrorView; 165 | -------------------------------------------------------------------------------- /src/app/nodeviews/index.ts: -------------------------------------------------------------------------------- 1 | import CodeBlockView from './CodeMirror'; 2 | import { Node as ProsemirrorNode } from 'prosemirror-model'; 3 | import { EditorView } from 'prosemirror-view'; 4 | 5 | const nodeViews = { 6 | code_block: (node: ProsemirrorNode, view: EditorView, getPos: () => number) => { 7 | return new CodeBlockView(node, view, getPos); 8 | } 9 | }; 10 | 11 | export default nodeViews; 12 | -------------------------------------------------------------------------------- /src/app/plugins/index.ts: -------------------------------------------------------------------------------- 1 | import { menu, placeholder } from 'ngx-editor'; 2 | 3 | import { undo, redo, history } from 'prosemirror-history'; 4 | import { splitListItem, liftListItem, sinkListItem } from 'prosemirror-schema-list'; 5 | import { keymap } from 'prosemirror-keymap'; 6 | import { toggleMark, baseKeymap } from 'prosemirror-commands'; 7 | import { Plugin } from 'prosemirror-state'; 8 | 9 | import codemirrorMenu from './menu/codemirror'; 10 | import { buildInputRules } from './input-rules'; 11 | import schema from '../schema'; 12 | 13 | const isMacOs = /Mac/.test(navigator.platform); 14 | 15 | export type KeyMap = { [key: string]: any }; 16 | 17 | const getHistoryKeyMap = (): KeyMap => { 18 | const historyMap: KeyMap = {}; 19 | 20 | historyMap['Mod-z'] = undo; 21 | 22 | if (isMacOs) { 23 | historyMap['Shift-Mod-z'] = redo; 24 | } else { 25 | historyMap['Mod-y'] = redo; 26 | } 27 | 28 | return historyMap; 29 | }; 30 | 31 | const getListKeyMap = (): KeyMap => { 32 | const listMap: KeyMap = {}; 33 | 34 | listMap.Enter = splitListItem(schema.nodes.list_item); 35 | listMap['Mod-['] = liftListItem(schema.nodes.list_item); 36 | listMap['Mod-]'] = sinkListItem(schema.nodes.list_item); 37 | listMap.Tab = sinkListItem(schema.nodes.list_item); 38 | 39 | return listMap; 40 | }; 41 | 42 | const getPlugins = (): Plugin[] => { 43 | const historyKeyMap = getHistoryKeyMap(); 44 | const listKeyMap = getListKeyMap(); 45 | 46 | const plugins = [ 47 | history(), 48 | keymap({ 49 | 'Mod-b': toggleMark(schema.marks.strong), 50 | 'Mod-i': toggleMark(schema.marks.em), 51 | 'Mod-`': toggleMark(schema.marks.code), 52 | }), 53 | keymap(historyKeyMap), 54 | keymap(listKeyMap), 55 | keymap(baseKeymap), 56 | buildInputRules(schema), 57 | menu({ 58 | toolbar: [ 59 | [codemirrorMenu] 60 | ], 61 | labels: { 62 | } 63 | }), 64 | // placeholder('Type Something here...') 65 | ]; 66 | 67 | return plugins; 68 | }; 69 | 70 | export default getPlugins(); 71 | -------------------------------------------------------------------------------- /src/app/plugins/input-rules.ts: -------------------------------------------------------------------------------- 1 | import { 2 | inputRules, wrappingInputRule, textblockTypeInputRule, 3 | smartQuotes, emDash, ellipsis, InputRule 4 | } from 'prosemirror-inputrules'; 5 | import { NodeType, Schema } from 'prosemirror-model'; 6 | 7 | // Source: https://github.com/ProseMirror/prosemirror-example-setup/ 8 | 9 | // : (NodeType) → InputRule 10 | // Given a blockquote node type, returns an input rule that turns `"> "` 11 | // at the start of a textblock into a blockquote. 12 | export function blockQuoteRule(nodeType: NodeType): InputRule { 13 | return wrappingInputRule(/^\s*>\s$/, nodeType); 14 | } 15 | 16 | // : (NodeType) → InputRule 17 | // Given a list node type, returns an input rule that turns a number 18 | // followed by a dot at the start of a textblock into an ordered list. 19 | export function orderedListRule(nodeType: NodeType): InputRule { 20 | return wrappingInputRule( 21 | /^(\d+)\.\s$/, 22 | nodeType, 23 | match => ({ order: +match[1] }), 24 | (match, node) => node.childCount + node.attrs.order === +match[1] 25 | ); 26 | } 27 | 28 | // : (NodeType) → InputRule 29 | // Given a list node type, returns an input rule that turns a bullet 30 | // (dash, plush, or asterisk) at the start of a textblock into a 31 | // bullet list. 32 | export function bulletListRule(nodeType: NodeType): InputRule { 33 | return wrappingInputRule(/^\s*([-+*])\s$/, nodeType); 34 | } 35 | 36 | // : (NodeType) → InputRule 37 | // Given a code block node type, returns an input rule that turns a 38 | // textblock starting with three backticks into a code block. 39 | export function codeBlockRule(nodeType: NodeType): InputRule { 40 | return textblockTypeInputRule(/^```$/, nodeType); 41 | } 42 | 43 | // : (NodeType, number) → InputRule 44 | // Given a node type and a maximum level, creates an input rule that 45 | // turns up to that number of `#` characters followed by a space at 46 | // the start of a textblock into a heading whose level corresponds to 47 | // the number of `#` signs. 48 | export function headingRule(nodeType: NodeType, maxLevel: number): InputRule { 49 | return textblockTypeInputRule( 50 | new RegExp('^(#{1,' + maxLevel + '})\\s$'), 51 | nodeType, 52 | (match) => ({ level: match[1].length }) 53 | ); 54 | } 55 | 56 | // : (Schema) → Plugin 57 | // A set of input rules for creating the basic block quotes, lists, 58 | // code blocks, and heading. 59 | export function buildInputRules(schema: Schema) { 60 | const rules = smartQuotes.concat(ellipsis, emDash); 61 | 62 | rules.push(blockQuoteRule(schema.nodes.blockquote)); 63 | rules.push(orderedListRule(schema.nodes.ordered_list)); 64 | rules.push(bulletListRule(schema.nodes.bullet_list)); 65 | rules.push(codeBlockRule(schema.nodes.code_block)); 66 | rules.push(headingRule(schema.nodes.heading, 6)); 67 | 68 | return inputRules({ rules }); 69 | } 70 | -------------------------------------------------------------------------------- /src/app/plugins/menu/codemirror.ts: -------------------------------------------------------------------------------- 1 | import { EditorState } from 'prosemirror-state'; 2 | import { isNodeActive, toggleBlockType } from 'ngx-editor'; 3 | 4 | import schema from '../../schema'; 5 | 6 | const codeMirror = (editorView) => { 7 | const dom: HTMLElement = document.createElement('div'); 8 | dom.innerHTML = '<>'; 9 | 10 | dom.classList.add('NgxEditor__MenuItem'); 11 | dom.classList.add('NgxEditor__MenuItem--Text'); 12 | 13 | const type = schema.nodes.code_block; 14 | 15 | const command = toggleBlockType(type, schema.nodes.paragraph); 16 | 17 | dom.addEventListener('mousedown', (e: MouseEvent) => { 18 | e.preventDefault(); 19 | 20 | // don't execute if not left click 21 | if (e.buttons !== 1) { 22 | return; 23 | } 24 | 25 | command(editorView.state, editorView.dispatch); 26 | }); 27 | 28 | const update = (state: EditorState): void => { 29 | const isActive = isNodeActive(state, type); 30 | 31 | const canExecute = command(state, null); 32 | 33 | dom.classList.toggle(`NgxEditor__MenuItem--Active`, isActive); 34 | dom.classList.toggle(`NgxEditor--Disabled`, !canExecute); 35 | }; 36 | 37 | return { 38 | dom, 39 | update 40 | }; 41 | }; 42 | 43 | export default codeMirror; 44 | -------------------------------------------------------------------------------- /src/app/schema.ts: -------------------------------------------------------------------------------- 1 | import { nodes as basicNodes, marks as basicMarks } from 'ngx-editor'; 2 | import { Schema, Node as ProsemirrorNode, NodeSpec } from 'prosemirror-model'; 3 | 4 | const codeBlock: NodeSpec = { 5 | group: 'block', 6 | editable: false, 7 | attrs: { 8 | text: { default: '' }, 9 | language: { default: 'text/javascript' } 10 | }, 11 | parseDOM: [{ 12 | tag: 'pre', 13 | getAttrs: (dom: HTMLElement) => { 14 | return { 15 | text: dom.textContent, 16 | language: dom.getAttribute('data-language') || 'text/plain' 17 | }; 18 | } 19 | } 20 | ], 21 | toDOM(node: ProsemirrorNode) { 22 | return ['pre', { 'data-language': node.attrs.language }, node.attrs.text]; 23 | } 24 | }; 25 | 26 | const nodes = Object.assign( 27 | {}, 28 | basicNodes, 29 | { 30 | code_mirror: codeBlock 31 | } 32 | ); 33 | 34 | const schema = new Schema({ 35 | nodes, 36 | marks: basicMarks, 37 | }); 38 | 39 | export default schema; 40 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/assets/icons/icon-128x128.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/icons/icon-128x128.png -------------------------------------------------------------------------------- /src/assets/icons/icon-144x144.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/icons/icon-144x144.png -------------------------------------------------------------------------------- /src/assets/icons/icon-152x152.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/icons/icon-152x152.png -------------------------------------------------------------------------------- /src/assets/icons/icon-192x192.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/icons/icon-192x192.png -------------------------------------------------------------------------------- /src/assets/icons/icon-384x384.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/icons/icon-384x384.png -------------------------------------------------------------------------------- /src/assets/icons/icon-512x512.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/icons/icon-512x512.png -------------------------------------------------------------------------------- /src/assets/icons/icon-72x72.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/icons/icon-72x72.png -------------------------------------------------------------------------------- /src/assets/icons/icon-96x96.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/assets/icons/icon-96x96.png -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build --prod` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/dist/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/titans55/json-to-drf-serializers/7db33be4edc625ea83545f378d31cac4bddc09e9/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Generate DRF serializers from JSON 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule) 12 | .catch(err => console.error(err)); 13 | -------------------------------------------------------------------------------- /src/manifest.webmanifest: -------------------------------------------------------------------------------- 1 | { 2 | "name": "json2drfserializer", 3 | "short_name": "json2drfserializer", 4 | "theme_color": "#1976d2", 5 | "background_color": "#fafafa", 6 | "display": "standalone", 7 | "scope": "./", 8 | "start_url": "./", 9 | "icons": [ 10 | { 11 | "src": "assets/icons/icon-72x72.png", 12 | "sizes": "72x72", 13 | "type": "image/png", 14 | "purpose": "maskable any" 15 | }, 16 | { 17 | "src": "assets/icons/icon-96x96.png", 18 | "sizes": "96x96", 19 | "type": "image/png", 20 | "purpose": "maskable any" 21 | }, 22 | { 23 | "src": "assets/icons/icon-128x128.png", 24 | "sizes": "128x128", 25 | "type": "image/png", 26 | "purpose": "maskable any" 27 | }, 28 | { 29 | "src": "assets/icons/icon-144x144.png", 30 | "sizes": "144x144", 31 | "type": "image/png", 32 | "purpose": "maskable any" 33 | }, 34 | { 35 | "src": "assets/icons/icon-152x152.png", 36 | "sizes": "152x152", 37 | "type": "image/png", 38 | "purpose": "maskable any" 39 | }, 40 | { 41 | "src": "assets/icons/icon-192x192.png", 42 | "sizes": "192x192", 43 | "type": "image/png", 44 | "purpose": "maskable any" 45 | }, 46 | { 47 | "src": "assets/icons/icon-384x384.png", 48 | "sizes": "384x384", 49 | "type": "image/png", 50 | "purpose": "maskable any" 51 | }, 52 | { 53 | "src": "assets/icons/icon-512x512.png", 54 | "sizes": "512x512", 55 | "type": "image/png", 56 | "purpose": "maskable any" 57 | } 58 | ] 59 | } 60 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 22 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 23 | 24 | /** 25 | * Web Animations `@angular/platform-browser/animations` 26 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 27 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 28 | */ 29 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 30 | 31 | /** 32 | * By default, zone.js will patch all possible macroTask and DomEvents 33 | * user can disable parts of macroTask/DomEvents patch by setting following flags 34 | * because those flags need to be set before `zone.js` being loaded, and webpack 35 | * will put import in the top of bundle, so user need to create a separate file 36 | * in this directory (for example: zone-flags.ts), and put the following flags 37 | * into that file, and then add the following code before importing zone.js. 38 | * import './zone-flags'; 39 | * 40 | * The flags allowed in zone-flags.ts are listed here. 41 | * 42 | * The following flags will work for all browsers. 43 | * 44 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 45 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 46 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 47 | * 48 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 49 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 50 | * 51 | * (window as any).__Zone_enable_cross_context_check = true; 52 | * 53 | */ 54 | 55 | /*************************************************************************************************** 56 | * Zone JS is required by default for Angular itself. 57 | */ 58 | import 'zone.js/dist/zone'; // Included with Angular CLI. 59 | 60 | 61 | /*************************************************************************************************** 62 | * APPLICATION IMPORTS 63 | */ 64 | -------------------------------------------------------------------------------- /src/styles.scss: -------------------------------------------------------------------------------- 1 | //needed bootstrap imports 2 | @import "~bootstrap/scss/functions"; 3 | @import "~bootstrap/scss/variables"; 4 | @import "~bootstrap/scss/mixins"; 5 | 6 | @import "~bootstrap/scss/reboot"; 7 | @import "~bootstrap/scss/grid"; 8 | @import "~bootstrap/scss/utilities"; 9 | 10 | @import "codemirror/lib/codemirror.css"; -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | keys(): string[]; 13 | (id: string): T; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting() 21 | ); 22 | // Then we find all the tests. 23 | const context = require.context('./', true, /\.spec\.ts$/); 24 | // And load the modules. 25 | context.keys().map(context); 26 | -------------------------------------------------------------------------------- /tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/app", 5 | "types": [] 6 | }, 7 | "files": [ 8 | "src/main.ts", 9 | "src/polyfills.ts" 10 | ], 11 | "include": [ 12 | "src/**/*.d.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "module": "esnext", 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "lib": [ 15 | "es2018", 16 | "dom" 17 | ] 18 | }, 19 | "angularCompilerOptions": { 20 | "fullTemplateTypeCheck": true, 21 | "strictInjectionParameters": true 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "align": { 5 | "options": [ 6 | "parameters", 7 | "statements" 8 | ] 9 | }, 10 | "array-type": false, 11 | "arrow-return-shorthand": true, 12 | "curly": true, 13 | "deprecation": { 14 | "severity": "warning" 15 | }, 16 | "component-class-suffix": true, 17 | "contextual-lifecycle": true, 18 | "directive-class-suffix": true, 19 | "directive-selector": [ 20 | true, 21 | "attribute", 22 | "app", 23 | "camelCase" 24 | ], 25 | "component-selector": [ 26 | true, 27 | "element", 28 | "app", 29 | "kebab-case" 30 | ], 31 | "eofline": true, 32 | "import-blacklist": [ 33 | true, 34 | "rxjs/Rx" 35 | ], 36 | "import-spacing": true, 37 | "indent": { 38 | "options": [ 39 | "spaces" 40 | ] 41 | }, 42 | "max-classes-per-file": false, 43 | "max-line-length": [ 44 | true, 45 | 140 46 | ], 47 | "member-ordering": [ 48 | true, 49 | { 50 | "order": [ 51 | "static-field", 52 | "instance-field", 53 | "static-method", 54 | "instance-method" 55 | ] 56 | } 57 | ], 58 | "no-console": [ 59 | true, 60 | "debug", 61 | "info", 62 | "time", 63 | "timeEnd", 64 | "trace" 65 | ], 66 | "no-empty": false, 67 | "no-inferrable-types": [ 68 | true, 69 | "ignore-params" 70 | ], 71 | "no-non-null-assertion": true, 72 | "no-redundant-jsdoc": true, 73 | "no-switch-case-fall-through": true, 74 | "no-var-requires": false, 75 | "object-literal-key-quotes": [ 76 | true, 77 | "as-needed" 78 | ], 79 | "quotemark": [ 80 | true, 81 | "single" 82 | ], 83 | "semicolon": { 84 | "options": [ 85 | "always" 86 | ] 87 | }, 88 | "space-before-function-paren": { 89 | "options": { 90 | "anonymous": "never", 91 | "asyncArrow": "always", 92 | "constructor": "never", 93 | "method": "never", 94 | "named": "never" 95 | } 96 | }, 97 | "typedef-whitespace": { 98 | "options": [ 99 | { 100 | "call-signature": "nospace", 101 | "index-signature": "nospace", 102 | "parameter": "nospace", 103 | "property-declaration": "nospace", 104 | "variable-declaration": "nospace" 105 | }, 106 | { 107 | "call-signature": "onespace", 108 | "index-signature": "onespace", 109 | "parameter": "onespace", 110 | "property-declaration": "onespace", 111 | "variable-declaration": "onespace" 112 | } 113 | ] 114 | }, 115 | "variable-name": { 116 | "options": [ 117 | "ban-keywords", 118 | "check-format", 119 | "allow-pascal-case" 120 | ] 121 | }, 122 | "whitespace": { 123 | "options": [ 124 | "check-branch", 125 | "check-decl", 126 | "check-operator", 127 | "check-separator", 128 | "check-type", 129 | "check-typecast" 130 | ] 131 | }, 132 | "no-conflicting-lifecycle": true, 133 | "no-host-metadata-property": true, 134 | "no-input-rename": true, 135 | "no-inputs-metadata-property": true, 136 | "no-output-native": true, 137 | "no-output-on-prefix": true, 138 | "no-output-rename": true, 139 | "no-outputs-metadata-property": true, 140 | "template-banana-in-box": true, 141 | "template-no-negated-async": true, 142 | "use-lifecycle-interface": true, 143 | "use-pipe-transform-interface": true 144 | }, 145 | "rulesDirectory": [ 146 | "codelyzer" 147 | ] 148 | } --------------------------------------------------------------------------------