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
|
import { IconProp } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { Tooltip } from '@material-ui/core';
import { action, computed, observable, reaction } from 'mobx';
import { observer } from 'mobx-react';
import { DateField } from '../../fields/DateField';
import { AclAdmin, AclEdit, DataSym, Doc, DocListCast, Field, HeightSym, WidthSym } from '../../fields/Doc';
import { Document } from '../../fields/documentSchemas';
import { InkField } from '../../fields/InkField';
import { ScriptField } from '../../fields/ScriptField';
import { Cast, NumCast, StrCast } from '../../fields/Types';
import { GetEffectiveAcl } from '../../fields/util';
import { emptyFunction, numberValue, returnFalse, setupMoveUpEvents } from '../../Utils';
import { Docs } from '../documents/Documents';
import { DocumentType } from '../documents/DocumentTypes';
import { DragManager } from '../util/DragManager';
import { SelectionManager } from '../util/SelectionManager';
import { SnappingManager } from '../util/SnappingManager';
import { undoBatch, UndoManager } from '../util/UndoManager';
import { CollectionDockingView } from './collections/CollectionDockingView';
import { CollectionFreeFormView } from './collections/collectionFreeForm';
import { DocumentButtonBar } from './DocumentButtonBar';
import './DocumentDecorations.scss';
import { Colors } from './global/globalEnums';
import { InkingStroke } from './InkingStroke';
import { InkStrokeProperties } from './InkStrokeProperties';
import { LightboxView } from './LightboxView';
import { DocumentView } from './nodes/DocumentView';
import { FormattedTextBox } from './nodes/formattedText/FormattedTextBox';
import { ImageBox } from './nodes/ImageBox';
import React = require('react');
@observer
export class DocumentDecorations extends React.Component<{ PanelWidth: number; PanelHeight: number; boundsLeft: number; boundsTop: number }, { value: string }> {
static Instance: DocumentDecorations;
private _resizeHdlId = '';
private _keyinput = React.createRef<HTMLInputElement>();
private _resizeBorderWidth = 16;
private _linkBoxHeight = 20 + 3; // link button height + margin
private _titleHeight = 20;
private _resizeUndo?: UndoManager.Batch;
private _offX = 0;
_offY = 0; // offset from click pt to inner edge of resize border
private _snapX = 0;
_snapY = 0; // last snapped location of resize border
private _dragHeights = new Map<Doc, { start: number; lowest: number }>();
private _inkDragDocs: { doc: Doc; x: number; y: number; width: number; height: number }[] = [];
@observable private _accumulatedTitle = '';
@observable private _titleControlString: string = '#title';
@observable private _editingTitle = false;
@observable private _hidden = false;
@observable public AddToSelection = false; // if Shift is pressed, then this should be set so that clicking on the selection background is ignored so overlapped documents can be added to the selection set.
@observable public Interacting = false;
@observable public pushIcon: IconProp = 'arrow-alt-circle-up';
@observable public pullIcon: IconProp = 'arrow-alt-circle-down';
@observable public pullColor: string = 'white';
@observable private _isRotating: boolean = false;
@observable private _isRounding: boolean = false;
@observable private _isResizing: boolean = false;
constructor(props: any) {
super(props);
DocumentDecorations.Instance = this;
reaction(
() => SelectionManager.Views().slice(),
action(docs => (this._editingTitle = false))
);
}
@computed
get Bounds() {
const views = SelectionManager.Views();
return views
.filter(dv => dv.props.renderDepth > 0)
.map(dv => dv.getBounds())
.reduce(
(bounds, rect) =>
!rect
? bounds
: {
x: Math.min(rect.left, bounds.x),
y: Math.min(rect.top, bounds.y),
r: Math.max(rect.right, bounds.r),
b: Math.max(rect.bottom, bounds.b),
c: views.length === 1 ? rect.center : undefined,
},
{ x: Number.MAX_VALUE, y: Number.MAX_VALUE, r: Number.MIN_VALUE, b: Number.MIN_VALUE, c: undefined as { X: number; Y: number } | undefined }
);
}
@action
titleBlur = () => {
this._editingTitle = false;
if (this._accumulatedTitle.startsWith('#') || this._accumulatedTitle.startsWith('=')) {
this._titleControlString = this._accumulatedTitle;
} else if (this._titleControlString.startsWith('#')) {
const titleFieldKey = this._titleControlString.substring(1);
UndoManager.RunInBatch(
() =>
titleFieldKey &&
SelectionManager.Views().forEach(d => {
if (titleFieldKey === 'title') {
d.dataDoc['title-custom'] = !this._accumulatedTitle.startsWith('-');
if (StrCast(d.rootDoc.title).startsWith('@') && !this._accumulatedTitle.startsWith('@')) {
Doc.RemoveDocFromList(Doc.MyPublishedDocs, undefined, d.rootDoc);
}
if (!StrCast(d.rootDoc.title).startsWith('@') && this._accumulatedTitle.startsWith('@')) {
Doc.AddDocToList(Doc.MyPublishedDocs, undefined, d.rootDoc);
}
}
//@ts-ignore
const titleField = +this._accumulatedTitle === this._accumulatedTitle ? +this._accumulatedTitle : this._accumulatedTitle;
Doc.SetInPlace(d.rootDoc, titleFieldKey, titleField, true);
if (d.rootDoc.syncLayoutFieldWithTitle) {
const title = titleField.toString();
const curKey = Doc.LayoutFieldKey(d.rootDoc);
if (curKey !== title && d.dataDoc[title] === undefined) {
d.rootDoc.layout = FormattedTextBox.LayoutString(title);
setTimeout(() => {
const val = d.dataDoc[curKey];
d.dataDoc[curKey] = undefined;
d.dataDoc[title] = val;
});
}
}
}),
'title blur'
);
}
};
titleEntered = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
e.stopPropagation();
(e.target as any).blur();
}
};
@action onTitleDown = (e: React.PointerEvent): void => {
setupMoveUpEvents(
this,
e,
e => this.onBackgroundMove(true, e),
e => {},
action(e => {
!this._editingTitle && (this._accumulatedTitle = this._titleControlString.startsWith('#') ? this.selectionTitle : this._titleControlString);
this._editingTitle = true;
this._keyinput.current && setTimeout(this._keyinput.current.focus);
})
);
};
onBackgroundDown = (e: React.PointerEvent) => setupMoveUpEvents(this, e, e => this.onBackgroundMove(false, e), emptyFunction, emptyFunction);
@action
onBackgroundMove = (dragTitle: boolean, e: PointerEvent): boolean => {
const dragDocView = SelectionManager.Views()[0];
const { left, top } = dragDocView.getBounds() || { left: 0, top: 0 };
const dragData = new DragManager.DocumentDragData(
SelectionManager.Views().map(dv => dv.props.Document),
dragDocView.props.dropAction
);
dragData.offset = dragDocView.props.ScreenToLocalTransform().transformDirection(e.x - left, e.y - top);
dragData.moveDocument = dragDocView.props.moveDocument;
dragData.isDocDecorationMove = true;
dragData.canEmbed = dragTitle;
this._hidden = this.Interacting = true;
DragManager.StartDocumentDrag(
SelectionManager.Views().map(dv => dv.ContentDiv!),
dragData,
e.x,
e.y,
{
dragComplete: action(e => {
dragData.canEmbed && SelectionManager.DeselectAll();
this._hidden = this.Interacting = false;
}),
hideSource: true,
}
);
return true;
};
_deleteAfterIconify = false;
_iconifyBatch: UndoManager.Batch | undefined;
onCloseClick = (forceDeleteOrIconify: boolean | undefined) => {
const views = SelectionManager.Views()
.slice()
.filter(v => v);
if (forceDeleteOrIconify === false && this._iconifyBatch) return;
this._deleteAfterIconify = forceDeleteOrIconify || this._iconifyBatch ? true : false;
if (!this._iconifyBatch) {
this._iconifyBatch = UndoManager.StartBatch('iconifying');
} else {
forceDeleteOrIconify = false; // can't force immediate close in the middle of iconifying -- have to wait until iconifying completes
}
var iconifyingCount = views.length;
const finished = action((force?: boolean) => {
if ((force || --iconifyingCount === 0) && this._iconifyBatch) {
if (this._deleteAfterIconify) {
views.forEach(iconView => iconView.props.removeDocument?.(iconView.props.Document));
SelectionManager.DeselectAll();
}
this._iconifyBatch?.end();
this._iconifyBatch = undefined;
}
});
if (forceDeleteOrIconify) finished(forceDeleteOrIconify);
else if (!this._deleteAfterIconify) views.forEach(dv => dv.iconify(finished));
};
onMaximizeDown = (e: React.PointerEvent) => {
setupMoveUpEvents(
this,
e,
() => {
DragManager.StartWindowDrag?.(e, [SelectionManager.Views().slice(-1)[0].rootDoc]);
return true;
},
emptyFunction,
this.onMaximizeClick,
false,
false
);
};
onMaximizeClick = (e: any): void => {
const selectedDocs = SelectionManager.Views();
if (selectedDocs.length) {
if (e.ctrlKey) {
// open an alias in a new tab with Ctrl Key
const bestAlias = DocListCast(selectedDocs[0].props.Document.aliases).find(doc => !doc.context && doc.author === Doc.CurrentUserEmail);
CollectionDockingView.AddSplit(bestAlias ?? Doc.MakeAlias(selectedDocs[0].props.Document), 'right');
} else if (e.shiftKey) {
// open centered in a new workspace with Shift Key
const alias = Doc.MakeAlias(selectedDocs[0].props.Document);
alias.context = undefined;
alias.x = -alias[WidthSym]() / 2;
alias.y = -alias[HeightSym]() / 2;
CollectionDockingView.AddSplit(Docs.Create.FreeformDocument([alias], { title: 'Tab for ' + alias.title }), 'right');
} else if (e.altKey) {
// open same document in new tab
CollectionDockingView.ToggleSplit(selectedDocs[0].props.Document, 'right');
} else {
var openDoc = selectedDocs[0].props.Document;
if (openDoc.layoutKey === 'layout_icon') {
openDoc = DocListCast(openDoc.aliases).find(alias => !alias.context) ?? Doc.MakeAlias(openDoc);
Doc.deiconifyView(openDoc);
}
LightboxView.SetLightboxDoc(
openDoc,
undefined,
selectedDocs.slice(1).map(view => view.props.Document)
);
}
}
SelectionManager.DeselectAll();
};
onIconifyClick = (): void => {
SelectionManager.Views().forEach(dv => dv?.iconify());
SelectionManager.DeselectAll();
};
onSelectorClick = () => SelectionManager.Views()?.[0]?.props.ContainingCollectionView?.props.select(false);
/**
* Handles setting up events when user clicks on the border radius editor
* @param e PointerEvent
*/
@action
onRadiusDown = (e: React.PointerEvent): void => {
this._isRounding = true;
this._resizeUndo = UndoManager.StartBatch('DocDecs set radius');
// Call util move event function
setupMoveUpEvents(
this, // target
e, // pointerEvent
(e, down) => {
const x = this.Bounds.x + 3;
const y = this.Bounds.y + 3;
const maxDist = Math.min((this.Bounds.r - this.Bounds.x) / 2, (this.Bounds.b - this.Bounds.y) / 2);
let dist = Math.sqrt((e.clientX - x) * (e.clientX - x) + (e.clientY - y) * (e.clientY - y));
if (e.clientX < x && e.clientY < y) dist = 0;
SelectionManager.Views()
.map(dv => dv.props.Document)
.map(doc => {
const docMax = Math.min(NumCast(doc.width) / 2, NumCast(doc.height) / 2);
const ratio = dist / maxDist;
const radius = Math.min(1, ratio) * docMax;
doc.borderRounding = `${radius}px`;
});
return false;
}, // moveEvent
action(e => {
this._isRounding = false;
this._resizeUndo?.end();
}), // upEvent
e => {} // clickEvent
);
};
@action
onRotateDown = (e: React.PointerEvent): void => {
this._isRotating = true;
const rotateUndo = UndoManager.StartBatch('rotatedown');
const selectedInk = SelectionManager.Views().filter(i => i.ComponentView instanceof InkingStroke);
const centerPoint = { X: (this.Bounds.x + this.Bounds.r) / 2, Y: (this.Bounds.y + this.Bounds.b) / 2 };
setupMoveUpEvents(
this,
e,
(e: PointerEvent, down: number[], delta: number[]) => {
const previousPoint = { X: e.clientX, Y: e.clientY };
const movedPoint = { X: e.clientX - delta[0], Y: e.clientY - delta[1] };
const angle = InkStrokeProperties.angleChange(previousPoint, movedPoint, centerPoint);
if (selectedInk.length) {
angle && InkStrokeProperties.Instance.rotateInk(selectedInk, -angle, centerPoint);
} else {
SelectionManager.Views().forEach(dv => {
const oldRotation = NumCast(dv.rootDoc._jitterRotation);
// Rotation between -360 and 360
let newRotation = (oldRotation - (angle * 180) / Math.PI) % 360;
const diff = Math.round(newRotation / 45) - newRotation / 45;
if (diff < 0.05) {
console.log('show lines');
}
dv.rootDoc._jitterRotation = newRotation;
});
}
return false;
}, // moveEvent
action(() => {
SelectionManager.Views().forEach(dv => {
const oldRotation = NumCast(dv.rootDoc._jitterRotation);
const diff = Math.round(oldRotation / 45) - oldRotation / 45;
if (diff < 0.05) {
let newRotation = Math.round(oldRotation / 45) * 45;
dv.rootDoc._jitterRotation = newRotation;
}
});
this._isRotating = false;
rotateUndo?.end();
UndoManager.FilterBatches(['data', 'x', 'y', 'width', 'height']);
}), // upEvent
emptyFunction
);
};
@action
onPointerDown = (e: React.PointerEvent): void => {
DragManager.docsBeingDragged = SelectionManager.Views().map(dv => dv.rootDoc);
this._inkDragDocs = DragManager.docsBeingDragged
.filter(doc => doc.type === DocumentType.INK)
.map(doc => {
if (InkStrokeProperties.Instance._lock) {
Doc.SetNativeHeight(doc, NumCast(doc._height));
Doc.SetNativeWidth(doc, NumCast(doc._width));
}
return { doc, x: NumCast(doc.x), y: NumCast(doc.y), width: NumCast(doc._width), height: NumCast(doc._height) };
});
setupMoveUpEvents(this, e, this.onPointerMove, this.onPointerUp, emptyFunction);
this.Interacting = true; // turns off pointer events on things like youtube videos and web pages so that dragging doesn't get "stuck" when cursor moves over them
this._resizeHdlId = e.currentTarget.className;
const bounds = e.currentTarget.getBoundingClientRect();
this._offX = this._resizeHdlId.toLowerCase().includes('left') ? bounds.right - e.clientX : bounds.left - e.clientX;
this._offY = this._resizeHdlId.toLowerCase().includes('top') ? bounds.bottom - e.clientY : bounds.top - e.clientY;
this._resizeUndo = UndoManager.StartBatch('DocDecs resize');
this._snapX = e.pageX;
this._snapY = e.pageY;
const ffviewSet = new Set<CollectionFreeFormView>();
SelectionManager.Views().forEach(docView => {
const ffview = docView.props.CollectionFreeFormDocumentView?.().props.CollectionFreeFormView;
ffview && ffviewSet.add(ffview);
this._dragHeights.set(docView.layoutDoc, { start: NumCast(docView.rootDoc._height), lowest: NumCast(docView.rootDoc._height) });
});
Array.from(ffviewSet).map(ffview => ffview.setupDragLines(false));
};
onPointerMove = (e: PointerEvent, down: number[], move: number[]): boolean => {
const first = SelectionManager.Views()[0];
if (!first) return false;
let thisPt = { x: e.clientX - this._offX, y: e.clientY - this._offY };
var fixedAspect = Doc.NativeAspect(first.layoutDoc);
InkStrokeProperties.Instance._lock &&
SelectionManager.Views()
.filter(dv => dv.rootDoc.type === DocumentType.INK)
.forEach(dv => (fixedAspect = Doc.NativeAspect(dv.rootDoc)));
const resizeHdl = this._resizeHdlId.split(' ')[0];
if (fixedAspect && (resizeHdl === 'documentDecorations-bottomRightResizer' || resizeHdl === 'documentDecorations-topLeftResizer')) {
// need to generalize for bl and tr drag handles
const project = (p: number[], a: number[], b: number[]) => {
const atob = [b[0] - a[0], b[1] - a[1]];
const atop = [p[0] - a[0], p[1] - a[1]];
const len = atob[0] * atob[0] + atob[1] * atob[1];
let dot = atop[0] * atob[0] + atop[1] * atob[1];
const t = dot / len;
dot = (b[0] - a[0]) * (p[1] - a[1]) - (b[1] - a[1]) * (p[0] - a[0]);
return [a[0] + atob[0] * t, a[1] + atob[1] * t];
};
const tl = first.props.ScreenToLocalTransform().inverse().transformPoint(0, 0);
const drag = project([e.clientX + this._offX, e.clientY + this._offY], tl, [tl[0] + fixedAspect, tl[1] + 1]);
thisPt = DragManager.snapDragAspect(drag, fixedAspect);
} else {
thisPt = DragManager.snapDrag(e, -this._offX, -this._offY, this._offX, this._offY);
}
move[0] = thisPt.x - this._snapX;
move[1] = thisPt.y - this._snapY;
this._snapX = thisPt.x;
this._snapY = thisPt.y;
let dragBottom = false,
dragRight = false,
dragBotRight = false,
dragTop = false;
let dX = 0,
dY = 0,
dW = 0,
dH = 0;
switch (this._resizeHdlId.split(' ')[0]) {
case '':
break;
case 'documentDecorations-topLeftResizer':
dX = -1;
dY = -1;
dW = -move[0];
dH = -move[1];
break;
case 'documentDecorations-topRightResizer':
dW = move[0];
dY = -1;
dH = -move[1];
break;
case 'documentDecorations-topResizer':
dY = -1;
dH = -move[1];
dragTop = true;
break;
case 'documentDecorations-bottomLeftResizer':
dX = -1;
dW = -move[0];
dH = move[1];
break;
case 'documentDecorations-bottomRightResizer':
dW = move[0];
dH = move[1];
dragBotRight = true;
break;
case 'documentDecorations-bottomResizer':
dH = move[1];
dragBottom = true;
break;
case 'documentDecorations-leftResizer':
dX = -1;
dW = -move[0];
break;
case 'documentDecorations-rightResizer':
dW = move[0];
dragRight = true;
break;
}
SelectionManager.Views().forEach(
action((docView: DocumentView) => {
if (e.ctrlKey && !Doc.NativeHeight(docView.props.Document)) docView.toggleNativeDimensions();
if (dX !== 0 || dY !== 0 || dW !== 0 || dH !== 0) {
const doc = Document(docView.rootDoc);
const nwidth = docView.nativeWidth;
const nheight = docView.nativeHeight;
let docheight = doc._height || 0;
let docwidth = doc._width || 0;
const width = docwidth;
let height = docheight || (nheight / nwidth) * width;
height = !height || isNaN(height) ? 20 : height;
const scale = docView.props.ScreenToLocalTransform().Scale;
const modifyNativeDim = (e.ctrlKey || doc.forceReflow) && doc.nativeDimModifiable && ((!dragBottom && !dragTop) || e.ctrlKey || doc.nativeHeightUnfrozen);
if (nwidth && nheight) {
if (nwidth / nheight !== width / height && !dragBottom && !dragTop) {
height = (nheight / nwidth) * width;
}
if (modifyNativeDim && !dragBottom && !dragTop) {
// ctrl key enables modification of the nativeWidth or nativeHeight durin the interaction
if (Math.abs(dW) > Math.abs(dH)) dH = (dW * nheight) / nwidth;
else dW = (dH * nwidth) / nheight;
}
}
let actualdW = Math.max(width + dW * scale, 20);
let actualdH = Math.max(height + dH * scale, 20);
const fixedAspect = nwidth && nheight && (!doc._fitWidth || e.ctrlKey || doc.nativeHeightUnfrozen);
console.log(fixedAspect);
if (fixedAspect) {
if ((Math.abs(dW) > Math.abs(dH) && ((!dragBottom && !dragTop) || !modifyNativeDim)) || dragRight) {
if (dragRight && modifyNativeDim) {
if (Doc.NativeWidth(doc)) {
doc._nativeWidth = (actualdW / (doc._width || 1)) * Doc.NativeWidth(doc);
}
} else {
if (!doc._fitWidth) {
actualdH = (nheight / nwidth) * actualdW;
doc._height = actualdH;
} else if (!modifyNativeDim || dragBotRight) doc._height = actualdH;
}
doc._width = actualdW;
} else {
if ((dragBottom || dragTop) && (modifyNativeDim || (docView.layoutDoc.nativeHeightUnfrozen && docView.layoutDoc._fitWidth))) {
// frozen web pages, PDFs, and some RTFS have frozen nativewidth/height. But they are marked to allow their nativeHeight to be explicitly modified with fitWidth and vertical resizing. (ie, with fitWidth they can't grow horizontally to match a vertical resize so it makes more sense to change their nativeheight even if the ctrl key isn't used)
doc._nativeHeight = (actualdH / (doc._height || 1)) * Doc.NativeHeight(doc);
doc._autoHeight = false;
} else {
if (!doc._fitWidth) {
actualdW = (nwidth / nheight) * actualdH;
doc._width = actualdW;
} else if (!modifyNativeDim || dragBotRight) doc._width = actualdW;
}
if (!modifyNativeDim) {
actualdH = Math.min((nheight / nwidth) * NumCast(doc._width), actualdH);
doc._height = actualdH;
} else doc._height = actualdH;
}
} else {
const maxHeight = 0; //Math.max(nheight, NumCast(doc.scrollHeight, NumCast(doc[docView.LayoutFieldKey + '-scrollHeight']))) * docView.NativeDimScaling();
dH && (doc._height = actualdH > maxHeight && maxHeight ? maxHeight : actualdH);
dW && (doc._width = actualdW);
dH && (doc._autoHeight = false);
}
doc.x = (doc.x || 0) + dX * (actualdW - docwidth);
doc.y = (doc.y || 0) + (dragBottom ? 0 : dY * (actualdH - docheight));
doc._lastModified = new DateField();
}
const val = this._dragHeights.get(docView.layoutDoc);
if (val) this._dragHeights.set(docView.layoutDoc, { start: val.start, lowest: Math.min(val.lowest, NumCast(docView.layoutDoc._height)) });
})
);
return false;
};
@action
onPointerUp = (e: PointerEvent): void => {
this._resizeHdlId = '';
this.Interacting = false;
this._resizeUndo?.end();
SnappingManager.clearSnapLines();
// detect autoHeight gesture and apply
SelectionManager.Views()
.map(docView => ({ doc: docView.layoutDoc, hgts: this._dragHeights.get(docView.layoutDoc) }))
.filter(pair => pair.hgts && pair.hgts.lowest < pair.hgts.start && pair.hgts.lowest <= 20)
.forEach(pair => (pair.doc._autoHeight = true));
//need to change points for resize, or else rotation/control points will fail.
this._inkDragDocs
.map(oldbds => ({ oldbds, inkPts: Cast(oldbds.doc.data, InkField)?.inkData || [] }))
.forEach(({ oldbds: { doc, x, y, width, height }, inkPts }) => {
Doc.GetProto(doc).data = new InkField(
inkPts.map(
(
ipt // (new x — oldx) + newWidth * (oldxpoint /oldWidth)
) => ({
X: NumCast(doc.x) - x + (NumCast(doc.width) * ipt.X) / width,
Y: NumCast(doc.y) - y + (NumCast(doc.height) * ipt.Y) / height,
})
)
);
Doc.SetNativeWidth(doc, undefined);
Doc.SetNativeHeight(doc, undefined);
});
};
@computed
get selectionTitle(): string {
if (SelectionManager.Views().length === 1) {
const selected = SelectionManager.Views()[0];
if (selected.ComponentView?.getTitle?.()) {
return selected.ComponentView.getTitle();
}
if (this._titleControlString.startsWith('=')) {
return ScriptField.MakeFunction(this._titleControlString.substring(1), { doc: Doc.name })!.script.run({ self: selected.rootDoc, this: selected.layoutDoc }, console.log).result?.toString() || '';
}
if (this._titleControlString.startsWith('#')) {
return Field.toString(selected.props.Document[this._titleControlString.substring(1)] as Field) || '-unset-';
}
return this._accumulatedTitle;
}
return SelectionManager.Views().length > 1 ? '-multiple-' : '-unset-';
}
@computed get hasIcons() {
return SelectionManager.Views().some(docView => docView.rootDoc.layoutKey === 'layout_icon');
}
render() {
const bounds = this.Bounds;
const seldoc = SelectionManager.Views().slice(-1)[0];
if (SnappingManager.GetIsDragging() || bounds.r - bounds.x < 1 || bounds.x === Number.MAX_VALUE || !seldoc || this._hidden || isNaN(bounds.r) || isNaN(bounds.b) || isNaN(bounds.x) || isNaN(bounds.y)) {
return null;
}
// hide the decorations if the parent chooses to hide it or if the document itself hides it
const hideResizers = seldoc.props.hideResizeHandles || seldoc.rootDoc.hideResizeHandles || seldoc.rootDoc._isGroup || this._isRounding || this._isRotating;
const hideTitle = seldoc.props.hideDecorationTitle || seldoc.rootDoc.hideDecorationTitle || this._isRounding || this._isRotating;
const hideDocumentButtonBar = seldoc.props.hideDocumentButtonBar || seldoc.rootDoc.hideDocumentButtonBar || this._isRounding || this._isRotating;
// if multiple documents have been opened at the same time, then don't show open button
const hideOpenButton =
seldoc.props.hideOpenButton ||
seldoc.rootDoc.hideOpenButton ||
SelectionManager.Views().some(docView => docView.props.Document._stayInCollection || docView.props.Document.isGroup || docView.props.Document.hideOpenButton) ||
this._isRounding ||
this._isRotating;
const hideDeleteButton =
this._isRounding ||
this._isRotating ||
seldoc.props.hideDeleteButton ||
seldoc.rootDoc.hideDeleteButton ||
SelectionManager.Views().some(docView => {
const collectionAcl = docView.props.ContainingCollectionView ? GetEffectiveAcl(docView.props.ContainingCollectionDoc?.[DataSym]) : AclEdit;
return docView.rootDoc.stayInCollection || (collectionAcl !== AclAdmin && collectionAcl !== AclEdit && GetEffectiveAcl(docView.rootDoc) !== AclAdmin);
});
const topBtn = (key: string, icon: string, pointerDown: undefined | ((e: React.PointerEvent) => void), click: undefined | ((e: any) => void), title: string) => (
<Tooltip key={key} title={<div className="dash-tooltip">{title}</div>} placement="top">
<div
className={`documentDecorations-${key}Button`}
onContextMenu={e => e.preventDefault()}
onPointerDown={
pointerDown ??
(e =>
setupMoveUpEvents(
this,
e,
returnFalse,
emptyFunction,
undoBatch(e => click!(e))
))
}>
<FontAwesomeIcon icon={icon as any} />
</div>
</Tooltip>
);
const colorScheme = StrCast(Doc.ActiveDashboard?.colorScheme);
const titleArea = hideTitle ? null : this._editingTitle ? (
<input
ref={this._keyinput}
className={`documentDecorations-title${colorScheme}`}
type="text"
name="dynbox"
autoComplete="on"
value={this._accumulatedTitle}
onBlur={e => this.titleBlur()}
onChange={action(e => (this._accumulatedTitle = e.target.value))}
onKeyDown={this.titleEntered}
/>
) : (
<div className="documentDecorations-title" key="title" onPointerDown={this.onTitleDown}>
<span className={`documentDecorations-titleSpan${colorScheme}`}>{`${this.selectionTitle}`}</span>
</div>
);
const leftBounds = this.props.boundsLeft;
const topBounds = LightboxView.LightboxDoc ? 0 : this.props.boundsTop;
bounds.x = Math.max(leftBounds, bounds.x - this._resizeBorderWidth / 2) + this._resizeBorderWidth / 2;
bounds.y = Math.max(topBounds, bounds.y - this._resizeBorderWidth / 2 - this._titleHeight) + this._resizeBorderWidth / 2 + this._titleHeight;
const borderRadiusDraggerWidth = 15;
bounds.r = Math.max(bounds.x, Math.max(leftBounds, Math.min(window.innerWidth, bounds.r + borderRadiusDraggerWidth + this._resizeBorderWidth / 2) - this._resizeBorderWidth / 2 - borderRadiusDraggerWidth));
bounds.b = Math.max(bounds.y, Math.max(topBounds, Math.min(window.innerHeight, bounds.b + this._resizeBorderWidth / 2 + this._linkBoxHeight) - this._resizeBorderWidth / 2 - this._linkBoxHeight));
// Rotation constants: Only allow rotation on ink and images
const useRotation = seldoc.ComponentView instanceof InkingStroke || seldoc.ComponentView instanceof ImageBox;
const rotation = NumCast(seldoc.rootDoc._jitterRotation);
const resizerScheme = colorScheme ? 'documentDecorations-resizer' + colorScheme : '';
// Radius constants
const useRounding = seldoc.ComponentView instanceof ImageBox || seldoc.ComponentView instanceof FormattedTextBox;
const borderRadius = numberValue(StrCast(seldoc.rootDoc.borderRounding));
const docMax = Math.min(NumCast(seldoc.rootDoc.width) / 2, NumCast(seldoc.rootDoc.height) / 2);
const maxDist = Math.min((this.Bounds.r - this.Bounds.x) / 2, (this.Bounds.b - this.Bounds.y) / 2);
const radiusHandle = (borderRadius / docMax) * maxDist;
const radiusHandleLocation = Math.min(radiusHandle, maxDist);
return (
<div className={`documentDecorations${colorScheme}`}>
<div
className="documentDecorations-background"
style={{
transform: `rotate(${rotation}deg)`,
transformOrigin: 'top left',
width: bounds.r - bounds.x + this._resizeBorderWidth + 'px',
height: bounds.b - bounds.y + this._resizeBorderWidth + 'px',
left: bounds.x - this._resizeBorderWidth / 2,
top: bounds.y - this._resizeBorderWidth / 2,
pointerEvents: DocumentDecorations.Instance.AddToSelection || this.Interacting ? 'none' : 'all',
display: SelectionManager.Views().length <= 1 ? 'none' : undefined,
}}
onPointerDown={this.onBackgroundDown}
onContextMenu={e => {
e.preventDefault();
e.stopPropagation();
}}
/>
{bounds.r - bounds.x < 15 && bounds.b - bounds.y < 15 ? null : (
<div>
<div
className="documentDecorations-container"
key="container"
style={{
transform: `translate(${bounds.x - this._resizeBorderWidth / 2}px, ${bounds.y - this._resizeBorderWidth / 2 - this._titleHeight}px) rotate(${rotation}deg)`,
transformOrigin: `50% calc(50% + 10px)`,
width: bounds.r - bounds.x + this._resizeBorderWidth + 'px',
height: bounds.b - bounds.y + this._resizeBorderWidth + this._titleHeight + 'px',
}}>
{hideDeleteButton ? <div /> : topBtn('close', this.hasIcons ? 'times' : 'window-maximize', undefined, e => this.onCloseClick(this.hasIcons ? true : undefined), 'Close')}
{hideTitle ? null : titleArea}
{hideOpenButton ? null : topBtn('open', 'external-link-alt', this.onMaximizeDown, undefined, 'Open in Tab (ctrl: as alias, shift: in new collection)')}
{hideResizers ? null : (
<>
<div key="tl" className={`documentDecorations-topLeftResizer ${resizerScheme}`} onPointerDown={this.onPointerDown} onContextMenu={e => e.preventDefault()} />
<div key="t" className={`documentDecorations-topResizer ${resizerScheme}`} onPointerDown={this.onPointerDown} onContextMenu={e => e.preventDefault()} />
<div key="tr" className={`documentDecorations-topRightResizer ${resizerScheme}`} onPointerDown={this.onPointerDown} onContextMenu={e => e.preventDefault()} />
<div key="l" className={`documentDecorations-leftResizer ${resizerScheme}`} onPointerDown={this.onPointerDown} onContextMenu={e => e.preventDefault()} />
<div key="c" className={`documentDecorations-centerCont ${resizerScheme}`}></div>
<div key="r" className={`documentDecorations-rightResizer ${resizerScheme}`} onPointerDown={this.onPointerDown} onContextMenu={e => e.preventDefault()} />
<div key="bl" className={`documentDecorations-bottomLeftResizer ${resizerScheme}`} onPointerDown={this.onPointerDown} onContextMenu={e => e.preventDefault()} />
<div key="b" className={`documentDecorations-bottomResizer ${resizerScheme}`} onPointerDown={this.onPointerDown} onContextMenu={e => e.preventDefault()} />
<div key="br" className={`documentDecorations-bottomRightResizer ${resizerScheme}`} onPointerDown={this.onPointerDown} onContextMenu={e => e.preventDefault()} />
{seldoc.props.renderDepth <= 1 || !seldoc.props.ContainingCollectionView ? null : topBtn('selector', 'arrow-alt-circle-up', undefined, this.onSelectorClick, 'tap to select containing document')}
</>
)}
{useRotation && (
<div key="rot" className={`documentDecorations-rotation`} onPointerDown={this.onRotateDown} onContextMenu={e => e.preventDefault()}>
{'⟲'}
</div>
)}
{useRounding && (
<div
key="rad"
style={{
background: `${this._isRounding ? Colors.MEDIUM_BLUE : undefined}`,
left: `${radiusHandleLocation + 3}`,
top: `${radiusHandleLocation + 23}`,
}}
className={`documentDecorations-borderRadius`}
onPointerDown={this.onRadiusDown}
onContextMenu={e => e.preventDefault()}
/>
)}
{hideDocumentButtonBar ? null : (
<div
className="link-button-container"
key="links"
style={{
transform: ` translate(${-this._resizeBorderWidth / 2 + 10}px, ${this._resizeBorderWidth + bounds.b - bounds.y + this._titleHeight}px) `,
}}>
<DocumentButtonBar views={SelectionManager.Views} />
</div>
)}
</div>
</div>
)}
</div>
);
}
}
|