git ssb

0+

alanz / patchwork



forked from Matt McKegg / patchwork

Tree: 1e3b2969c5517cbd13a47f312ed441add9c8900f

Files: 1e3b2969c5517cbd13a47f312ed441add9c8900f / modules / app / link-preview.js

2592 bytesRaw
1var { h, Value } = 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 currentHover(element => {
33 var href = element && element.getAttribute('href')
34 var preview = null
35
36 if (href) {
37 if (ref.isFeed(href)) {
38 preview = api.profile.html.preview(href)
39 preview.onwheel = previewElement.cancel
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 var rect = element.getBoundingClientRect()
52 var width = 510
53 var maxLeft = window.innerWidth - width
54 var maxTop = window.innerHeight - 100
55 var distanceFromRight = window.innerWidth - rect.right
56 var shouldDisplayBeside = rect.bottom > maxTop || rect.left < 50 || distanceFromRight < 50
57
58 if (shouldDisplayBeside && rect.bottom > 50) {
59 if (rect.right > maxLeft && (rect.left - width) < 0) {
60 // no room, just give up!
61 previewElement.set(null)
62 return
63 } else {
64 preview.style.top = `${Math.min(rect.top, maxTop)}px`
65 if (rect.right > maxLeft) {
66 preview.style.left = `${rect.left - width}px`
67 } else {
68 preview.style.left = `${rect.right + 5}px`
69 }
70 }
71 } else {
72 preview.style.top = `${rect.bottom + 5}px`
73 preview.style.left = `${Math.min(rect.left, maxLeft)}px`
74 }
75
76 previewElement.set(preview)
77 } else if (element !== false) {
78 previewElement.set(null)
79 }
80 })
81
82 previewElement.cancel = function () {
83 currentHover.cancel()
84 previewElement.set(null)
85 }
86
87 return previewElement
88 })
89}
90

Built with git-ssb-web