git ssb

10+

Matt McKegg / patchwork



Tree: 593dfd760dee299082f615e02f2747f1c6f660ec

Files: 593dfd760dee299082f615e02f2747f1c6f660ec / modules / app / link-preview.js

2845 bytesRaw
1var { h, Value, computed } = require('mutant')
2var ObserveLinkHover = require('../../lib/observe-link-hover')
3var ref = require('ssb-ref')
4
5var nest = require('depnest')
6
7exports.needs = nest({
8 'intl.sync.i18n': 'first',
9 'profile.html.preview': 'first'
10})
11
12exports.gives = nest('app.linkPreview')
13
14exports.create = function (api) {
15 var i18n = api.intl.sync.i18n
16 return nest('app.linkPreview', function (container, delay) {
17 var currentHover = ObserveLinkHover(container, (value, lastValue) => {
18 var href = value && value.getAttribute('href')
19 var oldHref = lastValue && lastValue.getAttribute('href')
20
21 var delay = 500
22 if (href && oldHref) {
23 delay = 100
24 } else if (!value) {
25 delay = 200
26 }
27
28 return delay
29 })
30 var previewElement = Value()
31
32 // hide preview on scroll
33 var hasPreview = computed(previewElement, x => !!x)
34 hasPreview(value => {
35 if (value) {
36 window.addEventListener('wheel', previewElement.cancel)
37 } else {
38 window.removeEventListener('wheel', previewElement.cancel)
39 }
40 })
41
42 currentHover(element => {
43 var href = element && element.getAttribute('href')
44 var preview = null
45
46 if (href) {
47 if (ref.isFeed(href)) {
48 preview = api.profile.html.preview(href)
49 } else if (href.includes('://')) {
50 preview = h('ProfilePreview', [
51 h('section', [
52 h('strong', [i18n('External Link'), ' ๐ŸŒ']), h('br'),
53 h('code', href)
54 ])
55 ])
56 }
57 }
58
59 if (preview) {
60 var rect = element.getBoundingClientRect()
61 var width = 510
62 var maxLeft = window.innerWidth - width
63 var maxTop = window.innerHeight - 100
64 var distanceFromRight = window.innerWidth - rect.right
65 var shouldDisplayBeside = rect.bottom > maxTop || rect.left < 50 || distanceFromRight < 50
66
67 if (shouldDisplayBeside && rect.bottom > 50) {
68 if (rect.right > maxLeft && (rect.left - width) < 0) {
69 // no room, just give up!
70 previewElement.set(null)
71 return
72 } else {
73 preview.style.top = `${Math.min(rect.top, maxTop)}px`
74 if (rect.right > maxLeft) {
75 preview.style.left = `${rect.left - width}px`
76 } else {
77 preview.style.left = `${rect.right + 5}px`
78 }
79 }
80 } else {
81 preview.style.top = `${rect.bottom + 5}px`
82 preview.style.left = `${Math.min(rect.left, maxLeft)}px`
83 }
84
85 previewElement.set(preview)
86 } else if (element !== false) {
87 previewElement.set(null)
88 }
89 })
90
91 previewElement.cancel = function () {
92 currentHover.cancel()
93 previewElement.set(null)
94 }
95
96 return previewElement
97 })
98}
99

Built with git-ssb-web