git ssb

16+

Dominic / patchbay



Tree: 03ce3474ce130d4761d364412f79db838997ddb9

Files: 03ce3474ce130d4761d364412f79db838997ddb9 / message / html / compose.js

9353 bytesRaw
1const { h, when, send, resolve, Value, Array: MutantArray, computed } = require('mutant')
2const nest = require('depnest')
3const ssbMentions = require('ssb-mentions')
4const extend = require('xtend')
5const addSuggest = require('suggest-box')
6const blobFiles = require('ssb-blob-files')
7const get = require('lodash/get')
8const datSharedFiles = require('dat-shared-files/lib')
9
10exports.gives = nest('message.html.compose')
11
12exports.needs = nest({
13 'about.async.suggest': 'first',
14 'channel.async.suggest': 'first',
15 'emoji.async.suggest': 'first',
16 'meme.async.suggest': 'first',
17 'message.html.confirm': 'first',
18 'drafts.sync.get': 'first',
19 'drafts.sync.set': 'first',
20 'drafts.sync.remove': 'first',
21 'settings.obs.get': 'first',
22 'sbot.obs.connection': 'first'
23})
24
25exports.create = function (api) {
26 return nest({ 'message.html.compose': compose })
27
28 function compose (options, cb) {
29 const {
30 meta,
31 location,
32 feedIdsInThread = [],
33 prepublish,
34 placeholder = 'Write a message',
35 shrink = true
36 } = options
37
38 if (typeof resolve(meta) !== 'object') throw new Error('Compose needs meta data about what sort of message composer you are making')
39 if (!location) throw new Error('Compose expects a unique location so it can save drafts of messages')
40
41 var files = []
42 var filesById = {}
43 var channelInputFocused = Value(false)
44 var textAreaFocused = Value(false)
45 var focused = computed([channelInputFocused, textAreaFocused], (a, b) => a || b)
46 var hasContent = Value(false)
47
48 var blurTimeout = null
49
50 var expanded = computed([shrink, focused, hasContent], (shrink, focused, hasContent) => {
51 if (!shrink || hasContent) return true
52
53 return focused
54 })
55
56 var channelInput = h('input.channel', {
57 'ev-input': () => hasContent.set(!!channelInput.value),
58 'ev-keyup': ev => {
59 ev.target.value = ev.target.value.replace(/^#*([\w@%&])/, '#$1')
60 },
61 'ev-blur': () => {
62 clearTimeout(blurTimeout)
63 blurTimeout = setTimeout(() => channelInputFocused.set(false), 200)
64 },
65 'ev-focus': send(channelInputFocused.set, true),
66 placeholder: '#channel (optional)',
67 value: computed(meta.channel, ch => ch ? '#' + ch : null),
68 disabled: meta.channel ? true : undefined,
69 title: meta.channel ? 'Reply is in same channel as original message' : undefined
70 })
71
72 var draftPerstTimeout = null
73 var draftLocation = location
74 var textArea = h('textarea', {
75 'ev-input': () => {
76 hasContent.set(!!textArea.value)
77 clearTimeout(draftPerstTimeout)
78 draftPerstTimeout = setTimeout(() => {
79 api.drafts.sync.set(draftLocation, textArea.value)
80 }, 200)
81 },
82 'ev-blur': () => {
83 clearTimeout(blurTimeout)
84 blurTimeout = setTimeout(() => textAreaFocused.set(false), 200)
85 },
86 'ev-focus': send(textAreaFocused.set, true),
87 'ev-paste': ev => {
88 const files = get(ev, 'clipboardData.files')
89 if (!files || !files.length) return
90 const opts = {
91 stripExif: api.settings.obs.get('patchbay.removeExif', true),
92 isPrivate
93 }
94
95 blobFiles(files, api.sbot.obs.connection, opts, afterBlobed)
96 },
97 placeholder
98 })
99
100 textArea.publish = publish // TODO: fix - clunky api for the keyboard shortcut to target
101
102 // load draft
103 let draft = api.drafts.sync.get(draftLocation)
104 if (typeof draft === 'string') {
105 textArea.value = draft
106 hasContent.set(true)
107 }
108
109 var isPrivate = location.page === 'private' ||
110 (location.key && !location.value) ||
111 (location.value && location.value.private)
112
113 var warningMessages = MutantArray([])
114 var warning = computed(warningMessages, msgs => {
115 if (!msgs.length) return
116
117 return h('section.warnings', msgs.map((m, i) => {
118 return h('div.warning', [
119 h('i.fa.fa-exclamation-triangle'),
120 h('div.message', m),
121 h('i.fa.fa-times', { 'ev-click': () => warningMessages.deleteAt(i) })
122 ])
123 }))
124 })
125
126 var ssbBlobInput = h('input -ssb', {
127 type: 'file',
128 // accept,
129 attributes: { multiple: true, title: 'Add files as blobs' },
130 'ev-click': () => hasContent.set(true),
131 'ev-change': (ev) => {
132 warningMessages.set([])
133
134 const files = ev.target.files
135 const opts = {
136 stripExif: api.settings.obs.get('patchbay.removeExif', true),
137 isPrivate
138 }
139 blobFiles(files, api.sbot.obs.connection, opts, afterBlobed)
140 }
141 })
142 function afterBlobed (err, result) {
143 if (err) {
144 console.error(err)
145 warningMessages.push(err.message)
146 return
147 }
148
149 files.push(result)
150 filesById[result.link] = result
151
152 const pos = textArea.selectionStart
153 const embed = result.type.match(/^image/) ? '!' : ''
154 const spacer = embed ? '\n' : ' '
155 const insertLink = spacer + embed + '[' + result.name + ']' + '(' + result.link + ')' + spacer
156
157 textArea.value = textArea.value.slice(0, pos) + insertLink + textArea.value.slice(pos)
158
159 console.log('added:', result)
160 }
161
162 var datBlobInput = h('input -dat', {
163 type: 'file',
164 attributes: { title: 'Add file as dat link' },
165 'ev-click': () => hasContent.set(true),
166 'ev-change': (ev) => {
167 const file = ev.target.files[0]
168 datSharedFiles.shareFile(file.path, (datLink) => {
169 const pos = textArea.selectionStart
170 const insertLink = '[' + file.name + ']' + '(' + datLink + '/' + file.name + ')'
171
172 textArea.value = textArea.value.slice(0, pos) + insertLink + textArea.value.slice(pos)
173 })
174 }
175 })
176
177 var isPublishing = Value(false)
178 var publishBtn = h('button', { 'ev-click': publish, disabled: isPublishing }, isPrivate ? 'Reply' : 'Publish')
179
180 var actions = h('section.actions', [
181 h('div.attach', [
182 h('i.fa.fa-paperclip'),
183 h('div.attachers', [
184 h('div.attacher', { 'ev-click': () => ssbBlobInput.click() }, [
185 h('i.fa.fa-file-o'),
186 h('div.label', 'small file(s)'),
187 h('div.subtext', '< 5MB')
188 ]),
189 h('div.attacher', { 'ev-click': () => datBlobInput.click() }, [
190 h('i.fa.fa-file-archive-o'),
191 h('div.label', 'large file'),
192 h('div.subtext', 'DAT archive, (BETA)')
193 ]),
194 ssbBlobInput,
195 datBlobInput
196 ])
197 ]),
198 publishBtn
199 ])
200
201 var composer = h('Compose', {
202 classList: when(expanded, '-expanded', '-contracted')
203 }, [
204 channelInput,
205 textArea,
206 warning,
207 actions
208 ])
209
210 composer.addQuote = function (data) {
211 try {
212 if (typeof data.content.text === 'string') {
213 var text = data.content.text
214 textArea.value += '> ' + text.replace(/\r\n|\r|\n/g, '\n> ') + '\r\n\n'
215 hasContent.set(!!textArea.value)
216 }
217 } catch (err) {
218 // object not have text or content
219 }
220 }
221
222 if (location.action === 'quote') { composer.addQuote(location.value) }
223
224 addSuggest(channelInput, (inputText, cb) => {
225 if (inputText[0] === '#') {
226 api.channel.async.suggest(inputText.slice(1), cb)
227 }
228 }, { cls: 'PatchSuggest' })
229 channelInput.addEventListener('suggestselect', ev => {
230 channelInput.value = ev.detail.id // HACK : this over-rides the markdown value
231 })
232
233 addSuggest(textArea, (inputText, cb) => {
234 const char = inputText[0]
235 const wordFragment = inputText.slice(1)
236
237 if (char === '@') api.about.async.suggest(wordFragment, feedIdsInThread, cb)
238 if (char === '#') api.channel.async.suggest(wordFragment, cb)
239 if (char === ':') api.emoji.async.suggest(wordFragment, cb)
240 if (char === '&') api.meme.async.suggest(wordFragment, cb)
241 }, { cls: 'PatchSuggest' })
242
243 return composer
244
245 // scoped
246
247 function publish () {
248 if (resolve(isPublishing)) return
249 isPublishing.set(true)
250
251 const channel = channelInput.value.startsWith('#')
252 ? channelInput.value.substr(1).trim()
253 : channelInput.value.trim()
254 const mentions = ssbMentions(textArea.value).map(mention => {
255 // merge markdown-detected mention with file info
256 var file = filesById[mention.link]
257 if (file) {
258 if (file.type) mention.type = file.type
259 if (file.size) mention.size = file.size
260 }
261 return mention
262 })
263
264 var content = extend(resolve(meta), {
265 text: textArea.value,
266 channel,
267 mentions
268 })
269
270 if (!channel) delete content.channel
271 if (!mentions.length) delete content.mentions
272 if (content.recps && content.recps.length === 0) delete content.recps
273
274 try {
275 if (typeof prepublish === 'function') {
276 content = prepublish(content)
277 }
278 } catch (err) {
279 isPublishing.set(false)
280 if (cb) cb(err)
281 else throw err
282 }
283
284 return api.message.html.confirm(content, done)
285
286 function done (err, msg) {
287 isPublishing.set(false)
288 if (err) throw err
289 else if (msg) {
290 textArea.value = ''
291 api.drafts.sync.remove(draftLocation)
292 }
293 if (cb) cb(err, msg)
294 }
295 }
296 }
297}
298

Built with git-ssb-web