@khanacademy/wonder-blocks-tooltip 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (36) hide show
  1. package/LICENSE +21 -0
  2. package/dist/es/index.js +1133 -0
  3. package/dist/index.js +1389 -0
  4. package/dist/index.js.flow +2 -0
  5. package/docs.md +11 -0
  6. package/package.json +37 -0
  7. package/src/__tests__/__snapshots__/generated-snapshot.test.js.snap +2674 -0
  8. package/src/__tests__/generated-snapshot.test.js +475 -0
  9. package/src/components/__tests__/__snapshots__/tooltip-tail.test.js.snap +9 -0
  10. package/src/components/__tests__/__snapshots__/tooltip.test.js.snap +47 -0
  11. package/src/components/__tests__/tooltip-anchor.test.js +987 -0
  12. package/src/components/__tests__/tooltip-bubble.test.js +80 -0
  13. package/src/components/__tests__/tooltip-popper.test.js +71 -0
  14. package/src/components/__tests__/tooltip-tail.test.js +117 -0
  15. package/src/components/__tests__/tooltip.integration.test.js +79 -0
  16. package/src/components/__tests__/tooltip.test.js +401 -0
  17. package/src/components/tooltip-anchor.js +330 -0
  18. package/src/components/tooltip-bubble.js +150 -0
  19. package/src/components/tooltip-bubble.md +92 -0
  20. package/src/components/tooltip-content.js +76 -0
  21. package/src/components/tooltip-content.md +34 -0
  22. package/src/components/tooltip-popper.js +101 -0
  23. package/src/components/tooltip-tail.js +462 -0
  24. package/src/components/tooltip-tail.md +143 -0
  25. package/src/components/tooltip.js +235 -0
  26. package/src/components/tooltip.md +194 -0
  27. package/src/components/tooltip.stories.js +76 -0
  28. package/src/index.js +12 -0
  29. package/src/util/__tests__/__snapshots__/active-tracker.test.js.snap +3 -0
  30. package/src/util/__tests__/__snapshots__/ref-tracker.test.js.snap +3 -0
  31. package/src/util/__tests__/active-tracker.test.js +142 -0
  32. package/src/util/__tests__/ref-tracker.test.js +153 -0
  33. package/src/util/active-tracker.js +94 -0
  34. package/src/util/constants.js +7 -0
  35. package/src/util/ref-tracker.js +46 -0
  36. package/src/util/types.js +29 -0
