Files: 8d409051a8f9c8f004d964d1c5cac5e5b8649a01 / modules / app / link-preview.js
2302 bytesRaw
1 | var { h, Value } = require('mutant') |
2 | var ObserveLinkHover = require('../../lib/observe-link-hover') |
3 | var ref = require('ssb-ref') |
4 | |
5 | var nest = require('depnest') |
6 | |
7 | exports.needs = nest({ |
8 | 'intl.sync.i18n': 'first', |
9 | 'profile.html.preview': 'first' |
10 | }) |
11 | |
12 | exports.gives = nest('app.linkPreview') |
13 | |
14 | exports.create = function (api) { |
15 | var i18n = api.intl.sync.i18n |
16 | return nest('app.linkPreview', function (container, delay) { |
17 | var currentHover = ObserveLinkHover(container, 500) |
18 | var previewElement = Value() |
19 | |
20 | currentHover(element => { |
21 | var href = element && element.getAttribute('href') |
22 | var preview = null |
23 | |
24 | if (href) { |
25 | if (ref.isFeed(href)) { |
26 | preview = api.profile.html.preview(href) |
27 | preview.onwheel = previewElement.cancel |
28 | } else if (href.includes('://')) { |
29 | preview = h('ProfilePreview', [ |
30 | h('section', [ |
31 | h('strong', [i18n('External Link'), ' ๐']), h('br'), |
32 | h('code', href) |
33 | ]) |
34 | ]) |
35 | } |
36 | } |
37 | |
38 | if (preview) { |
39 | var rect = element.getBoundingClientRect() |
40 | var width = 510 |
41 | var maxLeft = window.innerWidth - width |
42 | var maxTop = window.innerHeight - 100 |
43 | var distanceFromRight = window.innerWidth - rect.right |
44 | var shouldDisplayBeside = rect.bottom > maxTop || rect.left < 50 || distanceFromRight < 50 |
45 | |
46 | if (shouldDisplayBeside && rect.bottom > 50) { |
47 | if (rect.right > maxLeft && (rect.left - width) < 0) { |
48 | // no room, just give up! |
49 | previewElement.set(null) |
50 | return |
51 | } else { |
52 | preview.style.top = `${Math.min(rect.top, maxTop)}px` |
53 | if (rect.right > maxLeft) { |
54 | preview.style.left = `${rect.left - width}px` |
55 | } else { |
56 | preview.style.left = `${rect.right + 5}px` |
57 | } |
58 | } |
59 | } else { |
60 | preview.style.top = `${rect.bottom + 5}px` |
61 | preview.style.left = `${Math.min(rect.left, maxLeft)}px` |
62 | } |
63 | |
64 | previewElement.set(preview) |
65 | } else if (element !== false) { |
66 | previewElement.set(null) |
67 | } |
68 | }) |
69 | |
70 | previewElement.cancel = function () { |
71 | currentHover.cancel() |
72 | previewElement.set(null) |
73 | } |
74 | |
75 | return previewElement |
76 | }) |
77 | } |
78 |
Built with git-ssb-web