Как мне реализовать несколько курсоров в quill через Angular 8? - PullRequest
0 голосов
/ 07 ноября 2019

Я пытаюсь реализовать совместное редактирование в Quill, для которого я использую Angular в качестве внешнего интерфейса и Node в качестве внутреннего. Я уже настроил sharedb с адаптерами mongo, а также модуль ngx-quill во внешнем интерфейсе. Однако я не совсем понимаю, как реализовать модуль курсоров quill в Angular 8?

Мой сервис сокетов

import { Injectable } from '@angular/core';

@Injectable({
 providedIn: 'root'
})
export class SocketsService {
 connection: any;
 sharedb: any;
 socket:any;
 doc: any;

 constructor() {
   this.sharedb = require('sharedb/lib/client');
   this.sharedb.types.register(require('rich-text').type);
   // Open WebSocket connection to ShareDB server
   this.socket = new WebSocket('ws://localhost:8080/sharedb');
   this.connection = new this.sharedb.Connection(this.socket);
   this.doc = this.connection.get('examples', 'richtext');
 }
}

Мой редактор компонентов

import {ViewChild, Component, OnInit} from '@angular/core';
import { QuillEditorComponent } from 'ngx-quill';
import QuillCursors from 'quill-cursors';
import {SocketsService} from '../sockets.service';
import {HttpClient} from '@angular/common/http';
import Quill from 'quill';
import 'quill-mention';
import jsondecoder from 'jsonwebtoken/decode.js'
Quill.register('modules/cursors', QuillCursors);
const Tooltip = Quill.import('ui/tooltip'); 

@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.css']
})

export class EditorComponent implements OnInit{
  @ViewChild(QuillEditorComponent, { static: true })
  editor: QuillEditorComponent;
  content = '';
  myTooltip:any;
  public modules: any;
  private socket: any;
  private http: HttpClient;
  ngOnInit(){
  }

  constructor()
  {
    this.socket = new SocketsService();

    this.modules = {
      cursors: {
        transformOnTextChange: true
      },
      mention: {
        allowedChars: /^[A-Za-z\sÅÄÖåäö]*$/,
        onSelect: (item, insertItem) => {
          const editor = this.editor.quillEditor as Quill
          insertItem(item) // necessary because quill-mention triggers changes as 'api' instead of 'user'
          editor.insertText(editor.getLength() - 1, '', 'user')
        },
        source: (searchTerm, renderList) => {
          const values = [
            { id: 1, value: 'Alec'},
            { id: 2, value: 'Irshad'},
            { id: 3, value: 'Anmol'},
            { id: 4, value: 'MunMun'},
            { id: 5, value:'Zoya'}
          ]
          if (searchTerm.length === 0) {
            renderList(values, searchTerm)
          } else {
            const matches = []
            values.forEach((entry) => {
              if (entry.value.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1) {
                matches.push(entry)
              }
            })
            renderList(matches, searchTerm)
          }
        }
      }
    }
  }

  editorCreated($event){
    this.socket.doc.subscribe((err)=>{ // Get initial value of document and subscribe to changes
      if(err) throw err;
       $event.setContents(this.socket.doc.data);
      this.socket.doc.on('op', (op, source)=>{
        if (source === 'quill') return;
        $event.updateContents(op);
      });
    });
  }

  logChanged($event)
  { 
    if ($event.source !== 'user') return;
    this.socket.doc.submitOp($event.delta, {source: 'quill'});
  }
}

Код внутреннего узла My Node

var ShareDB = require('@teamwork/sharedb');
var richText = require('rich-text');
ShareDB.types.register(richText.type);
const mongodb = require('mongodb');
const db = require('@teamwork/sharedb-mongo')({mongo: function(callback) {
  mongodb.connect('mongodb://localhost:27017/test',{useUnifiedTopology: true},callback);
}});
const shareDBServer= new ShareDB({db, disableDocAction: true, disableSpaceDelimitedActions: true});
var connection = shareDBServer.connect();
var doc = connection.get('examples', 'richtext');
doc.fetch(function(err) {
  if (err) throw err;
  if (doc.type === null) {
    doc.create([{insert: 'Document Ready'}], 'rich-text', callback);
    return;
  }
});
 var wss = new WebSocket.Server({
    noServer: true
  });

  wss.on('connection', function(ws, req) {
    ws.isAlive = true;

    var stream = new WebSocketJSONStream(ws);
    shareDBServer.listen(stream);

    ws.on('pong', function(data, flags) {
      ws.isAlive = true;
    });

    ws.on('error', function(error) {
        console.log('Error');
    });
 });

У меня вопрос после импорта модуля quill-cursors в мой компонент Editor, как мне его реализовать?

1 Ответ

0 голосов
/ 07 ноября 2019

Сначала вы должны установить перо в свой угловой проект

npm install ngx-quill

для проектов, использующих Angular npm install ngx-quill@1.6.0

в вашем app.module.ts импорт QuillModule из ngx-quill:

import { QuillModule } from 'ngx-quill';

добавление QuillModule к импортам вашего NgModule:

@NgModule({
  imports: [
    ...,

    QuillModule.forRoot()
  ],
  ...
})
class YourModule { ... }

использование <quill-editor></quill-editor> в ваших шаблонах для добавления редактора quill по умолчанию

ссылка ngx-quill

...