Dave Jarvis' Repositories

git clone https://repo.autonoma.ca/repo/notanexus.git
const PAGE_NUMBER_OFFSET = 6;

export default class Annotation {
  constructor(data) {
    if (typeof data === 'object' && data !== null) {
      this.id = data.id || this.generateId();
      this.text = data.text;
      this.note = data.note || '';
      this.pageNumber = data.pageNumber;
      this.timestamp = data.timestamp ? new Date(data.timestamp) : new Date();
      this.regions = Array.isArray(data.regions) ? [...data.regions] : [];
    } else {
      const selectedText = arguments[0];
      const pageNumber = arguments[1];
      const note = arguments[2] || '';
      const existingId = arguments[3] || null;
      const timestamp = arguments[4] || new Date();

      this.id = existingId || this.generateId();
      this.text = selectedText;
      this.note = note;
      this.pageNumber = pageNumber;
      this.timestamp = timestamp;
      this.regions = [];
    }
  }

  generateId() {
    return Math.floor(1000000 + Math.random() * 10000000);
  }

  forEachRegion(callback) {
    this.regions.forEach((region, index) => {
      callback(region, index);
    });
  }

  addPdfRegion(region) {
    this.regions.push(region);
  }

  addRegion(element) {
    const randomId = this.generateId();
    const elementId = element.id || `region-${randomId}`;

    const existingRegion = this.regions.find(r => r.id === elementId);
    if (existingRegion) {
      return;
    }

    this.regions.push({
      id: elementId,
      left: parseFloat(element.style.left),
      top: parseFloat(element.style.top),
      width: parseFloat(element.style.width),
      height: parseFloat(element.style.height)
    });

    element.setAttribute('data-annotation-id', this.id);
  }

  removeRegion(elementIdOrElement) {
    const elementId = typeof elementIdOrElement === 'string' ?
                      elementIdOrElement :
                      elementIdOrElement.id;

    const index = this.regions.findIndex(r => r.id === elementId);
    if (index !== -1) {
      this.regions.splice(index, 1);
      return true;
    }
    return false;
  }

  hasRegions() {
    return this.regions.length > 0;
  }

  updateNote(newNote) {
    this.note = newNote;
    this._log();
  }

  toJson() {
    return {
      id: this.id,
      text: this.text,
      note: this.note,
      pageNumber: this.pageNumber,
      timestamp: this.timestamp,
      regions: this.regions
    };
  }

  static fromJson(data) {
    return new Annotation(data);
  }

  save() {
    this._log();
    return this;
  }

  toString() {
    const displayPageNum = parseInt(this.pageNumber) - PAGE_NUMBER_OFFSET;
    let result = '-'.repeat(5) + `| Page ${displayPageNum} |` + '-'.repeat(30) + '\n';
    result += `  > "${this.text}"\n`;
    result += `  * ${this.note}\n\n`;
    return result;
  }

  _log() {
    console.log('Annotation:', this.toJson());
  }
}