@@ -0,0 +1,1133 @@
1
+ import { Component, createElement, cloneElement, Fragment } from 'react';
2
+ import { findDOMNode, createPortal } from 'react-dom';
3
+ import { Text as Text$1, View, UniqueIDProvider } from '@khanacademy/wonder-blocks-core';
4
+ import { maybeGetPortalMountedModalHostElement } from '@khanacademy/wonder-blocks-modal';
5
+ import { css, StyleSheet } from 'aphrodite';
6
+ import Colors from '@khanacademy/wonder-blocks-color';
7
+ import Spacing from '@khanacademy/wonder-blocks-spacing';
8
+ import _extends from '@babel/runtime/helpers/extends';
9
+ import { Strut } from '@khanacademy/wonder-blocks-layout';
10
+ import { HeadingSmall, LabelMedium } from '@khanacademy/wonder-blocks-typography';
11
+ import { Popper } from 'react-popper';
12
+
13
+ /**
14
+ * This interface should be implemented by types that are interested in the
15
+ * notifications of active state being stolen. Generally, this would also be
16
+ * subscribers that may also steal active state, but not necessarily.
17
+ *
18
+ * Once implemented, the type must call subscribe on a tracker to begin
19
+ * receiving notifications.
20
+ */
21
+
22
+ /**
23
+ * This class is used to track the concept of active state (though technically
24
+ * that could be any boolean state). The tracker has a variety of subscribers
25
+ * that receive notifications of state theft and can steal the state.
26
+ *
27
+ * For the tooltip, this enables us to have a single tooltip active at any one
28
+ * time. The tracker allows tooltip anchors to coordinate which of them is
29
+ * active, and to ensure that if a different one becomes active, all the others
30
+ * know that they aren't.
31
+ *
32
+ * - When notified that the state has been stolen, subscribers can immediately
33
+ * reflect that theft (in the case of a tooltip, they would hide themselves).
34
+ * - The thief does not get notified if they were the one who stole the state
35
+ * since they should already know that they did that (this avoids having to have
36
+ * checks for reentrancy, for example).
37
+ * - When the subscriber that owns the state no longer needs it, it can
38
+ * voluntarily give it up.
39
+ * - If the state is stolen while a subscriber owns the
40
+ * state, that subscriber does not give up the state, as it doesn't have it
41
+ * anymore (it was stolen).
42
+ */
43
+ class ActiveTracker {
44
+ constructor() {
45
+ this._subscribers = [];
46
+ }
47
+
48
+ _getIndex(who) {
49
+ return this._subscribers.findIndex(v => v === who);
50
+ }
51
+ /**
52
+ * Called when a tooltip anchor becomes active so that it can tell all other
53
+ * anchors that they are no longer the active tooltip. Returns true if
54
+ * the there was a steal of active state from another anchor; otherwise, if
55
+ * no other anchor had been active, returns false.
56
+ */
57
+
58
+
59
+ steal(who) {
60
+ const wasActive = !!this._active;
61
+ this._active = true;
62
+
63
+ for (const anchor of this._subscribers) {
64
+ if (anchor === who) {
65
+ // We don't need to notify the thief.
66
+ continue;
67
+ }
68
+
69
+ anchor.activeStateStolen();
70
+ }
71
+
72
+ return wasActive;
73
+ }
74
+ /**
75
+ * Called if a tooltip doesn't want to be active anymore.
76
+ * Should not be called when being told the active spot was stolen by
77
+ * another anchor, only when the anchor is unhovered and unfocused and they
78
+ * were active.
79
+ */
80
+
81
+
82
+ giveup() {
83
+ this._active = false;
84
+ }
85
+ /**
86
+ * Subscribes a tooltip anchor to the tracker so that it can be notified of
87
+ * steals. Returns a method that can be used to unsubscribe the anchor from
88
+ * notifications.
89
+ */
90
+
91
+
92
+ subscribe(who) {
93
+ if (this._getIndex(who) >= 0) {
94
+ throw new Error("Already subscribed.");
95
+ }
96
+
97
+ this._subscribers.push(who);
98
+
99
+ const unsubscribe = () => {
100
+ const index = this._getIndex(who);
101
+
102
+ this._subscribers.splice(index, 1);
103
+ };
104
+
105
+ return unsubscribe;
106
+ }
107
+
108
+ }
109
+
110
+ /**
111
+ * The attribute used to identify a tooltip portal.
112
+ */
113
+ const TooltipAppearanceDelay = 100;
114
+ const TooltipDisappearanceDelay = 75;
115
+
116
+ /**
117
+ * This component turns the given content into an accessible anchor for
118
+ * positioning and displaying tooltips.
119
+ */
120
+ const TRACKER = new ActiveTracker();
121
+ class TooltipAnchor extends Component {
122
+ constructor(props) {
123
+ super(props);
124
+
125
+ this.activeStateStolen = () => {
126
+ // Something wants the active state.
127
+ // Do we have it? If so, let's remember that.
128
+ // If we are already active, or we're inactive but have a timeoutID,
129
+ // then it was stolen from us.
130
+ this._stolenFromUs = this.state.active || !!this._timeoutID; // Let's first tell ourselves we're not focused (otherwise the tooltip
131
+ // will be sticky on the next hover of this anchor and that just looks
132
+ // weird).
133
+
134
+ this._focused = false; // Now update our actual state.
135
+
136
+ this._setActiveState(false, true);
137
+ };
138
+
139
+ this._handleFocusIn = () => {
140
+ this._updateActiveState(this._hovered, true);
141
+ };
142
+
143
+ this._handleFocusOut = () => {
144
+ this._updateActiveState(this._hovered, false);
145
+ };
146
+
147
+ this._handleMouseEnter = () => {
148
+ this._updateActiveState(true, this._focused);
149
+ };
150
+
151
+ this._handleMouseLeave = () => {
152
+ this._updateActiveState(false, this._focused);
153
+ };
154
+
155
+ this._handleKeyUp = e => {
156
+ // We check the key as that's keyboard layout agnostic and also avoids
157
+ // the minefield of deprecated number type properties like keyCode and
158
+ // which, with the replacement code, which uses a string instead.
159
+ if (e.key === "Escape" && this.state.active) {
160
+ // Stop the event going any further.
161
+ // For cancellation events, like the Escape key, we generally should
162
+ // air on the side of caution and only allow it to cancel one thing.
163
+ // So, it's polite for us to stop propagation of the event.
164
+ // Otherwise, we end up with UX where one Escape key press
165
+ // unexpectedly cancels multiple things.
166
+ //
167
+ // For example, using Escape to close a tooltip or a dropdown while
168
+ // displaying a modal and having the modal close as well. This would
169
+ // be annoyingly bad UX.
170
+ e.preventDefault();
171
+ e.stopPropagation();
172
+
173
+ this._updateActiveState(false, false);
174
+ }
175
+ };
176
+
177
+ this._focused = false;
178
+ this._hovered = false;
179
+ this.state = {
180
+ active: false
181
+ };
182
+ }
183
+
184
+ componentDidMount() {
185
+ const anchorNode = findDOMNode(this); // This should never happen, but we have this check here to make flow
186
+ // happy and ensure that if this does happen, we'll know about it.
187
+
188
+ if (anchorNode instanceof Text) {
189
+ throw new Error("TooltipAnchor must be applied to an Element. Text content is not supported.");
190
+ }
191
+
192
+ this._unsubscribeFromTracker = TRACKER.subscribe(this);
193
+ this._anchorNode = anchorNode;
194
+
195
+ this._updateFocusivity();
196
+
197
+ if (anchorNode) {
198
+ /**
199
+ * TODO(somewhatabstract): Work out how to allow pointer to go over
200
+ * the tooltip content to keep it active. This likely requires
201
+ * pointer events but that would break the obscurement checks we do.
202
+ * So, careful consideration required. See WB-302.
203
+ */
204
+ anchorNode.addEventListener("focusin", this._handleFocusIn);
205
+ anchorNode.addEventListener("focusout", this._handleFocusOut);
206
+ anchorNode.addEventListener("mouseenter", this._handleMouseEnter);
207
+ anchorNode.addEventListener("mouseleave", this._handleMouseLeave);
208
+ this.props.anchorRef(this._anchorNode);
209
+ }
210
+ }
211
+
212
+ componentDidUpdate(prevProps) {
213
+ if (prevProps.forceAnchorFocusivity !== this.props.forceAnchorFocusivity || prevProps.children !== this.props.children) {
214
+ this._updateFocusivity();
215
+ }
216
+ }
217
+
218
+ componentWillUnmount() {
219
+ if (this._unsubscribeFromTracker) {
220
+ this._unsubscribeFromTracker();
221
+ }
222
+
223
+ this._clearPendingAction();
224
+
225
+ const anchorNode = this._anchorNode;
226
+
227
+ if (anchorNode) {
228
+ anchorNode.removeEventListener("focusin", this._handleFocusIn);
229
+ anchorNode.removeEventListener("focusout", this._handleFocusOut);
230
+ anchorNode.removeEventListener("mouseenter", this._handleMouseEnter);
231
+ anchorNode.removeEventListener("mouseleave", this._handleMouseLeave);
232
+ }
233
+
234
+ if (this.state.active) {
235
+ document.removeEventListener("keyup", this._handleKeyUp);
236
+ }
237
+ }
238
+
239
+ _updateFocusivity() {
240
+ const anchorNode = this._anchorNode;
241
+
242
+ if (!anchorNode) {
243
+ return;
244
+ }
245
+
246
+ const {
247
+ forceAnchorFocusivity
248
+ } = this.props;
249
+ const currentTabIndex = anchorNode.getAttribute("tabindex");
250
+
251
+ if (forceAnchorFocusivity && !currentTabIndex) {
252
+ // Ensure that the anchor point is keyboard focusable so that
253
+ // we can show the tooltip for visually impaired users that don't
254
+ // use pointer devices nor assistive technology like screen readers.
255
+ anchorNode.setAttribute("tabindex", "0");
256
+ this._weSetFocusivity = true;
257
+ } else if (!forceAnchorFocusivity && currentTabIndex) {
258
+ // We may not be forcing it, but we also want to ensure that if we
259
+ // did before, we remove it.
260
+ if (this._weSetFocusivity) {
261
+ anchorNode.removeAttribute("tabindex");
262
+ this._weSetFocusivity = false;
263
+ }
264
+ }
265
+ }
266
+
267
+ _updateActiveState(hovered, focused) {
268
+ // Update our stored values.
269
+ this._hovered = hovered;
270
+ this._focused = focused;
271
+
272
+ this._setActiveState(hovered || focused);
273
+ }
274
+
275
+ _clearPendingAction() {
276
+ if (this._timeoutID) {
277
+ clearTimeout(this._timeoutID);
278
+ this._timeoutID = null;
279
+ }
280
+ }
281
+
282
+ _setActiveState(active, instant) {
283
+ if (this._stolenFromUs || active !== this.state.active || !this.state.active && this._timeoutID) {
284
+ // If we are about to lose active state or change it, we need to
285
+ // cancel any pending action to show ourselves.
286
+ // So, if active is stolen from us, we are changing active state,
287
+ // or we are inactive and have a timer, clear the action.
288
+ this._clearPendingAction();
289
+ } else if (active === this.state.active && !this._timeoutID) {
290
+ // Nothing to do if we're already active.
291
+ return;
292
+ } // Determine if we are doing things immediately or not.
293
+
294
+
295
+ instant = instant || active && TRACKER.steal(this);
296
+
297
+ if (instant) {
298
+ if (active) {
299
+ document.addEventListener("keyup", this._handleKeyUp);
300
+ } else {
301
+ document.removeEventListener("keyup", this._handleKeyUp);
302
+ }
303
+
304
+ this.setState({
305
+ active
306
+ });
307
+ this.props.onActiveChanged(active);
308
+
309
+ if (!this._stolenFromUs && !active) {
310
+ // Only the very last thing going inactive will giveup
311
+ // the stolen active state.
312
+ TRACKER.giveup();
313
+ }
314
+
315
+ this._stolenFromUs = false;
316
+ } else {
317
+ const delay = active ? TooltipAppearanceDelay : TooltipDisappearanceDelay;
318
+ this._timeoutID = setTimeout(() => {
319
+ this._timeoutID = null;
320
+
321
+ this._setActiveState(active, true);
322
+ }, delay);
323
+ }
324
+ }
325
+
326
+ _renderAnchorableChildren() {
327
+ const {
328
+ children
329
+ } = this.props;
330
+ return typeof children === "string" ? /*#__PURE__*/createElement(Text$1, null, children) : children;
331
+ }
332
+
333
+ _renderAccessibleChildren(ids) {
334
+ const anchorableChildren = this._renderAnchorableChildren();
335
+
336
+ return /*#__PURE__*/cloneElement(anchorableChildren, {
337
+ "aria-describedby": ids.get(TooltipAnchor.ariaContentId)
338
+ });
339
+ }
340
+
341
+ render() {
342
+ // We need to make sure we can anchor on our content.
343
+ // If the content is just a string, we wrap it in a Text element
344
+ // so as not to affect styling or layout but still have an element
345
+ // to anchor to.
346
+ if (this.props.ids) {
347
+ return this._renderAccessibleChildren(this.props.ids);
348
+ }
349
+
350
+ return this._renderAnchorableChildren();
351
+ }
352
+
353
+ }
354
+ TooltipAnchor.defaultProps = {
355
+ forceAnchorFocusivity: true
356
+ };
357
+ TooltipAnchor.ariaContentId = "aria-content";
358
+
359
+ // TODO(somewhatabstract): Replace this really basic unique ID work with
360
+ // something SSR-friendly and more robust.
361
+ let tempIdCounter = 0;
362
+ class TooltipTail extends Component {
363
+ _calculateDimensionsFromPlacement() {
364
+ const {
365
+ placement
366
+ } = this.props; // The trimline, which we draw to make the tail flush to the bubble,
367
+ // has a thickness of 1. Since the line is drawn centered to the
368
+ // coordinates, we use an offset of 0.5 so that it properly covers what
369
+ // we want it to.
370
+
371
+ const trimlineOffset = 0.5; // Calculate the three points of the arrow. Depending on the tail's
372
+ // direction (i.e., the tooltip's "side"), we choose different points,
373
+ // and set our SVG's bounds differently.
374
+ //
375
+ // Note that when the tail points to the left or right, the width/height
376
+ // are inverted.
377
+
378
+ switch (placement) {
379
+ case "top":
380
+ return {
381
+ trimlinePoints: [`0,-${trimlineOffset}`, `${ARROW_WIDTH},-${trimlineOffset}`],
382
+ points: ["0,0", `${ARROW_WIDTH / 2},${ARROW_HEIGHT}`, `${ARROW_WIDTH},0`],
383
+ height: ARROW_HEIGHT,
384
+ width: ARROW_WIDTH
385
+ };
386
+
387
+ case "right":
388
+ return {
389
+ trimlinePoints: [`${ARROW_HEIGHT + trimlineOffset},0`, `${ARROW_HEIGHT + trimlineOffset},${ARROW_WIDTH}`],
390
+ points: [`${ARROW_HEIGHT},0`, `0,${ARROW_WIDTH / 2}`, `${ARROW_HEIGHT},${ARROW_WIDTH}`],
391
+ width: ARROW_HEIGHT,
392
+ height: ARROW_WIDTH
393
+ };
394
+
395
+ case "bottom":
396
+ return {
397
+ trimlinePoints: [`0, ${ARROW_HEIGHT + trimlineOffset}`, `${ARROW_WIDTH},${ARROW_HEIGHT + trimlineOffset}`],
398
+ points: [`0, ${ARROW_HEIGHT}`, `${ARROW_WIDTH / 2},0`, `${ARROW_WIDTH},${ARROW_HEIGHT}`],
399
+ width: ARROW_WIDTH,
400
+ height: ARROW_HEIGHT
401
+ };
402
+
403
+ case "left":
404
+ return {
405
+ trimlinePoints: [`-${trimlineOffset},0`, `-${trimlineOffset},${ARROW_WIDTH}`],
406
+ points: [`0,0`, `${ARROW_HEIGHT},${ARROW_WIDTH / 2}`, `0,${ARROW_WIDTH}`],
407
+ width: ARROW_HEIGHT,
408
+ height: ARROW_WIDTH
409
+ };
410
+
411
+ default:
412
+ throw new Error(`Unknown placement: ${placement}`);
413
+ }
414
+ }
415
+
416
+ _getFilterPositioning() {
417
+ const {
418
+ placement
419
+ } = this.props;
420
+
421
+ switch (placement) {
422
+ case "top":
423
+ return {
424
+ y: "-50%",
425
+ x: "-50%",
426
+ offsetShadowX: 0
427
+ };
428
+
429
+ case "bottom":
430
+ // No shadow on the arrow as it falls "under" the bubble.
431
+ return null;
432
+
433
+ case "left":
434
+ return {
435
+ y: "-50%",
436
+ x: "0%",
437
+ offsetShadowX: 1
438
+ };
439
+
440
+ case "right":
441
+ return {
442
+ y: "-50%",
443
+ x: "-100%",
444
+ offsetShadowX: -1
445
+ };
446
+
447
+ default:
448
+ throw new Error(`Unknown placement: ${placement}`);
449
+ }
450
+ }
451
+ /**
452
+ * Create an SVG filter that applies a blur to an element.
453
+ * We'll apply it to a dark shape outlining the tooltip, which
454
+ * will produce the overall effect of a drop-shadow.
455
+ *
456
+ * Also, scope its ID by side, so that tooltips with other
457
+ * "side" values don't end up using the wrong filter from
458
+ * elsewhere in the document. (The `height` value depends on
459
+ * which way the arrow is turned!)
460
+ */
461
+
462
+
463
+ _maybeRenderDropshadow(points) {
464
+ const position = this._getFilterPositioning();
465
+
466
+ if (!position) {
467
+ return null;
468
+ }
469
+
470
+ const {
471
+ placement
472
+ } = this.props;
473
+ const {
474
+ y,
475
+ x,
476
+ offsetShadowX
477
+ } = position;
478
+ const dropShadowFilterId = `tooltip-dropshadow-${placement}-${tempIdCounter++}`;
479
+ return [/*#__PURE__*/createElement("filter", {
480
+ key: "filter",
481
+ id: dropShadowFilterId // Height and width tell the filter how big of a canvas to
482
+ // draw based on its parent size. i.e. 2 times bigger.
483
+ // This is so that the diffuse gaussian blur has space to
484
+ // bleed into.
485
+ ,
486
+ width: "200%",
487
+ height: "200%" // The x and y values tell the filter where, relative to its
488
+ // parent, it should begin showing its canvas. Without these
489
+ // the filter would clip at 0,0, which would look really
490
+ // strange.
491
+ ,
492
+ x: x,
493
+ y: y
494
+ }, /*#__PURE__*/createElement("feGaussianBlur", {
495
+ in: "SourceAlpha",
496
+ stdDeviation: Spacing.xxSmall_6 / 2
497
+ }), /*#__PURE__*/createElement("feComponentTransfer", null, /*#__PURE__*/createElement("feFuncA", {
498
+ type: "linear",
499
+ slope: "0.3"
500
+ }))),
501
+ /*#__PURE__*/
502
+
503
+ /**
504
+ * Draw the tooltip arrow and apply the blur filter we created
505
+ * above, to produce a drop shadow effect.
506
+ * We move it down a bit with a translation, so that it is what
507
+ * we want.
508
+ *
509
+ * We offset the shadow on the X-axis because for left/right
510
+ * tails, we move the tail 1px toward the bubble. If we didn't
511
+ * offset the shadow, it would crash the bubble outline.
512
+ *
513
+ * See styles below for why we offset the arrow.
514
+ */
515
+ createElement("g", {
516
+ key: "dropshadow",
517
+ transform: `translate(${offsetShadowX},5.5)`
518
+ }, /*#__PURE__*/createElement("polyline", {
519
+ fill: Colors.offBlack16,
520
+ points: points.join(" "),
521
+ stroke: Colors.offBlack32,
522
+ filter: `url(#${dropShadowFilterId})`
523
+ }))];
524
+ }
525
+
526
+ _minDistanceFromCorners(placement) {
527
+ const minDistanceFromCornersForTopBottom = Spacing.medium_16;
528
+ const minDistanceFromCornersForLeftRight = 7;
529
+
530
+ switch (placement) {
531
+ case "top":
532
+ case "bottom":
533
+ return minDistanceFromCornersForTopBottom;
534
+
535
+ case "left":
536
+ case "right":
537
+ return minDistanceFromCornersForLeftRight;
538
+
539
+ default:
540
+ throw new Error(`Unknown placement: ${placement}`);
541
+ }
542
+ }
543
+
544
+ _getFullTailWidth() {
545
+ return ARROW_WIDTH + 2 * MIN_DISTANCE_FROM_CORNERS;
546
+ }
547
+
548
+ _getFullTailHeight() {
549
+ return ARROW_HEIGHT + DISTANCE_FROM_ANCHOR;
550
+ }
551
+
552
+ _getContainerStyle() {
553
+ const {
554
+ placement
555
+ } = this.props;
556
+ /**
557
+ * Ensure the container is sized properly for us to be placed correctly
558
+ * by the Popper.js code.
559
+ *
560
+ * Here we offset the arrow 1px toward the bubble. This ensures the arrow
561
+ * outline meets the bubble outline and allows the arrow to erase the bubble
562
+ * outline between the ends of the arrow outline. We do this so that the
563
+ * arrow outline and bubble outline create a single, seamless outline of
564
+ * the callout.
565
+ *
566
+ * NOTE: The widths and heights refer to the downward-pointing tail
567
+ * (i.e. placement="top"). When the tail points to the left or right
568
+ * instead, the width/height are inverted.
569
+ */
570
+
571
+ const fullTailWidth = this._getFullTailWidth();
572
+
573
+ const fullTailHeight = this._getFullTailHeight();
574
+
575
+ switch (placement) {
576
+ case "top":
577
+ return {
578
+ top: -1,
579
+ width: fullTailWidth,
580
+ height: fullTailHeight
581
+ };
582
+
583
+ case "right":
584
+ return {
585
+ left: 1,
586
+ width: fullTailHeight,
587
+ height: fullTailWidth
588
+ };
589
+
590
+ case "bottom":
591
+ return {
592
+ top: 1,
593
+ width: fullTailWidth,
594
+ height: fullTailHeight
595
+ };
596
+
597
+ case "left":
598
+ return {
599
+ left: -1,
600
+ width: fullTailHeight,
601
+ height: fullTailWidth
602
+ };
603
+
604
+ default:
605
+ throw new Error(`Unknown placement: ${placement}`);
606
+ }
607
+ }
608
+
609
+ _getArrowStyle() {
610
+ const {
611
+ placement
612
+ } = this.props;
613
+
614
+ switch (placement) {
615
+ case "top":
616
+ return {
617
+ marginLeft: MIN_DISTANCE_FROM_CORNERS,
618
+ marginRight: MIN_DISTANCE_FROM_CORNERS,
619
+ paddingBottom: DISTANCE_FROM_ANCHOR
620
+ };
621
+
622
+ case "right":
623
+ return {
624
+ marginTop: MIN_DISTANCE_FROM_CORNERS,
625
+ marginBottom: MIN_DISTANCE_FROM_CORNERS,
626
+ paddingLeft: DISTANCE_FROM_ANCHOR
627
+ };
628
+
629
+ case "bottom":
630
+ return {
631
+ marginLeft: MIN_DISTANCE_FROM_CORNERS,
632
+ marginRight: MIN_DISTANCE_FROM_CORNERS,
633
+ paddingTop: DISTANCE_FROM_ANCHOR
634
+ };
635
+
636
+ case "left":
637
+ return {
638
+ marginTop: MIN_DISTANCE_FROM_CORNERS,
639
+ marginBottom: MIN_DISTANCE_FROM_CORNERS,
640
+ paddingRight: DISTANCE_FROM_ANCHOR
641
+ };
642
+
643
+ default:
644
+ throw new Error(`Unknown placement: ${placement}`);
645
+ }
646
+ }
647
+
648
+ _renderArrow() {
649
+ const {
650
+ trimlinePoints,
651
+ points,
652
+ height,
653
+ width
654
+ } = this._calculateDimensionsFromPlacement();
655
+
656
+ const {
657
+ color
658
+ } = this.props;
659
+ return /*#__PURE__*/createElement("svg", {
660
+ className: css(styles.arrow),
661
+ style: this._getArrowStyle(),
662
+ width: width,
663
+ height: height
664
+ }, this._maybeRenderDropshadow(points), /*#__PURE__*/createElement("polyline", {
665
+ fill: Colors[color],
666
+ stroke: Colors[color],
667
+ points: points.join(" ")
668
+ }), /*#__PURE__*/createElement("polyline", {
669
+ // Redraw the stroke on top of the background color,
670
+ // so that the ends aren't extra dark where they meet
671
+ // the border of the tooltip.
672
+ fill: Colors[color],
673
+ points: points.join(" "),
674
+ stroke: Colors.offBlack16
675
+ }), /*#__PURE__*/createElement("polyline", {
676
+ stroke: Colors[color],
677
+ points: trimlinePoints.join(" ")
678
+ }));
679
+ }
680
+
681
+ render() {
682
+ const {
683
+ offset,
684
+ placement,
685
+ updateRef
686
+ } = this.props;
687
+ return /*#__PURE__*/createElement(View, {
688
+ style: [styles.tailContainer, _extends({}, offset), this._getContainerStyle()],
689
+ "data-placement": placement,
690
+ ref: updateRef
691
+ }, this._renderArrow());
692
+ }
693
+
694
+ }
695
+ /**
696
+ * Some constants to make style generation easier to understand.
697
+ * NOTE: The widths and heights refer to the downward-pointing tail
698
+ * (i.e. placement="top"). When the tail points to the left or right instead,
699
+ * the width/height are inverted.
700
+ */
701
+
702
+ TooltipTail.defaultProps = {
703
+ color: "white"
704
+ };
705
+ const DISTANCE_FROM_ANCHOR = Spacing.xSmall_8;
706
+ const MIN_DISTANCE_FROM_CORNERS = Spacing.xSmall_8;
707
+ const ARROW_WIDTH = Spacing.large_24;
708
+ const ARROW_HEIGHT = Spacing.small_12;
709
+ const styles = StyleSheet.create({
710
+ /**
711
+ * Container
712
+ */
713
+ tailContainer: {
714
+ position: "relative",
715
+ pointerEvents: "none"
716
+ },
717
+
718
+ /**
719
+ * Arrow
720
+ */
721
+ arrow: {
722
+ // Ensure the dropshadow bleeds outside our bounds.
723
+ overflow: "visible"
724
+ }
725
+ });
726
+
727
+ class TooltipBubble extends Component {
728
+ constructor(...args) {
729
+ super(...args);
730
+ this.state = {
731
+ active: false
732
+ };
733
+
734
+ this.handleMouseEnter = () => {
735
+ this._setActiveState(true);
736
+ };
737
+
738
+ this.handleMouseLeave = () => {
739
+ this.props.onActiveChanged(false);
740
+ };
741
+ }
742
+
743
+ _setActiveState(active) {
744
+ this.setState({
745
+ active
746
+ });
747
+ this.props.onActiveChanged(active);
748
+ }
749
+
750
+ render() {
751
+ const {
752
+ id,
753
+ children,
754
+ updateBubbleRef,
755
+ placement,
756
+ isReferenceHidden,
757
+ style,
758
+ updateTailRef,
759
+ tailOffset
760
+ } = this.props;
761
+ return /*#__PURE__*/createElement(View, {
762
+ id: id,
763
+ role: "tooltip",
764
+ "data-placement": placement,
765
+ onMouseEnter: this.handleMouseEnter,
766
+ onMouseLeave: this.handleMouseLeave,
767
+ ref: updateBubbleRef,
768
+ style: [isReferenceHidden && styles$1.hide, styles$1.bubble, styles$1[`content-${placement}`], style]
769
+ }, /*#__PURE__*/createElement(View, {
770
+ style: styles$1.content
771
+ }, children), /*#__PURE__*/createElement(TooltipTail, {
772
+ updateRef: updateTailRef,
773
+ placement: placement,
774
+ offset: tailOffset
775
+ }));
776
+ }
777
+
778
+ }
779
+ const styles$1 = StyleSheet.create({
780
+ bubble: {
781
+ position: "absolute"
782
+ },
783
+
784
+ /**
785
+ * The hide style ensures that the bounds of the bubble stay unchanged.
786
+ * This is because popper.js calculates the bubble position based off its
787
+ * bounds and if we stopped rendering it entirely, it wouldn't know where to
788
+ * place it when it reappeared.
789
+ */
790
+ hide: {
791
+ pointerEvents: "none",
792
+ opacity: 0,
793
+ backgroundColor: "transparent",
794
+ color: "transparent"
795
+ },
796
+
797
+ /**
798
+ * Ensure the content and tail are properly arranged.
799
+ */
800
+ "content-top": {
801
+ flexDirection: "column"
802
+ },
803
+ "content-right": {
804
+ flexDirection: "row-reverse"
805
+ },
806
+ "content-bottom": {
807
+ flexDirection: "column-reverse"
808
+ },
809
+ "content-left": {
810
+ flexDirection: "row"
811
+ },
812
+ content: {
813
+ maxWidth: 472,
814
+ borderRadius: Spacing.xxxSmall_4,
815
+ border: `solid 1px ${Colors.offBlack16}`,
816
+ backgroundColor: Colors.white,
817
+ boxShadow: `0 ${Spacing.xSmall_8}px ${Spacing.xSmall_8}px 0 ${Colors.offBlack8}`,
818
+ justifyContent: "center"
819
+ }
820
+ });
821
+
822
+ /**
823
+ * This component is used to provide the content that is to be rendered in the
824
+ * tooltip bubble.
825
+ */
826
+ class TooltipContent extends Component {
827
+ _renderTitle() {
828
+ const {
829
+ title
830
+ } = this.props;
831
+
832
+ if (title) {
833
+ if (typeof title === "string") {
834
+ return /*#__PURE__*/createElement(HeadingSmall, null, title);
835
+ } else {
836
+ return title;
837
+ }
838
+ }
839
+
840
+ return null;
841
+ }
842
+
843
+ _renderChildren() {
844
+ const {
845
+ children
846
+ } = this.props;
847
+
848
+ if (typeof children === "string") {
849
+ return /*#__PURE__*/createElement(LabelMedium, null, children);
850
+ } else {
851
+ return children;
852
+ }
853
+ }
854
+
855
+ render() {
856
+ const title = this._renderTitle();
857
+
858
+ const children = this._renderChildren();
859
+
860
+ const containerStyle = title ? styles$2.withTitle : styles$2.withoutTitle;
861
+ return /*#__PURE__*/createElement(View, {
862
+ style: containerStyle
863
+ }, title, title && children && /*#__PURE__*/createElement(Strut, {
864
+ size: Spacing.xxxSmall_4
865
+ }), children);
866
+ }
867
+
868
+ }
869
+ const styles$2 = StyleSheet.create({
870
+ withoutTitle: {
871
+ padding: `10px ${Spacing.medium_16}px`
872
+ },
873
+ withTitle: {
874
+ padding: Spacing.medium_16
875
+ }
876
+ });
877
+
878
+ /**
879
+ * This is a little helper that we can use to wrap the react-popper reference
880
+ * update methods so that we can convert a regular React ref into a DOM node
881
+ * as react-popper expects, and also ensure we only update react-popper
882
+ * on actual changes, and not just renders of the same thing.
883
+ */
884
+ class RefTracker {
885
+ constructor() {
886
+ this.updateRef = ref => {
887
+ if (ref) {
888
+ // We only want to update the reference if it is
889
+ // actually changed. Otherwise, we can trigger another render that
890
+ // would then update the reference again and just keep looping.
891
+ const domNode = findDOMNode(ref);
892
+
893
+ if (domNode instanceof HTMLElement && domNode !== this._lastRef) {
894
+ this._lastRef = domNode;
895
+ this._targetFn && this._targetFn(domNode);
896
+ }
897
+ }
898
+ };
899
+
900
+ this.setCallback = targetFn => {
901
+ if (this._targetFn !== targetFn) {
902
+ if (targetFn && typeof targetFn !== "function") {
903
+ throw new Error("targetFn must be a function");
904
+ }
905
+
906
+ this._targetFn = targetFn || null;
907
+
908
+ if (this._lastRef && this._targetFn) {
909
+ this._targetFn(this._lastRef);
910
+ }
911
+ }
912
+ };
913
+ }
914
+
915
+ }
916
+
917
+ /**
918
+ * This component is a light wrapper for react-popper, allowing us to position
919
+ * and control the tooltip bubble location and visibility as we need.
920
+ */
921
+ class TooltipPopper extends Component {
922
+ constructor(...args) {
923
+ super(...args);
924
+ this._bubbleRefTracker = new RefTracker();
925
+ this._tailRefTracker = new RefTracker();
926
+ }
927
+
928
+ _renderPositionedContent(popperProps) {
929
+ const {
930
+ children
931
+ } = this.props; // We'll hide some complexity from the children here and ensure
932
+ // that our placement always has a value.
933
+
934
+ const placement = // We know that popperProps.placement will only be one of our
935
+ // supported values, so just cast it.
936
+ popperProps.placement || this.props.placement; // Just in case the callbacks have changed, let's update our reference
937
+ // trackers.
938
+
939
+ this._bubbleRefTracker.setCallback(popperProps.ref);
940
+
941
+ this._tailRefTracker.setCallback(popperProps.arrowProps.ref); // Here we translate from the react-popper's PropperChildrenProps
942
+ // to our own TooltipBubbleProps.
943
+
944
+
945
+ const bubbleProps = {
946
+ placement,
947
+ style: {
948
+ // NOTE(jeresig): We can't just use `popperProps.style` here
949
+ // as the Flow type doesn't match Aphrodite's CSS flow props
950
+ // (as it doesn't camelCase props). So we just copy over the
951
+ // props that we need, instead.
952
+ top: popperProps.style.top,
953
+ left: popperProps.style.left,
954
+ bottom: popperProps.style.bottom,
955
+ right: popperProps.style.right,
956
+ position: popperProps.style.position,
957
+ transform: popperProps.style.transform
958
+ },
959
+ updateBubbleRef: this._bubbleRefTracker.updateRef,
960
+ tailOffset: {
961
+ bottom: popperProps.arrowProps.style.bottom,
962
+ right: popperProps.arrowProps.style.right,
963
+ top: popperProps.arrowProps.style.top,
964
+ left: popperProps.arrowProps.style.left,
965
+ transform: popperProps.arrowProps.style.transform
966
+ },
967
+ updateTailRef: this._tailRefTracker.updateRef,
968
+ isReferenceHidden: popperProps.isReferenceHidden
969
+ };
970
+ return children(bubbleProps);
971
+ }
972
+
973
+ render() {
974
+ const {
975
+ anchorElement,
976
+ placement
977
+ } = this.props;
978
+ return /*#__PURE__*/createElement(Popper, {
979
+ referenceElement: anchorElement,
980
+ placement: placement,
981
+ modifiers: [{
982
+ name: "preventOverflow",
983
+ options: {
984
+ rootBoundary: "document"
985
+ }
986
+ }]
987
+ }, props => this._renderPositionedContent(props));
988
+ }
989
+
990
+ }
991
+
992
+ /**
993
+ * The Tooltip component provides the means to anchor some additional
994
+ * information to some content. The additional information is shown in a
995
+ * callout that hovers above the page content. This additional information is
996
+ * invoked by hovering over the anchored content, or focusing all or part of the
997
+ * anchored content.
998
+ *
999
+ * This component is structured as follows:
1000
+ *
1001
+ * Tooltip (this component)
1002
+ * - TooltipAnchor (provides hover/focus behaviors on anchored content)
1003
+ * - TooltipPortalMounter (creates portal into which the callout is rendered)
1004
+ * --------------------------- [PORTAL BOUNDARY] ------------------------------
1005
+ * - TooltipPopper (provides positioning for the callout using react-popper)
1006
+ * - TooltipBubble (renders the callout borders, background and shadow)
1007
+ * - TooltipContent (renders the callout content; the actual information)
1008
+ * - TooltipTail (renders the callout tail and shadow that points from the
1009
+ * callout to the anchor content)
1010
+ */
1011
+ class Tooltip extends Component {
1012
+ constructor(...args) {
1013
+ super(...args);
1014
+ this.state = {
1015
+ active: false,
1016
+ activeBubble: false,
1017
+ anchorElement: null
1018
+ };
1019
+ }
1020
+
1021
+ _updateAnchorElement(ref) {
1022
+ if (ref && ref !== this.state.anchorElement) {
1023
+ this.setState({
1024
+ anchorElement: ref
1025
+ });
1026
+ }
1027
+ }
1028
+
1029
+ _renderBubbleContent() {
1030
+ const {
1031
+ title,
1032
+ content
1033
+ } = this.props;
1034
+
1035
+ if (typeof content === "string") {
1036
+ return /*#__PURE__*/createElement(TooltipContent, {
1037
+ title: title
1038
+ }, content);
1039
+ } else if (title) {
1040
+ return /*#__PURE__*/cloneElement(content, {
1041
+ title
1042
+ });
1043
+ } else {
1044
+ return content;
1045
+ }
1046
+ }
1047
+
1048
+ _renderPopper(ids) {
1049
+ const {
1050
+ id
1051
+ } = this.props;
1052
+ const bubbleId = ids ? ids.get(Tooltip.ariaContentId) : id;
1053
+
1054
+ if (!bubbleId) {
1055
+ throw new Error("Did not get an identifier factory nor a id prop");
1056
+ }
1057
+
1058
+ const {
1059
+ placement
1060
+ } = this.props;
1061
+ return /*#__PURE__*/createElement(TooltipPopper, {
1062
+ anchorElement: this.state.anchorElement,
1063
+ placement: placement
1064
+ }, props => /*#__PURE__*/createElement(TooltipBubble, {
1065
+ id: bubbleId,
1066
+ style: props.style,
1067
+ tailOffset: props.tailOffset,
1068
+ isReferenceHidden: props.isReferenceHidden,
1069
+ placement: props.placement,
1070
+ updateTailRef: props.updateTailRef,
1071
+ updateBubbleRef: props.updateBubbleRef,
1072
+ onActiveChanged: active => this.setState({
1073
+ activeBubble: active
1074
+ })
1075
+ }, this._renderBubbleContent()));
1076
+ }
1077
+
1078
+ _getHost() {
1079
+ const {
1080
+ anchorElement
1081
+ } = this.state;
1082
+ return maybeGetPortalMountedModalHostElement(anchorElement) || document.body;
1083
+ }
1084
+
1085
+ _renderTooltipAnchor(ids) {
1086
+ const {
1087
+ children,
1088
+ forceAnchorFocusivity
1089
+ } = this.props;
1090
+ const {
1091
+ active,
1092
+ activeBubble
1093
+ } = this.state;
1094
+
1095
+ const popperHost = this._getHost(); // TODO(kevinb): update to use ReactPopper's React 16-friendly syntax
1096
+
1097
+
1098
+ return /*#__PURE__*/createElement(Fragment, null, /*#__PURE__*/createElement(TooltipAnchor, {
1099
+ forceAnchorFocusivity: forceAnchorFocusivity,
1100
+ anchorRef: r => this._updateAnchorElement(r),
1101
+ onActiveChanged: active => this.setState({
1102
+ active
1103
+ }),
1104
+ ids: ids
1105
+ }, children), popperHost && (active || activeBubble) && /*#__PURE__*/createPortal(this._renderPopper(ids), popperHost));
1106
+ }
1107
+
1108
+ render() {
1109
+ const {
1110
+ id
1111
+ } = this.props;
1112
+
1113
+ if (id) {
1114
+ // Let's bypass the extra weight of an id provider since we don't
1115
+ // need it.
1116
+ return this._renderTooltipAnchor();
1117
+ } else {
1118
+ return /*#__PURE__*/createElement(UniqueIDProvider, {
1119
+ scope: "tooltip",
1120
+ mockOnFirstRender: true
1121
+ }, ids => this._renderTooltipAnchor(ids));
1122
+ }
1123
+ }
1124
+
1125
+ }
1126
+ Tooltip.defaultProps = {
1127
+ forceAnchorFocusivity: true,
1128
+ placement: "top"
1129
+ };
1130
+ Tooltip.ariaContentId = "aria-content";
1131
+
1132
+ export default Tooltip;
1133
+ export { TooltipContent, TooltipPopper, TooltipTail };