~vpzom/hitide

ref: ec9a80efb3340d4254c460526cd698baa9a92314 hitide/src/components/mod.rs -rw-r--r-- 18.7 KiB
ec9a80ef — Colin Reeder Limit post titles to one line in lists 3 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
pub mod timeago;

use std::borrow::{Borrow, Cow};
use std::collections::HashMap;

use crate::resp_types::{
    RespCommentInfo, RespMinimalAuthorInfo, RespMinimalCommentInfo, RespMinimalCommunityInfo,
    RespNotification, RespNotificationInfo, RespPostCommentInfo, RespPostInfo, RespPostListPost,
    RespThingComment, RespThingInfo,
};
use crate::util::{abbreviate_link, author_is_me};
use crate::PageBaseData;

pub use timeago::TimeAgo;

#[render::component]
pub fn Comment<'a>(
    comment: &'a RespPostCommentInfo<'a>,
    base_data: &'a PageBaseData,
    lang: &'a crate::Translator,
) {
    render::rsx! {
        <li class={"comment"}>
            {
                if base_data.login.is_some() {
                    Some(render::rsx! {
                        <div class={"votebox"}>
                            {
                                if comment.your_vote.is_some() {
                                    render::rsx! {
                                        <form method={"POST"} action={format!("/comments/{}/unlike", comment.as_ref().id)}>
                                            <button class={"iconbutton"} type={"submit"}>{hitide_icons::UPVOTED.img()}</button>
                                        </form>
                                    }
                                } else {
                                    render::rsx! {
                                        <form method={"POST"} action={format!("/comments/{}/like", comment.as_ref().id)}>
                                            <button class={"iconbutton"} type={"submit"}>{hitide_icons::UPVOTE.img()}</button>
                                        </form>
                                    }
                                }
                            }
                        </div>
                    })
                } else {
                    None
                }
            }
            <div class={"content"}>
                <small>
                    <cite><UserLink user={comment.author.as_ref()} /></cite>
                    {" "}
                    <TimeAgo since={chrono::DateTime::parse_from_rfc3339(&comment.created).unwrap()} lang />
                </small>
                <Content src={comment} />
                {
                    comment.attachments.iter().map(|attachment| {
                        let href = &attachment.url;
                        render::rsx! {
                            <div>
                                <strong>{lang.tr("comment_attachment_prefix", None)}</strong>
                                {" "}
                                <em><a href={href.as_ref()}>{abbreviate_link(&href)}{" ↗"}</a></em>
                            </div>
                        }
                    })
                    .collect::<Vec<_>>()
                }
                <div class={"actionList"}>
                    {
                        if base_data.login.is_some() {
                            Some(render::rsx! {
                                <a href={format!("/comments/{}", comment.as_ref().id)}>{lang.tr("reply", None)}</a>
                            })
                        } else {
                            None
                        }
                    }
                    {
                        if author_is_me(&comment.author, &base_data.login) || (comment.local && base_data.is_site_admin()) {
                            Some(render::rsx! {
                                <a href={format!("/comments/{}/delete", comment.as_ref().id)}>{lang.tr("delete", None)}</a>
                            })
                        } else {
                            None
                        }
                    }
                </div>
            </div>

            {
                if let Some(replies) = &comment.replies {
                        Some(render::rsx! {
                            <ul class={"commentList"}>
                                {
                                    replies.iter().map(|reply| {
                                        render::rsx! {
                                            <Comment comment={reply} base_data lang />
                                        }
                                    })
                                    .collect::<Vec<_>>()
                                }
                            </ul>
                        })
                } else {
                    None
                }
            }
            {
                if comment.replies.is_none() && comment.has_replies {
                    Some(render::rsx! {
                        <ul><li><a href={format!("/comments/{}", comment.as_ref().id)}>{"-> "}{lang.tr("view_more_comments", None)}</a></li></ul>
                    })
                } else {
                    None
                }
            }
        </li>
    }
}

