Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 | 67x 67x 67x 67x 67x 67x 67x 67x 67x 67x 98x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 35x 35x 29x 29x 29x 29x 12x 17x 17x 18x 18x 29x 29x 58x 29x 29x 29x 29x 4x 69x 126x 126x 110x 11x 11x 11x 11x 67x 57x 67x 11x 67x 11x 67x 40x 67x 67x 40x 67x 40x 67x 57x 67x 57x 67x 40x 67x 40x 40x 82x 28x 21x 21x 28x 11x 11x 29x 1x 1x 1x 29x 2x 3x 2x 1x 2x 2x 3x 2x 2x 3x 3x 3x 3x 2x 1x 2x 1x 2x 1x 2x 1x 1x 1x 1x 7x 6x 1x 1x 2x 2x 1x 1x 1x 3x 1x 5x 3x 1x 2x 1x 2x 2x 1x 1x 2x | import { Overlay, OverlayRef } from '@angular/cdk/overlay';
import { DomPortal, TemplatePortal } from '@angular/cdk/portal';
import { HttpEventType } from '@angular/common/http';
import {
AfterViewInit,
Component,
ElementRef,
EventEmitter,
forwardRef,
HostBinding,
HostListener,
Input,
OnChanges,
OnDestroy,
Output,
SimpleChanges,
TemplateRef,
ViewChild,
ViewContainerRef
} from '@angular/core';
import { FormBuilder, ReactiveFormsModule, UntypedFormArray, UntypedFormControl } from '@angular/forms';
import { NavigationEnd, Router } from '@angular/router';
import Europa from 'europa';
import { debounce, defer, delay, intersection, sortedLastIndex, uniq, without } from 'lodash-es';
import { autorun, IReactionDisposer } from 'mobx';
import { catchError, filter, last, map, Observable, of, Subject, Subscription, switchMap, takeUntil, tap } from 'rxjs';
import { v4 as uuid } from 'uuid';
import { LoadingComponent } from '../../component/loading/loading.component';
import { MdComponent } from '../../component/md/md.component';
import { AutofocusDirective } from '../../directive/autofocus.directive';
import { FillWidthDirective } from '../../directive/fill-width.directive';
import { LimitWidthDirective } from '../../directive/limit-width.directive';
import { Ref } from '../../model/ref';
import { EditorButton, sortOrder } from '../../model/tag';
import { mimeToCode } from '../../mods/media/code';
import { AccountService } from '../../service/account.service';
import { AdminService } from '../../service/admin.service';
import { ProxyService } from '../../service/api/proxy.service';
import { RefService } from '../../service/api/ref.service';
import { TaggingService } from '../../service/api/tagging.service';
import { AuthzService } from '../../service/authz.service';
import { Store } from '../../store/store';
import { readFileAsDataURL, readFileAsString } from '../../util/async';
import { memo, MemoCache } from '../../util/memo';
import { expandedTagsInclude, hasTag, test } from '../../util/tag';
export interface EditorUpload {
id: string;
name: string;
progress: number;
subscription?: Subscription;
completed?: boolean;
error?: string;
ref?: Ref | null;
}
@Component({
selector: 'app-editor',
templateUrl: './editor.component.html',
styleUrls: ['./editor.component.scss'],
host: { 'class': 'editor' },
imports: [
forwardRef(() => MdComponent),
LoadingComponent,
ReactiveFormsModule,
FillWidthDirective,
AutofocusDirective,
LimitWidthDirective,
],
})
export class EditorComponent implements OnChanges, AfterViewInit, OnDestroy {
private destroy$ = new Subject<void>();
private disposers: IReactionDisposer[] = [];
@Input()
id = 'editor-' + uuid();
@HostBinding('class.stacked')
stacked = true;
@HostBinding('class.fullscreen')
fullscreen = false;
@HostBinding('class.help')
help = false;
@HostBinding('class.md-preview')
preview = this.store.local.showPreview;
@ViewChild('helpButton')
helpButton?: ElementRef<HTMLButtonElement>;
@ViewChild('editor')
editor?: ElementRef<HTMLTextAreaElement>;
@ViewChild('md')
md?: MdComponent;
@ViewChild('hiddenMeasure')
hiddenMeasure?: ElementRef<HTMLTextAreaElement>;
@ViewChild('help')
helpTemplate!: TemplateRef<any>;
@ViewChild('ref')
refTemplate!: TemplateRef<any>;
@ViewChild('fileUpload')
fileUpload!: ElementRef<HTMLInputElement>;
@Input()
hasTags = true;
@Input()
selectResponseType = false;
@Input()
tags?: UntypedFormArray;
@Input()
createdTags: string[] = [];
@Input()
control!: UntypedFormControl;
@Input()
autoFocus = false;
@Input()
addButton = false;
@Input()
url = '';
@Input()
addCommentTitle = $localize`Add comment`;
@Input()
addCommentLabel = $localize`+ Add comment`;
@Input()
fillWidth?: HTMLElement;
@Output()
syncEditor = new EventEmitter<string>();
@Output()
syncTags = new EventEmitter<string[]>();
@Output()
addSource = new EventEmitter<string>();
@Output()
scrape = new EventEmitter<void>();
@Output()
uploadCompleted = new EventEmitter<Ref>();
dropping = false;
overlayRef?: OverlayRef;
helpRef?: OverlayRef;
toggleIndex = 0;
initialFullscreen = false;
focused?: boolean = false;
progress = 0;
uploads: EditorUpload[] = [];
files = !!this.admin.getPlugin('plugin/file');
loadingEvents: any = {};
private _text? = '';
private _editing = false;
private _padding = 8;
private europa?: Europa;
private scrollTop = 0;
private scrollTopFullscreen = 0;
private selectionStart = 0;
private selectionEnd = 0;
private blurTimeout = 0;
private scrollMap = new Map<number, number>();
private sourceMap: number[] = [];
constructor(
public admin: AdminService,
private accounts: AccountService,
private auth: AuthzService,
private proxy: ProxyService,
private refs: RefService,
private ts: TaggingService,
public store: Store,
private overlay: Overlay,
private router: Router,
private el: ElementRef,
private vc: ViewContainerRef,
private fb: FormBuilder,
) {
this.router.events.pipe(
filter(event => event instanceof NavigationEnd)
).subscribe(() => this.toggleFullscreen(false));
this.disposers.push(autorun(() => {
this.loadingEvents[this.store.eventBus.event] = false;
}));
}
init() {
MemoCache.clear(this);
Iif (this.selectResponseType && this.responseButtons.length) {
this.toggleIndex = 0;
const tags = this.tags?.value || this.createdTags;
for (const p of this.responseButtons) {
if (hasTag(p.tag, tags)) {
this.toggleIndex = this.responseButtons.indexOf(p);
}
}
}
}
ngAfterViewInit(): void {
this.disposers.push(autorun(() => {
const height = this.store.viewportHeight - 4;
Iif (this.overlayRef) {
this.overlayRef.updateSize({ height });
document.body.style.height = height + 'px';
this.el.nativeElement.style.setProperty('--viewport-height', height + 'px');
}
}));
if (this.tags) {
this.tags.valueChanges.pipe(
takeUntil(this.destroy$),
).subscribe(() => {
this.init();
});
} else {
this.init();
this.updateTags(this.editing ? this.initTags : this.allTags);
}
}
ngOnChanges(changes: SimpleChanges) {
Eif (changes.tags || changes.createdTags || changes.url) {
this.init();
}
}
ngOnDestroy() {
this.destroy$.next();
this.destroy$.complete();
for (const dispose of this.disposers) dispose();
this.disposers.length = 0;
document.body.style.height = '';
document.body.classList.remove('fullscreen');
this.el.nativeElement.style.setProperty('--viewport-height', this.store.viewportHeight + 'px');
}
@Input()
set scraping(value: boolean) {
this.loadingEvents['scrape-done'] = value;
}
@HostListener('window:scroll')
preventScroll() {
if (this.overlayRef) {
window.scrollTo(0, 0);
}
}
onSelect(event?: MouseEvent) {
if (event && !event.button) return;
defer(() => {
this.selectionStart = this.editor?.nativeElement.selectionStart || 0;
this.selectionEnd = this.editor?.nativeElement.selectionEnd || 0;
if (this.selectionEnd > this.selectionStart) {
this.onSelectEditor();
}
});
}
postProcessMarkdown() {
this.sourceMap.length = 0;
this.scrollMap.clear();
this.el.nativeElement.querySelectorAll('[aria-posinset]').forEach((el: HTMLElement) => {
const start = +el.getAttribute('aria-posinset')!;
this.scrollMap.set(start, el.offsetTop);
this.sourceMap.push(start);
});
this.sourceMap.sort((a, b) => a - b);
}
onSelectEditor() {
if (!this.preview || !this.fullscreen || !this.md) return;
const start = this.sourceMap[Math.max(sortedLastIndex(this.sourceMap, this.selectionStart) - 1, 0)];
this.md.el.nativeElement.scrollTop = (this.scrollMap.get(start) ?? 0) - this.md.el.nativeElement.clientHeight / 2;
}
onSelectPreview() {
if (!this.preview || !this.fullscreen || !this.hiddenMeasure || !this.editor) return;
const sel = window.getSelection();
if (!sel || sel.isCollapsed) return;
if (!this.md?.el.nativeElement?.contains(sel.anchorNode)) return;
const anchorEl = (sel.anchorNode as Node).nodeType === Node.ELEMENT_NODE
? sel.anchorNode as HTMLElement
: (sel.anchorNode as Node).parentElement;
const sourceMap = anchorEl!.closest('[aria-posinset]');
if (!sourceMap) return;
const start = +sourceMap.getAttribute('aria-posinset')!;
this.hiddenMeasure.nativeElement.style.width = this.editor.nativeElement.clientWidth + 'px';
this.hiddenMeasure.nativeElement.value = this.currentText.slice(0, start);
this.editor.nativeElement.scrollTop = this.hiddenMeasure.nativeElement.scrollHeight - this.editor.nativeElement.clientHeight / 2;
}
@HostBinding('class.add-button')
get addButtonClass() {
return this.addButton && !this.editing && !this.currentText;
}
@HostBinding('style.padding.px')
get padding(): number {
Iif (this.fullscreen) return 0;
return this._padding + 8;
}
set padding(value: number) {
this._padding = value;
}
get editing(): boolean {
return this._editing;
}
@HostBinding('class.editing')
set editing(value: boolean) {
Eif (!this._editing && value) {
defer(() => {
this._editing = true;
this.updateTags(this.initTags);
});
}
}
@memo
get allTags() {
return uniq([
...without(this.tags ? this.tags.value : this.createdTags, ...this.allResponseTags),
...this.responseTags,
]);
}
@memo
get initTags() {
return [
...without(intersection(this.store.account.defaultEditors(this.editors), this.editorButtons.filter(b => this.visible(b)).map(b => b.toggle!)), ...this.allTags),
...this.allTags,
];
}
@memo
get editors() {
return this.editorButtons.map(p => p?.toggle as string).filter(p => !!p);
}
@memo
get editorButtons(): EditorButton[] {
return sortOrder(this.admin.getEditorButtons(this.allTags, this.scheme)).reverse();
}
@memo
get responseButtons() {
return this.admin.responseButton;
}
@memo
get editorRibbons() {
return sortOrder(this.editorButtons.filter(b => b.ribbon && this.visible(b)).map(b => this.setButtonOn(b)));
}
@memo
get editorPushButtons() {
return sortOrder(this.editorButtons.filter(b => !b.ribbon && this.visible(b)).map(b => this.setButtonOn(b)));
}
@memo
get responseTags() {
Eif (!this.selectResponseType || !this.responseButtons.length) return [];
const p = this.responseButtons[this.toggleIndex];
return p.config?.reply || [p.tag];
}
@memo
get allResponseTags() {
Eif (!this.selectResponseType) return [];
return this.responseButtons.flatMap(p => p.config?.reply || [p.tag]);
}
@memo
get scheme() {
Eif (!this.url) return '';
if (!this.url.includes(':')) return '';
return this.url.substring(0, this.url.indexOf(':') + 1);
}
@memo
get helpLinks() {
const helpConfig = this.admin.getTemplate('config/help');
return helpConfig?.config?.editorHelpLinks || [];
}
get currentText() {
return this._text || this.control?.value || '';
}
updateTags(tags: string[]) {
if (!this.tags) {
this.createdTags = tags;
MemoCache.clear(this);
}
this.syncTags.next(tags);
}
toggleTag(button: EditorButton) {
if (button.event) this.fireEvent(button);
const toggle = button.toggle!;
if (hasTag(toggle, this.allTags)) {
this.updateTags(this.allTags.filter(t => !expandedTagsInclude(t, toggle)));
if (button.remember && this.admin.getTemplate('user')) {
this.accounts.removeConfigArray$('editors', toggle).subscribe();
}
} else if (toggle !== 'locked' || confirm($localize`Locking is permanent once saved. Are you sure you want to lock?`)) {
this.updateTags([...this.allTags, toggle]);
if (button.remember && this.admin.getTemplate('user')) {
this.accounts.addConfigArray$('editors', toggle).subscribe();
}
}
if ('vibrate' in navigator) navigator.vibrate([2, 8, 8]);
if (this.focused !== false) this.editor?.nativeElement.focus();
}
setResponse(tag: string) {
const tags = this.tags?.value || this.createdTags;
if (!hasTag(tag, tags)) {
const responses = this.responseButtons.map(p => p.tag);
this.toggleIndex = responses.indexOf(tag);
this.updateTags([...without(tags, ...responses), tag]);
}
if ('vibrate' in navigator) navigator.vibrate([2, 8, 8]);
if (this.focused !== false) this.editor?.nativeElement.focus();
}
focusText() {
this.focused = true;
Iif (this.blurTimeout) {
clearTimeout(this.blurTimeout);
this.blurTimeout = 0;
}
}
blurText(value: string) {
if (this.focused) {
this.focused = undefined;
this.blurTimeout = delay(() => {
if (this.focused === undefined) this.focused = false;
this.blurTimeout = 0;
}, 400);
}
this.setText(value);
}
setText = debounce((value: string) => {
if (this._text === value) return;
this._text = value;
}, 400, { leading: true, trailing: true, maxWait: 3000 });
syncText(value: string) {
Iif (!value) {
// Do not throttle
this._text = value;
this.syncEditor.next(this._text);
}
// Clear previous throttled values
this.syncTextThrottled(value);
this.control.setValue(value);
}
syncTextThrottled = debounce((value: string) => {
if (this._text === value) return;
this._text = value;
this.syncEditor.next(this._text);
}, 400);
togglePreview() {
if (this.fullscreen) {
this.store.local.showFullscreenPreview = this.preview = !this.preview;
} else {
this.store.local.showPreview = this.preview = !this.preview;
}
if (this.focused !== false) this.editor?.nativeElement.focus();
}
toggleStacked() {
if (this.stacked) {
if (this.preview) {
this.store.local.showFullscreenPreview = this.preview = false;
} else {
this.store.local.showFullscreenPreview = this.preview = true;
this.store.local.editorStacked = this.stacked = false;
}
} else {
this.store.local.editorStacked = this.stacked = true;
}
if (this.focused !== false) this.editor?.nativeElement.focus();
}
toggleFullscreen(override?: boolean) {
if (!this.editor) return;
if (override === this.fullscreen) return;
this.initialFullscreen = true;
this.fullscreen = override !== undefined ? override : !this.fullscreen;
this.focused ||= this.focused === undefined || this.fullscreen;
if (this.fullscreen) {
document.documentElement.style.overflowY = 'auto';
this._text = this.currentText;
this.stacked = this.store.local.editorStacked;
this.preview = this.store.local.showFullscreenPreview;
this.scrollTop = this.editor.nativeElement.scrollTop;
let height = 'calc(100vh - 4px)';
if (window.visualViewport?.height) {
height = (window.visualViewport.height - 4) + 'px';
document.body.style.height = height;
this.el.nativeElement.style.setProperty('--viewport-height', height);
}
document.body.classList.add('fullscreen');
this.overlayRef = this.overlay.create({
height,
width: '100vw',
positionStrategy: this.overlay.position()
.global()
.centerHorizontally()
.top('0'),
hasBackdrop: true,
scrollStrategy: this.overlay.scrollStrategies.block(),
});
this.overlayRef.attach(new DomPortal(this.el));
this.overlayRef.backdropClick().subscribe(() => this.toggleFullscreen(false));
this.overlayRef.keydownEvents().subscribe(event => event.key === 'Escape' && this.toggleFullscreen(false));
this.editor.nativeElement.scrollIntoView({ block: 'end' });
this.editor.nativeElement.focus();
this.editor.nativeElement.setSelectionRange(this.selectionStart, this.selectionEnd);
this.editor.nativeElement.scrollTop = this.scrollTopFullscreen;
} else {
document.documentElement.style.overflowY = 'scroll';
this.stacked = true;
this.preview = this.store.local.showPreview;
this.scrollTopFullscreen = this.editor.nativeElement.scrollTop;
this.overlayRef?.detach();
this.overlayRef?.dispose();
delete this.overlayRef;
document.body.style.height = '';
this.el.nativeElement.style.setProperty('--viewport-height', this.store.viewportHeight + 'px');
document.body.classList.remove('fullscreen');
this.editor.nativeElement.scrollIntoView({ block: 'center', inline: 'center' });
if (this.focused) {
this.editor.nativeElement.focus();
this.editor.nativeElement.setSelectionRange(this.selectionStart, this.selectionEnd);
this.editor.nativeElement.scrollTop = this.scrollTop;
}
}
}
toggleHelp(override?: boolean) {
this.help = override !== undefined ? override : !this.help;
if (this.help) {
const positionStrategy = this.overlay.position()
.flexibleConnectedTo(this.helpButton!)
.withPositions([{
originX: 'start',
originY: 'bottom',
overlayX: 'start',
overlayY: 'top',
}]);
this.helpRef = this.overlay.create({
hasBackdrop: true,
backdropClass: 'hide',
positionStrategy,
scrollStrategy: this.overlay.scrollStrategies.close()
});
this.helpRef.attach(new TemplatePortal(this.helpTemplate, this.vc));
this.helpRef.backdropClick().subscribe(() => this.toggleHelp(false));
} else {
this.helpRef?.detach();
this.helpRef?.dispose();
}
}
private visible(button: EditorButton) {
if (button.scheme && button.scheme !== this.scheme) return false;
if (button.toggle && !this.auth.canAddTag(button.toggle)) return false;
if (button.global) return true;
return test(button.query || button._parent!.tag, this.allTags);
}
fireEvent(button: EditorButton) {
const event = button.event!;
if (button.eventDone) this.loadingEvents[button.eventDone] = true;
if (event === 'html-to-markdown') {
this.europa ||= new Europa({
absolute: !!this.url,
baseUri: this.url,
inline: true,
});
const md = this.europa.convert(this.editor!.nativeElement.value);
this.syncText(md);
} else if (event === 'scrape') {
this.scrape.emit();
} else if (event === 'attach') {
this.fileUpload.nativeElement.click();
} else {
this.store.eventBus.fire(event);
}
if (this.focused !== false) this.editor?.nativeElement.focus();
}
addComment() {
this.editing = true;
defer(() => this.editor?.nativeElement?.focus());
}
private setButtonOn(b: EditorButton) {
b._on = !!b.toggle && hasTag(b.toggle, this.allTags);
return b;
}
drop(event: Event, items?: DataTransferItemList) {
this.dropping = false;
if (!this.admin.getPlugin('plugin/file')) return;
if (!items) return;
const files = [] as any;
for (let i = 0; i < items.length; i++) {
const d = items[i];
if (d?.kind == 'file') {
files.push(d.getAsFile());
}
}
if (!files.length) return;
event.preventDefault();
event.stopPropagation();
this.upload(files);
}
upload(files?: FileList | null) {
Iif (!files) return;
const hasActiveUploads = this.uploads.some(upload => !upload.completed && !upload.error);
if (!hasActiveUploads) {
// Only clear uploads if no active uploads exist
this.uploads = [];
}
this.control.disable();
const fileArray = Array.from(files);
const fileUploads: EditorUpload[] = fileArray.map(file => ({
id: uuid(),
name: file.name,
progress: 0
}));
this.uploads = [...this.uploads, ...fileUploads];
fileArray.map((file, index) => {
const upload = fileUploads[index];
return upload.subscription = this.upload$(file, upload).subscribe(ref => {
Iif (ref && !ref.url.startsWith('data:')) {
upload.completed = true;
upload.progress = 100;
upload.ref = ref;
// Emit upload completion so parent can tag it
this.uploadCompleted.emit(ref);
}
this.checkAllUploadsComplete();
});
});
}
upload$(file: File, upload: EditorUpload): Observable<Ref | null> {
const codeType = mimeToCode(file.type);
if (codeType.length) {
const ref = {
origin: this.store.account.origin,
url: 'internal:' + uuid(),
title: file.name,
// Upload as private - only localTag and internal, no visibility tags
tags: uniq([
this.store.account.localTag,
'internal',
...file.type === 'text/markdown' ? [] : codeType
])
};
upload.progress = 50; // Simulate progress for text files
return readFileAsString(file).pipe(
switchMap(contents => this.refs.create({
...ref,
comment: contents,
})),
map(cursor => ref),
tap(() => upload.progress = 100),
catchError(err => {
upload.error = err.message || 'Upload failed';
upload.progress = 0;
return readFileAsDataURL(file).pipe(map(url => ({ ...ref, url }))); // base64
}),
);
} else {
// Upload binary files as private - only plugin/file and type-specific tags
const tags: string[] = ['plugin/file'];
if (file.type.startsWith('audio/') && this.admin.getPlugin('plugin/audio')) {
tags.push('plugin/audio');
} else if (file.type.startsWith('video/') && this.admin.getPlugin('plugin/video')) {
tags.push('plugin/video', 'plugin/thumbnail');
} else if (file.type.startsWith('image/') && this.admin.getPlugin('plugin/image')) {
tags.push('plugin/image', 'plugin/thumbnail');
} else if (file.type.startsWith('application/pdf') && this.admin.getPlugin('plugin/pdf')) {
tags.push('plugin/pdf');
}
return this.proxy.save(file, this.store.account.origin).pipe(
map(event => {
switch (event.type) {
case HttpEventType.Response:
return event.body;
case HttpEventType.UploadProgress:
const percentDone = event.total ? Math.round(100 * event.loaded / event.total) : 0;
this.progress = percentDone;
upload.progress = percentDone;
return null;
}
return null;
}),
last(),
switchMap(ref => !ref ? of(ref) : this.ts.patch(tags, ref.url, ref.origin).pipe(
map(cursor => ({ ...ref, tags: uniq([...ref?.tags || [], ...tags]) })),
)),
catchError(err => {
upload.error = err.message || 'Upload failed';
upload.progress = 0;
return readFileAsDataURL(file).pipe(map(url => ({url, tags}))); // base64
}),
);
}
}
attachUrls(...refs: (Ref | null)[]) {
refs = refs.filter(u => !!u);
Iif (!refs.length) return;
for (const ref of refs) this.addSource.next(ref!.url);
const text = this.currentText;
const embed = (ref: Ref) => hasTag('plugin/audio', ref) || hasTag('plugin/video', ref) || hasTag('plugin/image', ref) || hasTag('plugin/pdf', ref);
Iif (refs.length === 1) {
if (!refs[0]) return;
const encodedUrl = (this.selectionStart !== this.selectionEnd ? '[' + text.substring(this.selectionStart, this.selectionEnd) + ']'
: embed(refs[0]) ? '![]' : '![=]'
) + '(' + refs[0].url.replace(')', '\\)') + ')\n';
if (this.selectionStart || this.selectionStart !== this.selectionEnd) {
this.syncText(text.substring(0, this.selectionStart) + encodedUrl + text.substring(this.selectionEnd));
} else {
this.syncText(text + encodedUrl + '\n');
}
} else {
const encodedUrls = refs.map(ref => (embed(ref!) ? '![]' : '![=]') + '(' + ref!.url.replace(')', '\\)') + ')\n').join('');
this.syncText(text.substring(0, this.selectionStart) + encodedUrls + text.substring(this.selectionStart));
Eif (!text) this.preview = true;
}
Eif (!text) this.preview = true;
Iif (this.focused !== false) this.editor?.nativeElement.focus();
}
checkAllUploadsComplete() {
const allComplete = this.uploads.every(upload => upload.completed || upload.error);
if (allComplete && this.uploads.length > 0) {
this.control.enable();
const completedRefs = this.uploads
.filter(upload => upload.completed && upload.ref)
.map(upload => upload.ref!);
Eif (completedRefs.length > 0) {
this.attachUrls(...completedRefs);
}
this.uploads = [];
}
}
cancelUpload(upload: EditorUpload) {
if (upload.subscription) {
upload.subscription.unsubscribe();
}
this.uploads = this.uploads.filter(u => u.id !== upload.id);
if (this.uploads.length === 0) {
this.control.enable();
} else {
this.checkAllUploadsComplete();
}
}
cancelAllUploads() {
this.uploads.forEach(upload => {
Eif (upload.subscription) {
upload.subscription.unsubscribe();
}
});
this.uploads = [];
this.control.enable();
}
dragLeave(parent: HTMLElement, target: HTMLElement) {
if (this.dropping && parent === target || !parent.contains(target)) {
this.dropping = false;
}
}
hasActiveUploads(): boolean {
return this.uploads.some(upload => !upload.completed && !upload.error);
}
}
|