Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/common/BaseAnnotator.scss
Original file line number Diff line number Diff line change
Expand Up @@ -20,14 +20,14 @@
@import '~box-ui-elements/es/styles/common/forms';
@import '~box-ui-elements/es/styles/common/buttons';

.ba-Layer {
@include box-sizing;
@include common-typography;
}

&.is-hidden {
.ba-Layer {
display: none;
}
}
}

.ba-Layer {
@include box-sizing;
@include common-typography;
}
1 change: 0 additions & 1 deletion src/common/BaseManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ export type Options = {

export type Props = {
intl: IntlShape;
scale: number;
store: Store;
};

Expand Down
26 changes: 24 additions & 2 deletions src/common/__tests__/BaseAnnotator-test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
import * as store from '../../store';
import APIFactory from '../../api';
import BaseAnnotator from '../BaseAnnotator';
import { ANNOTATOR_EVENT } from '../../constants';
import { Event, LegacyEvent } from '../../@types';
import { Mode } from '../../store/common';
import APIFactory from '../../api';

jest.mock('../EventEmitter');
jest.mock('../../api');
jest.mock('../../store', () => ({
createStore: jest.fn(() => ({ dispatch: jest.fn() })),
Expand Down Expand Up @@ -128,6 +127,29 @@ describe('BaseAnnotator', () => {
});
});

describe('event handlers', () => {
beforeEach(() => {
jest.spyOn(annotator, 'init');
jest.spyOn(annotator, 'removeAnnotation');
jest.spyOn(annotator, 'setActiveId');
jest.spyOn(annotator, 'setVisibility');
});

test('should call their underlying methods', () => {
annotator.emit(LegacyEvent.SCALE, { scale: 1 });
expect(annotator.init).toHaveBeenCalledWith(1);

annotator.emit(Event.ACTIVE_SET, 12345);
expect(annotator.setActiveId).toHaveBeenCalledWith(12345);

annotator.emit(Event.ANNOTATION_REMOVE, 12345);
expect(annotator.removeAnnotation).toHaveBeenCalledWith(12345);

annotator.emit(Event.VISIBLE_SET, true);
expect(annotator.setVisibility).toHaveBeenCalledWith(true);
});
});

describe('scrollToAnnotation()', () => {
test('should exist', () => {
expect(annotator.scrollToAnnotation).toBeTruthy();
Expand Down
9 changes: 4 additions & 5 deletions src/document/DocumentAnnotator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,6 @@ export default class DocumentAnnotator extends BaseAnnotator {
pageManagers.forEach(manager =>
manager.render({
intl: this.intl,
scale: this.scale,
store: this.store,
}),
);
Expand Down Expand Up @@ -112,10 +111,10 @@ export default class DocumentAnnotator extends BaseAnnotator {
}

const canSmoothScroll = 'scrollBehavior' in this.annotatedEl.style;
const parentCenterX = this.annotatedEl.clientWidth / 2;
const parentCenterY = this.annotatedEl.clientHeight / 2;
const offsetCenterX = Math.round(offsetX * this.scale);
const offsetCenterY = Math.round(offsetY * this.scale);
const parentCenterX = Math.round(this.annotatedEl.clientWidth / 2);
const parentCenterY = Math.round(this.annotatedEl.clientHeight / 2);
const offsetCenterX = Math.round(pageEl.clientWidth * (offsetX / 100));
const offsetCenterY = Math.round(pageEl.clientHeight * (offsetY / 100));
const offsetScrollLeft = pageEl.offsetLeft - parentCenterX + offsetCenterX;
const offsetScrollTop = pageEl.offsetTop - parentCenterY + offsetCenterY;
const scrollLeft = Math.max(0, Math.min(offsetScrollLeft, this.annotatedEl.scrollWidth));
Expand Down
3 changes: 2 additions & 1 deletion src/document/__tests__/DocumentAnnotator-test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,6 @@ describe('DocumentAnnotator', () => {
expect(annotator.getPageNumber).toHaveBeenCalledWith(pageEl);
expect(mockManager.render).toHaveBeenCalledWith({
intl: annotator.intl,
scale: 1,
store: expect.any(Object),
});
});
Expand Down Expand Up @@ -201,6 +200,8 @@ describe('DocumentAnnotator', () => {
const getPageMock = (pageNumber = 1): HTMLElement => {
const page = document.createElement('div');

Object.defineProperty(page, 'clientHeight', { configurable: true, value: 100 });
Object.defineProperty(page, 'clientWidth', { configurable: true, value: 100 });
Object.defineProperty(page, 'offsetLeft', { configurable: true, value: 0 });
Object.defineProperty(page, 'offsetTop', { configurable: true, value: (pageNumber - 1) * 100 }); // 100 pixels per page

Expand Down
2 changes: 0 additions & 2 deletions src/region/RegionAnnotation.scss
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@
.ba-RegionAnnotation {
@include ba-RegionRect;

margin: 0;
padding: 0;
background: none;
border: none;
box-shadow: none;
Expand Down
27 changes: 9 additions & 18 deletions src/region/RegionAnnotations.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import RegionRect, { RegionRectRef } from './RegionRect';
import { AnnotationRegion, Rect } from '../@types';
import { CreateArg } from './actions';
import { CreatorItem, CreatorStatus } from '../store/creator';
import { scaleShape } from './regionUtil';
import './RegionAnnotations.scss';

type Props = {
Expand All @@ -16,7 +15,6 @@ type Props = {
isCreating: boolean;
message: string;
page: number;
scale: number;
setActiveAnnotationId: (annotationId: string | null) => void;
setMessage: (message: string) => void;
setStaged: (staged: CreatorItem | null) => void;
Expand All @@ -33,27 +31,21 @@ export default class RegionAnnotations extends React.PureComponent<Props, State>
static defaultProps = {
annotations: [],
isCreating: false,
scale: 1,
};

state: State = {};

setStatus(status: CreatorStatus): void {
const { setStatus } = this.props;
setStatus(status);
}

handleAnnotationActive = (annotationId: string | null): void => {
const { setActiveAnnotationId } = this.props;

setActiveAnnotationId(annotationId);
};

handleCancel = (): void => {
const { setMessage, setStaged } = this.props;
const { setMessage, setStaged, setStatus } = this.props;
setMessage('');
setStaged(null);
this.setStatus(CreatorStatus.init);
setStatus(CreatorStatus.init);
};

handleChange = (text?: string): void => {
Expand All @@ -62,15 +54,15 @@ export default class RegionAnnotations extends React.PureComponent<Props, State>
};

handleStart = (): void => {
const { setStaged } = this.props;
const { setStaged, setStatus } = this.props;
setStaged(null);
this.setStatus(CreatorStatus.init);
setStatus(CreatorStatus.init);
};

handleStop = (shape: Rect): void => {
const { page, scale, setStaged } = this.props;
setStaged({ location: page, shape: scaleShape(shape, scale, true) });
this.setStatus(CreatorStatus.staged);
const { page, setStaged, setStatus } = this.props;
setStaged({ location: page, shape });
setStatus(CreatorStatus.staged);
};

handleSubmit = (): void => {
Expand All @@ -88,7 +80,7 @@ export default class RegionAnnotations extends React.PureComponent<Props, State>
};

render(): JSX.Element {
const { activeAnnotationId, annotations, isCreating, message, scale, staged, status } = this.props;
const { activeAnnotationId, annotations, isCreating, message, staged, status } = this.props;
const { rectRef } = this.state;
const canReply = status !== CreatorStatus.init;
const isPending = status === CreatorStatus.pending;
Expand All @@ -101,7 +93,6 @@ export default class RegionAnnotations extends React.PureComponent<Props, State>
annotations={annotations}
className="ba-RegionAnnotations-list"
onSelect={this.handleAnnotationActive}
scale={scale}
/>

{/* Layer 2: Drawn (unsaved) incomplete annotation target, if any */}
Expand All @@ -116,7 +107,7 @@ export default class RegionAnnotations extends React.PureComponent<Props, State>
{/* Layer 3a: Staged (unsaved) annotation target, if any */}
{isCreating && staged && (
<div className="ba-RegionAnnotations-target">
<RegionRect ref={this.setRectRef} isActive shape={scaleShape(staged.shape, scale)} />
<RegionRect ref={this.setRectRef} isActive shape={staged.shape} />
</div>
)}

Expand Down
2 changes: 1 addition & 1 deletion src/region/RegionCreator.scss
Original file line number Diff line number Diff line change
Expand Up @@ -8,5 +8,5 @@ $region_cursor_32_3x: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAGAAAABgCAY
}

.ba-RegionCreator-rect {
will-change: height, transform, width;
transform: translateZ(0);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why do we need this translate?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It seems to help performance in Firefox and Safari a bit and has no apparent effect in Chrome. It's the same concept as using translate3d instead of translate. I can always remove it later if it becomes a problem.

}
16 changes: 10 additions & 6 deletions src/region/RegionCreator.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -49,7 +49,7 @@ export default function RegionCreator({ className, onStart, onStop }: Props): JS
const { current: x2 } = positionX2Ref;
const { current: y2 } = positionY2Ref;

if (!creatorEl || !x1 || !x2 || !y1 || !y2) {
if (!creatorEl || x1 === null || x2 === null || y1 === null || y2 === null) {
return null;
}

Expand All @@ -63,12 +63,16 @@ export default function RegionCreator({ className, onStart, onStop }: Props): JS
const targetX = Math.min(Math.max(MIN_X, x2 > x1 ? x2 : x1), MAX_X);
const targetY = Math.min(Math.max(MIN_Y, y2 > y1 ? y2 : y1), MAX_Y);

// Derive the shape height/width from the two coordinates
const shapeHeight = Math.max(MIN_SIZE, targetY - originY);
const shapeWidth = Math.max(MIN_SIZE, targetX - originX);

return {
height: Math.max(MIN_SIZE, targetY - originY),
height: (shapeHeight / height) * 100,
type: 'rect',
width: Math.max(MIN_SIZE, targetX - originX),
x: originX,
y: originY,
width: (shapeWidth / width) * 100,
x: (originX / width) * 100,
y: (originY / height) * 100,
};
};

Expand Down Expand Up @@ -164,7 +168,7 @@ export default function RegionCreator({ className, onStart, onStop }: Props): JS

if (isDirty && regionRect && shape) {
// Directly set the style attribute
Object.assign(regionRect.style, styleShape(shape, true));
Object.assign(regionRect.style, styleShape(shape));

// Reset the dirty state to avoid multiple renders
regionDirtyRef.current = false;
Expand Down
51 changes: 32 additions & 19 deletions src/region/RegionList.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,26 +4,36 @@ import noop from 'lodash/noop';
import RegionAnnotation from './RegionAnnotation';
import useOutsideEvent from '../common/useOutsideEvent';
import { AnnotationRegion } from '../@types';
import { scaleShape } from './regionUtil';

export type Props = {
activeId?: string | null;
annotations: AnnotationRegion[];
className?: string;
onSelect?: (annotationId: string | null) => void;
scale: number;
};

export function RegionList({ activeId, annotations, className, onSelect = noop, scale }: Props): JSX.Element {
export function checkValue(value: number): boolean {
return value >= 0 && value <= 100; // Values cannot be negative or larger than 100%
}

export function filterRegion({ target }: AnnotationRegion): boolean {
const { shape } = target;
const { height, width, x, y } = shape;

return checkValue(height) && checkValue(width) && checkValue(x) && checkValue(y);
}

export function sortRegion({ target: targetA }: AnnotationRegion, { target: targetB }: AnnotationRegion): number {
const { shape: shapeA } = targetA;
const { shape: shapeB } = targetB;

// Render the smallest annotations last to ensure they are always clickable
return shapeA.height * shapeA.width > shapeB.height * shapeB.width ? -1 : 1;
}

export function RegionList({ activeId, annotations, className, onSelect = noop }: Props): JSX.Element {
const [isListening, setIsListening] = React.useState(true);
const rootElRef = React.createRef<HTMLDivElement>();
const sortedAnnotations = annotations.sort(({ target: targetA }, { target: targetB }) => {
const { shape: shapeA } = targetA;
const { shape: shapeB } = targetB;

// Render the smallest annotations last to ensure they are always clickable
return shapeA.height * shapeA.width > shapeB.height * shapeB.width ? -1 : 1;
});

// Document-level event handlers for focus and pointer control
useOutsideEvent('click', rootElRef, (): void => onSelect(null));
Expand All @@ -32,15 +42,18 @@ export function RegionList({ activeId, annotations, className, onSelect = noop,

return (
<div ref={rootElRef} className={classNames(className, { 'is-listening': isListening })}>
{sortedAnnotations.map(({ id, target }) => (
<RegionAnnotation
key={id}
annotationId={id}
isActive={activeId === id}
onSelect={onSelect}
shape={scaleShape(target.shape, scale)}
/>
))}
{annotations
.filter(filterRegion)
.sort(sortRegion)
.map(({ id, target }) => (
<RegionAnnotation
key={id}
annotationId={id}
isActive={activeId === id}
onSelect={onSelect}
shape={target.shape}
/>
))}
</div>
);
}
Expand Down
5 changes: 5 additions & 0 deletions src/region/RegionRect.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,11 @@

position: absolute;

// stylelint-disable-next-line declaration-no-important
box-sizing: content-box !important; // Padding needs to increase the hit area of the button to include the borders
Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The other alternative that I considered was to use something like this in styleShape, but it seemed somehow worse than just changing the box sizing model:

width: `calc(${width}% + ${BORDER_TOTAL}px)`

margin: -#{$border-size-outer};
padding: $border-size-outer;

&::after {
position: absolute;
top: $border-size-outer;
Expand Down
3 changes: 3 additions & 0 deletions src/region/__mocks__/RegionRect.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import React from 'react';

export default React.forwardRef((props, ref: React.Ref<HTMLDivElement>) => <div ref={ref} />);
4 changes: 1 addition & 3 deletions src/region/__mocks__/data.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
export const scale = 1;

export const rect = {
type: 'rect' as const,
height: 10,
Expand Down Expand Up @@ -68,7 +66,7 @@ export const annotations = [
id: 'anno_4',
target: {
location: { type: 'page', value: 10 },
shape: { height: 100, width: 100, x: 100, y: 100, type: 'rect' },
shape: { height: 40, width: 40, x: 40, y: 40, type: 'rect' },
type: 'region',
},
},
Expand Down
7 changes: 4 additions & 3 deletions src/region/__tests__/RegionAnnotation-test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,10 @@ describe('RegionAnnotation', () => {

expect(wrapper.prop('style')).toMatchObject({
display: 'block',
height: '18px',
transform: 'translate(6px, 6px)',
width: '18px',
height: '10%',
left: '10%',
top: '10%',
width: '10%',
});
});

Expand Down
Loading