pub struct CommunityLink<'community> {
    pub community: &'community RespMinimalCommunityInfo<'community>,
}
impl<'community> render::Render for CommunityLink<'community> {
    fn render_into<W: std::fmt::Write>(self, writer: &mut W) -> std::fmt::Result {
        let community = &self.community;

        let href = format!("/communities/{}", community.id);
        (render::rsx! {
            <a href={&href}>
            {
                (if community.local {
                    community.name.as_ref().into()
                } else {
                    Cow::Owned(format!("{}@{}", community.name, community.host))
                }).as_ref()
            }
            </a>
        })
        .render_into(writer)
    }
}

pub trait HavingContent {
    fn content_text(&self) -> Option<&str>;
    fn content_html(&self) -> Option<&str>;
}

impl<'a> HavingContent for RespMinimalCommentInfo<'a> {
    fn content_text(&self) -> Option<&str> {
        self.content_text.as_deref()
    }
    fn content_html(&self) -> Option<&str> {
        self.content_html.as_deref()
    }
}

impl<'a> HavingContent for RespThingComment<'a> {
    fn content_text(&self) -> Option<&str> {
        self.base.content_text()
    }
    fn content_html(&self) -> Option<&str> {
        self.base.content_html()
    }
}

impl<'a> HavingContent for RespPostCommentInfo<'a> {
    fn content_text(&self) -> Option<&str> {
        self.base.content_text()
    }
    fn content_html(&self) -> Option<&str> {
        self.base.content_html()
    }
}

impl<'a> HavingContent for RespCommentInfo<'a> {
    fn content_text(&self) -> Option<&str> {
        self.base.content_text()
    }
    fn content_html(&self) -> Option<&str> {
        self.base.content_html()
    }
}

impl<'a> HavingContent for RespPostInfo<'a> {
    fn content_text(&self) -> Option<&str> {
        self.content_text.as_deref()
    }
    fn content_html(&self) -> Option<&str> {
        self.content_html.as_deref()
    }
}

pub struct Content<'a, T: HavingContent + 'a> {
    pub src: &'a T,
}

impl<'a, T: HavingContent + 'a> render::Render for Content<'a, T> {
    fn render_into<W: std::fmt::Write>(self, writer: &mut W) -> std::fmt::Result {
        match self.src.content_html() {
            Some(html) => {
                let cleaned = ammonia::clean(&html);
                writer.write_str("<p>")?;
                render::raw!(cleaned.as_ref()).render_into(writer)?;
                writer.write_str("</p>")?;
            }
            None => {
                if let Some(text) = self.src.content_text() {
                    writer.write_str("<p>")?;
                    text.render_into(writer)?;
                    writer.write_str("</p>")?;
                }
            }
        }

        Ok(())
    }
}

#[render::component]
pub fn HTPage<'a, Children: render::Render>(
    base_data: &'a PageBaseData,
    lang: &'a crate::Translator,
    title: &'a str,
    children: Children,
) {
    render::rsx! {
        <>
            <render::html::HTML5Doctype />
            <html>
                <head>
                    <meta charset={"utf-8"} />
                    <link rel={"stylesheet"} href={"/static/main.css"} />
                    <title>{title}</title>
                </head>
                <body>
                    <header class={"mainHeader"}>
                        <div class={"left actionList"}>
                            <a href={"/"} class={"siteName"}>{"lotide"}</a>
                            <a href={"/all"}>{lang.tr("all", None)}</a>
                            <a href={"/communities"}>{lang.tr("communities", None)}</a>
                            <a href={"/about"}>{lang.tr("about", None)}</a>
                        </div>
                        <div class={"right actionList"}>
                            {
                                if let Some(login) =  &base_data.login {
                                    Some(render::rsx! {
                                        <>
                                            <a
                                                href={"/notifications"}
                                            >
                                                {
                                                    if login.user.has_unread_notifications {
                                                        hitide_icons::NOTIFICATIONS_SOME.img()
                                                    } else {
                                                        hitide_icons::NOTIFICATIONS.img()
                                                    }
                                                }
                                            </a>
                                            <a href={format!("/users/{}", login.user.id)}>
                                                {hitide_icons::PERSON.img()}
                                            </a>
                                            <form method={"POST"} action={"/logout"} class={"inline"}>
                                                <button type={"submit"} class={"iconbutton"}>
                                                    {hitide_icons::LOGOUT.img()}
                                                </button>
                                            </form>
                                        </>
                                    })
                                } else {
                                    None
                                }
                            }
                            {
                                if base_data.login.is_none() {
                                    Some(render::rsx! {
                                        <a href={"/login"}>{lang.tr("login", None)}</a>
                                    })
                                } else {
                                    None
                                }
                            }
                        </div>
                    </header>
                    {children}
                </body>
            </html>
        </>
    }
}

