Files: b8dcb5e1ae317132d4e8498b59e5279fcf92490f / modules / app / link-preview.js
2702 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 | |
18 | var currentHover = ObserveLinkHover(container, (value, lastValue) => { |
19 | var href = value && value.getAttribute('href') |
20 | var oldHref = lastValue && lastValue.getAttribute('href') |
21 | |
22 | var delay = 500 |
23 | if (href && oldHref) { |
24 | delay = 100 |
25 | } else if (!value) { |
26 | delay = 200 |
27 | } |
28 | |
29 | return delay |
30 | }) |
31 | var previewElement = Value() |
32 | |
33 | currentHover(element => { |
34 | var href = element && element.getAttribute('href') |
35 | var preview = null |
36 | |
37 | if (href) { |
38 | if (ref.isFeed(href)) { |
39 | preview = api.profile.html.preview(href) |
40 | } else if (href.includes('://')) { |
41 | preview = h('ProfilePreview', [ |
42 | h('section', [ |
43 | h('strong', [i18n('External Link'), ' ๐']), h('br'), |
44 | h('code', href) |
45 | ]) |
46 | ]) |
47 | } |
48 | } |
49 | |
50 | if (preview) { |
51 | preview.addEventListener('wheel', previewElement.cancel) |
52 | var rect = element.getBoundingClientRect() |
53 | var width = 510 |
54 | var maxLeft = window.innerWidth - width |
55 | var maxTop = window.innerHeight - 100 |
56 | var distanceFromRight = window.innerWidth - rect.right |
57 | var shouldDisplayBeside = rect.bottom > maxTop || rect.left < 50 || distanceFromRight < 50 |
58 | |
59 | if (shouldDisplayBeside && rect.bottom > 50) { |
60 | if (rect.right > maxLeft && (rect.left - width) < 0) { |
61 | // no room, just give up! |
62 | previewElement.set(null) |
63 | return |
64 | } else { |
65 | preview.style.top = `${Math.min(rect.top, maxTop)}px` |
66 | if (rect.right > maxLeft) { |
67 | preview.style.left = `${rect.left - width}px` |
68 | } else { |
69 | preview.style.left = `${rect.right + 5}px` |
70 | } |
71 | } |
72 | } else { |
73 | preview.style.top = `${rect.bottom + 5}px` |
74 | preview.style.left = `${Math.min(rect.left, maxLeft)}px` |
75 | } |
76 | |
77 | previewElement.set(preview) |
78 | } else if (element !== false) { |
79 | previewElement.set(null) |
80 | } |
81 | }) |
82 | |
83 | previewElement.cancel = function () { |
84 | currentHover.cancel() |
85 | previewElement.set(null) |
86 | } |
87 | |
88 | // hide preview on scroll |
89 | container.addEventListener('wheel', previewElement.cancel) |
90 | |
91 | return previewElement |
92 | }) |
93 | } |
94 |
Built with git-ssb-web