in angular ngx-markdown-editor is not working and not show the right preview

Discussão em 'Angular' iniciado por Rinkal, Dezembro 16, 2024.

  1. Rinkal

    Rinkal Guest

    here this is markdown-editor demo github in here i am not use bootstrap style in angular.json because in my main project i am using tailwind css so if in angular.json i am use bootstrap style than it is generate the conflict so in in demo also i am not use bootstrap style and if i am write the raw content than it is give the perfect answer like [[​IMG]] and the same code i am write in my project than it is give the this type of preview [​IMG]

    here this is code for ts file


    import { LMarkdownEditorModule } from 'ngx-markdown-editor';
    import { CategoryService } from './../services/category.service';
    import {
    ChangeDetectorRef,
    Component,
    HostListener,
    Inject,
    Renderer2,
    } from '@angular/core';
    import { CeateOpenaiService } from './ceate-openai.service';
    import { SharedModule } from '../shared/shared.module';
    import { CommonModule } from '@angular/common';
    import {
    FormBuilder,
    FormGroup,
    FormsModule,
    ReactiveFormsModule,
    Validators,
    } from '@angular/forms';
    import { ProjectService } from '../services/project.service';
    import { format } from 'date-fns';
    import { ActivatedRoute, Router, RouterModule } from '@angular/router';
    import { debounceTime, Subject, Subscription } from 'rxjs';
    import { L10nLocale, L10N_LOCALE, L10nTranslationModule } from 'angular-l10n';
    import { ToastrService } from 'ngx-toastr';
    import { marked } from 'marked';

    @Component({
    selector: 'app-create-openai',
    standalone: true,
    imports: [
    SharedModule,
    CommonModule,
    FormsModule,
    RouterModule,
    L10nTranslationModule,
    ReactiveFormsModule,
    LMarkdownEditorModule,
    ],
    templateUrl: './create-openai.component.html',
    styleUrl: './create-openai.component.scss',
    })
    export class CreateOpenaiComponent {
    isDataLoading: boolean = true;
    createform!: FormGroup;
    isNoDataFound: boolean = false;
    transcriptionHistory: string[] = [];
    isSidebarOpen = false;
    dropdownOpen = false;
    lastCreatedAtId: any;
    toggleSidebar() {
    this.isSidebarOpen = !this.isSidebarOpen;
    }

    toggleDropdown() {
    this.dropdownOpen = !this.dropdownOpen;
    }

    private transcriptionSubscription: Subscription | null = null;

    isVisible: boolean = false;
    transcription: string = '';
    aiResponse: string = '';
    isRecording: boolean = false;
    isEditing: boolean = false;
    editedText: string = '';
    aiResponses: string[] = [];
    data: any[] = [];
    projectnames: any[] = [];
    projectname: any;
    paginationMeta: any = {};
    currentPage: number = 1;
    perPage: number = 15;
    projectId: number = 0;
    aiId: any;
    audioBlob: Blob | null = null;
    mediaRecorder: any;
    silenceTimeout: any;
    openAiResponse: string = '';
    spacebarTimer: any;
    minHoldTime = 100;
    isLoading: boolean = false;
    isLoadingSaveData = false;
    isUpdate: boolean = false;
    sortBy: string = '';
    sortDir: string = '';
    aires: boolean = false;
    image: any;
    templateId: number = 0;
    isProcessing = false;
    private typingSubject = new Subject<string>();
    page: number = 0;
    previewContent: string = '';
    aitrancriptId: number = 0;

    constructor(
    private fb: FormBuilder,
    private route: ActivatedRoute,
    private toastr: ToastrService,
    public router: Router,
    private openAIService: CeateOpenaiService,
    private projectService: ProjectService,
    private cdr: ChangeDetectorRef,
    private renderer: Renderer2,
    private CategoryService: CategoryService,
    @Inject(L10N_LOCALE) public lang: L10nLocale
    ) {
    this.route.params.subscribe((result: any) => {
    this.projectId = result.id;
    });

    }

    formpromoInitialization() {
    this.createform = this.fb?.group({
    transcription: ['', [Validators.required]],
    airesponse: ['', [Validators.required]],
    });
    }

    get trancript() {
    return this.createform.get('transcription');
    }

    get airesponse() {
    return this.createform.get('airesponse');
    }

    ngOnInit() {
    this.projectId = +this.route.snapshot.paramMap.get('id')!;
    this.getprojectname();
    this.updatetranscript();
    this.openAIService.fetchProjectById(this.projectId)
    }
    transcribeAudio() {
    if (this.audioBlob) {
    const audioFile = new File([this.audioBlob], 'recording.wav', {
    type: 'audio/wav',
    });

    this.openAIService.transcribeAudio(audioFile, 'en').subscribe(
    (response: any) => {
    if (response && response.text) {
    this.transcription += ' ' + response.text;
    this.transcriptionHistory.push(this.transcription);
    this.savedata();
    }
    this.isProcessing = false;
    this.isLoading = false;
    },
    (error) => {
    console.error('Transcription error:', error);
    this.isLoading = false;
    }
    );
    }
    }



    onTextInput(event: any) {
    this.transcription = event.target.value;
    this.typingSubject.next(this.transcription);
    this.cdr.detectChanges();
    }

    savedata() {
    if (this.aitrancriptId !== 0) {
    this.saveapi(false);
    return;
    }
    this.templateId = this.CategoryService.getTemplateId() || 0;
    const newEntry = {
    transcript: this.transcription,
    ai_response: '',
    template_id: this.templateId,
    created_at: format(new Date(), 'dd MMM. yyyy HH:mm:ss'),
    isUpdate: false,
    };
    this.isLoadingSaveData = true;
    this.openAIService
    .createqustion(this.transcription, newEntry, this.projectId)
    .subscribe(
    (response) => {
    this.isLoadingSaveData = false;
    if (response) {
    this.openAIService.addAiResponse({
    ...response.ai_interaction_id,
    isUpdate: false,
    });
    this.aitrancriptId = response.ai_interaction_id.id;
    this.aires = false;
    this.isRecording = false;
    this.cdr.detectChanges();
    }
    },
    (error) => {
    console.log('error', error);
    }
    );
    }

    saveText() {
    this.isLoading = true;
    this.aires = true;
    this.getAIResponse(this.transcription)
    .then((aiResponseText: string) => {
    this.aiResponse = aiResponseText;
    this.isLoading = false;
    })
    .catch(() => {
    this.isLoading = false;
    });
    this.cdr.detectChanges();
    }

    async getAIResponse(prompt: string): Promise<string> {
    try {
    this.aires = true
    const response = await this.openAIService.getResponse([prompt]);
    this.aiResponse = response;
    this.createform.get('airesponse')?.setValue(this.aiResponse);
    return response;
    } catch (error) {
    console.error('Error generating AI response:', error);
    return 'Something went wrong while generating the response.';
    }
    }

    saveapi(isreset: boolean = true): void {
    this.openAIService
    .getOpenAiResponse(
    this.page,
    this.perPage,
    this.projectId,
    this.sortBy,
    this.sortDir
    )
    .subscribe((response: any) => {
    if (response && response.data && response.data.length > 0) {
    this.data = response.data || [];
    const sortedData = this.data.sort(
    (a, b) =>
    new Date(b.created_at).getTime() -
    new Date(a.created_at).getTime()
    );
    this.lastCreatedAtId = sortedData[0]?.id;
    try {
    const template_id = this.CategoryService.getTemplateId();
    const updatedData = {
    transcript: this.transcription,
    ai_response: this.aiResponse,
    template_id: template_id,
    image: this.CategoryService.getImage(),
    created_at: format(new Date(), 'dd MMM. yyyy HH:mm:ss'),
    isUpdate: true,
    id: this.lastCreatedAtId,
    };
    this.isLoadingSaveData = true;
    this.openAIService
    .updateTranscription(
    this.projectId,
    updatedData,
    this.lastCreatedAtId
    )
    .subscribe(
    (response: any) => {
    this.isLoadingSaveData = false;
    if (isreset) {
    this.toastr.success('Data saved successfully!');
    }
    this.aiResponse = updatedData.ai_response;
    this.openAIService.addAiResponse(updatedData);

    if (response) {
    if (isreset) {
    this.createform.reset();
    this.aitrancriptId = 0;
    this.aiId = '';
    this.transcription = '';
    this.aiResponse = '';
    this.templateId = 0;
    }
    this.aires = false;
    this.cdr.detectChanges();
    this.isRecording = false;
    }
    },
    (HttpErrorResponse) => {
    this.isLoadingSaveData = false;
    if (
    HttpErrorResponse.status === 422 &&
    HttpErrorResponse.error
    ) {
    if (HttpErrorResponse.error.transcript) {
    this.trancript?.setErrors({
    serverError: HttpErrorResponse.error.name.join(', '),
    });
    }
    if (HttpErrorResponse.error.description) {
    this.airesponse?.setErrors({
    serverError:
    HttpErrorResponse.error.description.join(', '),
    });
    }
    this.toastr.error('Please fix the form errors.');
    } else {
    this.toastr.error(HttpErrorResponse.error.message);
    }
    }
    );
    } catch (error) {
    this.toastr.error('An unexpected error occurred.');
    this.isLoadingSaveData = false;
    }
    }
    });
    }

    private updatetranscript(): void {
    this.transcriptionSubscription =
    this.openAIService.transcription$.subscribe((data: any) => {
    this.isEditing = true;
    this.transcription = data.transcript;
    this.aiResponse = data.ai_response;
    this.aiId = data.id;
    this.aitrancriptId = data.id;
    this.aires = true;
    this.templateId = data.template.id;
    });
    }

    update(aiResponse: any) {
    if (this.createform.invalid) {
    this.createform.markAllAsTouched();
    return;
    }
    const image = this.image;
    const updatedData = {
    transcript: this.transcription,
    ai_response: aiResponse,
    template_id: this.templateId,
    image: image,
    created_at: format(new Date(), 'dd MMM. yyyy HH:mm:ss'),
    isUpdate: true,
    id: this.aiId,
    };
    this.openAIService.addAiResponse(updatedData);
    this.isLoadingSaveData = true;
    this.openAIService
    .updateTranscription(this.projectId, updatedData, this.aiId)
    .subscribe(
    (response) => {
    this.isLoadingSaveData = false;
    if (response) {
    }
    this.createform.reset();
    this.transcription = '';
    this.aiResponse ='';
    this.aires = false;
    this.isEditing = false;
    this.aitrancriptId =0;
    this.cdr.detectChanges();
    this.toastr.success(response.message);
    },

    (HttpErrorResponse) => {
    this.isLoadingSaveData = false;
    if (HttpErrorResponse.status === 422 && HttpErrorResponse.error) {
    if (HttpErrorResponse.error.transcript) {
    this.trancript?.setErrors({
    serverError: HttpErrorResponse.error.name.join(', '),
    });
    }
    if (HttpErrorResponse.error.description) {
    this.airesponse?.setErrors({
    serverError: HttpErrorResponse.error.description.join(', '),
    });
    }
    this.toastr.error('Please fix the form errors.');
    } else {
    this.toastr.error(HttpErrorResponse.error.message);
    }
    }
    );
    }

    getprojectname() {
    this.isDataLoading = true;
    try {
    this.projectService.getProject().subscribe(
    (response: any) => {
    if (response && response.data) {
    const project = response.data.find(
    (item: any) => item.id === this.projectId
    );
    this.projectname = project;
    }
    this.isDataLoading = false;
    },
    (error) => {
    console.error('Error fetching project:', error);
    this.isDataLoading = false;
    }
    );
    } catch (error) {
    console.log(error);
    this.isDataLoading = false;
    }
    }


    preRenderFunc(content: string) {
    return content.replace(/something/g, 'new value');
    }

    postRenderFunc(content: string) {
    this.previewContent = content;
    this.aiResponse = content
    return content.replace(/something/g, 'new value');
    }

    onEditorLoaded(event: any): void {
    }

    onPreviewDomChanged(event: any): void {
    if (event && event.target instanceof HTMLElement) {
    const previewHtmlContent = event.target.innerHTML;
    this.previewContent = previewHtmlContent;
    } else {
    }
    }
    }




    and here


    <div class="mt-2" *ngIf="aiResponse">
    <!-- <textarea
    [(ngModel)]="aiResponse"
    id="airesponse"
    name="airesponse"
    formControlName="airesponse"
    rows="3"
    [ngClass]="{
    'border-red-500':
    createform.get('airesponse')!.invalid &&
    (createform.get('airesponse')!.dirty ||
    createform.get('airesponse')!.touched)
    }"
    class="block w-full rounded-md border-0 py-2 px-4 text-gray-900 shadow-sm ring-1 ring-inset ring-gray-300 placeholder:text-gray-400 focus:ring-2 focus:ring-inset focus:ring-indigo-600 sm:text-sm/6"
    ></textarea> -->
    <!-- <md-editor name="Content"
    [(ngModel)]="aiResponse"
    [preRender]="preRenderFunc"
    [postRender]="postRenderFunc"
    [height]="'300px'"
    formControlName="airesponse"
    (onEditorLoaded)="onEditorLoaded($event)"
    (onPreviewDomChanged)="onPreviewDomChanged($event)"
    required
    maxlength="500"
    [ngClass]="{
    'border-red-500':
    createform.get('airesponse')!.invalid &&
    (createform.get('airesponse')!.dirty ||
    createform.get('airesponse')!.touched)
    }"
    class="block w-full"
    >
    </md-editor> -->
    <md-editor name="Content"
    [preRender]="preRenderFunc"
    [postRender]="postRenderFunc"
    [height]="'200px'"
    (onEditorLoaded)="onEditorLoaded($event)"
    (onPreviewDomChanged)="onPreviewDomChanged($event)"
    required
    maxlength="500">
    <slot custom-btns></slot>
    </md-editor>
    <div
    *ngIf="
    createform.get('airesponse')!.invalid &&
    (createform.get('airesponse')!.dirty ||
    createform.get('airesponse')!.touched)
    "
    class="text-red-500 text-sm mt-1"
    >
    <div *ngIf="createform.get('airesponse')!.errors?.['required']">
    {{ "Createai.AIRESPONSE_ERROR" | translate : lang.language }}
    </div>
    <div
    *ngIf="createform.get('airesponse')!.errors?.['serverError']"
    >
    {{ createform.get('airesponse')!.errors?.['serverError'] }}
    </div>
    </div>
    </div>



    this is html file

    Continue reading...

Compartilhe esta Página