#[render::component]
pub fn PostItem<'a>(
    post: &'a RespPostListPost<'a>,
    in_community: bool,
    no_user: bool,
    lang: &'a crate::Translator,
) {
    render::rsx! {
        <li>
            <div class={"titleLine"}>
                <a href={format!("/posts/{}", post.as_ref().as_ref().id)}>
                    {post.as_ref().as_ref().title.as_ref()}
                </a>
                {
                    if let Some(href) = &post.as_ref().href {
                        Some(render::rsx! {
                            <em><a href={href.as_ref()}>{abbreviate_link(&href)}{" ↗"}</a></em>
                        })
                    } else {
                        None
                    }
                }
            </div>
            <small>
                {lang.tr("submitted", None)}
                {" "}
                <TimeAgo since={chrono::DateTime::parse_from_rfc3339(&post.as_ref().created).unwrap()} lang />
                {
                    if no_user {
                        None
                    } else {
                        Some(render::rsx! {
                            <>
                                {" "}{lang.tr("by", None)}{" "}<UserLink user={post.as_ref().author.as_ref()} />
                            </>
                        })
                    }
                }
                {
                    if !in_community {
                        Some(render::rsx! {
                            <>{" "}{lang.tr("to", None)}{" "}<CommunityLink community={&post.as_ref().community} /></>
                        })
                    } else {
                        None
                    }
                }
                {" | "}
                {lang.tr("post_comments_count", Some(&fluent::fluent_args!["count" => post.replies_count_total])).into_owned()}
            </small>
        </li>
    }
}

pub struct ThingItem<'a> {
    pub lang: &'a crate::Translator,
    pub thing: &'a RespThingInfo<'a>,
}

impl<'a> render::Render for ThingItem<'a> {
    fn render_into<W: std::fmt::Write>(self, writer: &mut W) -> std::fmt::Result {
        let lang = self.lang;

        match self.thing {
            RespThingInfo::Post(post) => {
                (PostItem { post, in_community: false, no_user: true, lang: self.lang }).render_into(writer)
            },
            RespThingInfo::Comment(comment) => {
                (render::rsx! {
                    <li>
                        <small>
                            <a href={format!("/comments/{}", comment.as_ref().id)}>{lang.tr("comment", None)}</a>
                            {" "}{lang.tr("on", None)}{" "}<a href={format!("/posts/{}", comment.post.id)}>{comment.post.title.as_ref()}</a>{":"}
                        </small>
                        <Content src={comment} />
                    </li>
                }).render_into(writer)
            }
        }
    }
}

pub struct UserLink<'user> {
    pub user: Option<&'user RespMinimalAuthorInfo<'user>>,
}

impl<'user> render::Render for UserLink<'user> {
    fn render_into<W: std::fmt::Write>(self, writer: &mut W) -> std::fmt::Result {
        match self.user {
            None => "[unknown]".render_into(writer),
            Some(user) => {
                let href = format!("/users/{}", user.id);
                (render::rsx! {
                    <a href={&href}>
                        {
                            (if user.local {
                                user.username.as_ref().into()
                            } else {
                                Cow::Owned(format!("{}@{}", user.username, user.host))
                            }).as_ref()
                        }
                    </a>
                })
                .render_into(writer)
            }
        }
    }
}

pub trait GetIndex<K, V> {
    fn get(&self, key: K) -> Option<&V>;
}

impl<K: Borrow<Q> + Eq + std::hash::Hash, V, Q: ?Sized + Eq + std::hash::Hash> GetIndex<&Q, V>
    for HashMap<K, V>
{
    fn get<'a>(&'a self, key: &Q) -> Option<&'a V> {
        HashMap::get(self, key)
    }
}

impl<I: serde_json::value::Index> GetIndex<I, serde_json::Value> for serde_json::Value {
    fn get(&self, key: I) -> Option<&serde_json::Value> {
        self.get(key)
    }
}

fn maybe_fill_value<'a, 'b, M: GetIndex<&'b str, serde_json::Value>>(
    values: &'a Option<&'a M>,
    name: &'b str,
    default_value: Option<&'a str>,
) -> &'a str {
    values
        .and_then(|values| values.get(name))
        .and_then(serde_json::Value::as_str)
        .or(default_value)
        .unwrap_or("")
}

#[render::component]
pub fn MaybeFillInput<'a, M: GetIndex<&'a str, serde_json::Value>>(
    values: &'a Option<&'a M>,
    r#type: &'a str,
    name: &'a str,
    required: bool,
    id: &'a str,
) {
    let value = maybe_fill_value(values, name, None);
    if required {
        render::rsx! {
            <input
                r#type
                name
                value
                id
                required={""}
            />
        }
    } else {
        render::rsx! {
            <input
                r#type
                name
                value
                id
            />
        }
    }
}

#[render::component]
pub fn MaybeFillTextArea<'a, M: GetIndex<&'a str, serde_json::Value>>(
    values: &'a Option<&'a M>,
    name: &'a str,
    default_value: Option<&'a str>,
) {
    render::rsx! {
        <textarea name>
            {maybe_fill_value(values, name, default_value)}
        </textarea>
    }
}

#[render::component]
pub fn BoolSubmitButton<'a>(value: bool, do_text: &'a str, done_text: &'a str) {
    if value {
        render::rsx! {
            <button disabled={""}>{done_text}</button>
        }
    } else {
        render::rsx! {
            <button type={"submit"}>{do_text}</button>
        }
    }
}

pub struct NotificationItem<'a> {
    pub notification: &'a RespNotification<'a>,
    pub lang: &'a crate::Translator,
}

impl<'a> render::Render for NotificationItem<'a> {
    fn render_into<W: std::fmt::Write>(self, writer: &mut W) -> std::fmt::Result {
        let lang = self.lang;

        write!(writer, "<li class=\"notification-item")?;
        if self.notification.unseen {
            write!(writer, " unread")?;
        }
        write!(writer, "\">")?;
        match &self.notification.info {
            RespNotificationInfo::Unknown => {
                "[unknown notification type]".render_into(writer)?;
            }
            RespNotificationInfo::PostReply { reply, post } => {
                (render::rsx! {
                    <>
                        <a href={format!("/comments/{}", reply.id)}>{lang.tr("comment", None)}</a>
                        {" "}{lang.tr("on_your_post", None)}{" "}<a href={format!("/posts/{}", post.id)}>{post.title.as_ref()}</a>{":"}
                        <Content src={reply} />
                    </>
                }).render_into(writer)?;
            }
            RespNotificationInfo::CommentReply {
                reply,
                comment,
                post,
            } => {
                (render::rsx! {
                    <>
                        {lang.tr("reply_to", None)}
                        {" "}
                        <a href={format!("/comments/{}", comment)}>{lang.tr("your_comment", None)}</a>
                        {
                            if let Some(post) = post {
                                Some(render::rsx! { <>{" "}{lang.tr("on", None)}{" "}<a href={format!("/posts/{}", post.id)}>{post.title.as_ref()}</a></> })
                            } else {
                                None
                            }
                        }
                        {":"}
                        <Content src={reply} />
                    </>
                }).render_into(writer)?;
            }
        }

        write!(writer, "</li>")
    }
}

pub trait IconExt {
    fn img(&self) -> render::SimpleElement<()>;
}

impl IconExt for hitide_icons::Icon {
    fn img(&self) -> render::SimpleElement<()> {
        render::rsx! { <img src={format!("/static/{}", self.path)} class={"icon"} /> }
    }
}