stacker.news/components/link-form.js

234 lines
7.3 KiB
JavaScript
Raw Normal View History

2023-05-06 15:54:04 +00:00
import { useState, useEffect } from 'react'
2021-08-11 20:13:10 +00:00
import { Form, Input, SubmitButton } from '../components/form'
import { useRouter } from 'next/router'
2022-04-19 18:32:39 +00:00
import { gql, useApolloClient, useLazyQuery, useMutation } from '@apollo/client'
2021-08-11 20:34:10 +00:00
import Countdown from './countdown'
2023-02-08 19:38:04 +00:00
import AdvPostForm, { AdvPostInitial } from './adv-post-form'
2021-10-28 20:49:51 +00:00
import { ITEM_FIELDS } from '../fragments/items'
import Item from './item'
import AccordianItem from './accordian-item'
2022-08-18 18:15:24 +00:00
import FeeButton, { EditFeeButton } from './fee-button'
2023-01-12 23:53:09 +00:00
import Delete from './delete'
2023-07-24 18:35:05 +00:00
import Button from 'react-bootstrap/Button'
2023-02-08 19:38:04 +00:00
import { linkSchema } from '../lib/validate'
2023-04-01 03:07:04 +00:00
import Moon from '../svgs/moon-fill.svg'
2023-05-11 00:26:07 +00:00
import { SubSelectInitial } from './sub-select-form'
2023-06-12 19:34:10 +00:00
import CancelButton from './cancel-button'
2021-08-11 20:13:10 +00:00
2023-05-11 00:26:07 +00:00
export function LinkForm ({ item, sub, editThreshold, children }) {
2021-10-28 20:49:51 +00:00
const router = useRouter()
2022-04-19 18:32:39 +00:00
const client = useApolloClient()
2023-02-08 19:38:04 +00:00
const schema = linkSchema(client)
Service worker rework, Web Target Share API & Web Push API (#324) * npm uninstall next-pwa next-pwa was last updated in August 2022. There is also an issue which mentions that next-pwa is abandoned (?): https://github.com/shadowwalker/next-pwa/issues/482 But the main reason for me uninstalling it is that it adds a lot of preconfigured stuff which is not necessary for us. It even lead to a bug since pages were cached without our knowledge. So I will go with a different PWA approach. This different approach should do the following: - make it more transparent what the service worker is doing - gives us more control to configure the service worker and thus making it easier * Use workbox-webpack-plugin Every other plugin (`next-offline`, `next-workbox-webpack-plugin`, `next-with-workbox`, ...) added unnecessary configuration which felt contrary to how PWAs should be built. (PWAs should progressivly enhance the website in small steps, see https://web.dev/learn/pwa/getting-started/#focus-on-a-feature) These default configurations even lead to worse UX since they made invalid assumptions about stacker.news: We _do not_ want to cache our start url and we _do not_ want to cache anything unless explicitly told to. Almost every page on SN should be fresh for the best UX. To achieve this, by default, the service worker falls back to the network (as if the service worker wasn't there). Therefore, this should be the simplest configuration with a valid precache and cache busting support. In the future, we can try to use prefetching to improve performance of navigation requests. * Add support for Web Share Target API See https://developer.chrome.com/articles/web-share-target/ * Use Web Push API for push notifications I followed this (very good!) guide: https://web.dev/notifications/ * Refactor code related to Web Push * Send push notification to users on events * Merge notifications * Send notification to author of every parent recursively * Remove unused userId param in savePushSubscription As it should be, the user id is retrieved from the authenticated user in the backend. * Resubscribe user if push subscription changed * Update old subscription if oldEndpoint was given * Allow users to unsubscribe * Use LTREE operator instead of recursive query * Always show checkbox for push notifications * Justify checkbox to end * Update title of first push notification * Fix warning from uncontrolled to controlled * Add comment about Notification.requestPermission * Fix timestamp * Catch error on push subscription toggle * Wrap function bodies in try/catch * Use Promise.allSettled * Filter subscriptions by user notification settings * Fix user notification filter * Use skipWaiting --------- Co-authored-by: ekzyis <ek@stacker.news>
2023-07-04 19:36:07 +00:00
// if Web Share Target API was used
const shareUrl = router.query.url
const shareTitle = router.query.title
2021-10-28 20:49:51 +00:00
2023-01-12 18:05:47 +00:00
const [getPageTitleAndUnshorted, { data }] = useLazyQuery(gql`
query PageTitleAndUnshorted($url: String!) {
pageTitleAndUnshorted(url: $url) {
title
unshorted
}
}`)
const [getDupes, { data: dupesData, loading: dupesLoading }] = useLazyQuery(gql`
${ITEM_FIELDS}
query Dupes($url: String!) {
dupes(url: $url) {
...ItemFields
}
}`, {
2023-04-01 03:27:49 +00:00
onCompleted: () => setPostDisabled(false)
2021-10-28 20:49:51 +00:00
})
2023-01-12 20:30:17 +00:00
const [getRelated, { data: relatedData }] = useLazyQuery(gql`
${ITEM_FIELDS}
query related($title: String!) {
related(title: $title, minMatch: "75%", limit: 3) {
items {
...ItemFields
}
2023-01-12 20:30:17 +00:00
}
}`)
2023-01-12 20:30:17 +00:00
const related = []
for (const item of relatedData?.related?.items || []) {
let found = false
for (const ditem of dupesData?.dupes || []) {
if (ditem.id === item.id) {
found = true
break
}
}
if (!found) {
related.push(item)
}
}
2021-10-28 20:49:51 +00:00
const [upsertLink] = useMutation(
2021-08-11 20:13:10 +00:00
gql`
2023-05-01 20:58:30 +00:00
mutation upsertLink($sub: String, $id: ID, $title: String!, $url: String!, $boost: Int, $forward: String) {
upsertLink(sub: $sub, id: $id, title: $title, url: $url, boost: $boost, forward: $forward) {
2021-08-11 20:13:10 +00:00
id
}
}`
)
2021-10-28 20:49:51 +00:00
2023-05-06 15:54:04 +00:00
useEffect(() => {
if (data?.pageTitleAndUnshorted?.title) {
setTitleOverride(data.pageTitleAndUnshorted.title)
}
}, [data?.pageTitleAndUnshorted?.title])
useEffect(() => {
if (data?.pageTitleAndUnshorted?.unshorted) {
getDupes({
variables: { url: data?.pageTitleAndUnshorted?.unshorted }
})
}
}, [data?.pageTitleAndUnshorted?.unshorted])
2023-04-01 03:27:49 +00:00
const [postDisabled, setPostDisabled] = useState(false)
2023-05-06 15:54:04 +00:00
const [titleOverride, setTitleOverride] = useState()
2023-04-01 03:27:49 +00:00
2021-08-11 20:13:10 +00:00
return (
<Form
initial={{
Service worker rework, Web Target Share API & Web Push API (#324) * npm uninstall next-pwa next-pwa was last updated in August 2022. There is also an issue which mentions that next-pwa is abandoned (?): https://github.com/shadowwalker/next-pwa/issues/482 But the main reason for me uninstalling it is that it adds a lot of preconfigured stuff which is not necessary for us. It even lead to a bug since pages were cached without our knowledge. So I will go with a different PWA approach. This different approach should do the following: - make it more transparent what the service worker is doing - gives us more control to configure the service worker and thus making it easier * Use workbox-webpack-plugin Every other plugin (`next-offline`, `next-workbox-webpack-plugin`, `next-with-workbox`, ...) added unnecessary configuration which felt contrary to how PWAs should be built. (PWAs should progressivly enhance the website in small steps, see https://web.dev/learn/pwa/getting-started/#focus-on-a-feature) These default configurations even lead to worse UX since they made invalid assumptions about stacker.news: We _do not_ want to cache our start url and we _do not_ want to cache anything unless explicitly told to. Almost every page on SN should be fresh for the best UX. To achieve this, by default, the service worker falls back to the network (as if the service worker wasn't there). Therefore, this should be the simplest configuration with a valid precache and cache busting support. In the future, we can try to use prefetching to improve performance of navigation requests. * Add support for Web Share Target API See https://developer.chrome.com/articles/web-share-target/ * Use Web Push API for push notifications I followed this (very good!) guide: https://web.dev/notifications/ * Refactor code related to Web Push * Send push notification to users on events * Merge notifications * Send notification to author of every parent recursively * Remove unused userId param in savePushSubscription As it should be, the user id is retrieved from the authenticated user in the backend. * Resubscribe user if push subscription changed * Update old subscription if oldEndpoint was given * Allow users to unsubscribe * Use LTREE operator instead of recursive query * Always show checkbox for push notifications * Justify checkbox to end * Update title of first push notification * Fix warning from uncontrolled to controlled * Add comment about Notification.requestPermission * Fix timestamp * Catch error on push subscription toggle * Wrap function bodies in try/catch * Use Promise.allSettled * Filter subscriptions by user notification settings * Fix user notification filter * Use skipWaiting --------- Co-authored-by: ekzyis <ek@stacker.news>
2023-07-04 19:36:07 +00:00
title: item?.title || shareTitle || '',
url: item?.url || shareUrl || '',
2023-05-11 00:26:07 +00:00
...AdvPostInitial({ forward: item?.fwdUser?.name }),
...SubSelectInitial({ sub: item?.subName || sub?.name })
2021-08-11 20:13:10 +00:00
}}
2023-02-08 19:38:04 +00:00
schema={schema}
2022-07-13 15:49:55 +00:00
onSubmit={async ({ boost, title, ...values }) => {
const { error } = await upsertLink({
2023-05-05 17:38:56 +00:00
variables: { sub: item?.subName || sub?.name, id: item?.id, boost: boost ? Number(boost) : undefined, title: title.trim(), ...values }
})
2021-08-11 20:13:10 +00:00
if (error) {
throw new Error({ message: error.toString() })
}
2022-01-07 16:50:41 +00:00
if (item) {
2022-03-10 18:25:16 +00:00
await router.push(`/items/${item.id}`)
2022-01-07 16:50:41 +00:00
} else {
const prefix = sub?.name ? `/~${sub.name}` : ''
2023-05-01 20:58:30 +00:00
await router.push(prefix + '/recent')
2022-01-07 16:50:41 +00:00
}
2021-08-11 20:13:10 +00:00
}}
2022-01-07 18:28:23 +00:00
storageKeyPrefix={item ? undefined : 'link'}
2021-08-11 20:13:10 +00:00
>
2023-05-11 00:26:07 +00:00
{children}
2021-08-11 20:13:10 +00:00
<Input
label='title'
name='title'
2023-05-06 15:54:04 +00:00
overrideValue={titleOverride}
2021-08-11 20:13:10 +00:00
required
2022-08-25 18:46:07 +00:00
clear
2023-01-12 20:30:17 +00:00
onChange={async (formik, e) => {
if (e.target.value) {
getRelated({
variables: { title: e.target.value }
})
}
2023-05-06 15:54:04 +00:00
if (e.target.value === e.target.value.toUpperCase()) {
setTitleOverride(e.target.value.replace(/\w\S*/g, txt =>
txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase()))
}
2023-01-12 20:30:17 +00:00
}}
2021-08-11 20:13:10 +00:00
/>
<Input
label='url'
name='url'
required
autoFocus
2022-08-25 18:46:07 +00:00
clear
autoComplete='off'
2023-01-12 18:05:47 +00:00
overrideValue={data?.pageTitleAndUnshorted?.unshorted}
2021-08-11 20:13:10 +00:00
hint={editThreshold
2023-07-24 18:35:05 +00:00
? <div className='text-muted fw-bold'><Countdown date={editThreshold} /></div>
2021-08-11 20:13:10 +00:00
: null}
2021-08-22 15:25:17 +00:00
onChange={async (formik, e) => {
if ((/^ *$/).test(formik?.values.title)) {
2023-01-12 18:05:47 +00:00
getPageTitleAndUnshorted({
2021-08-22 15:25:17 +00:00
variables: { url: e.target.value }
})
} else {
client.cache.modify({
fields: {
pageTitleAndUnshorted () {
return null
}
}
})
2021-08-22 15:25:17 +00:00
}
2023-04-01 03:27:49 +00:00
if (e.target.value) {
setPostDisabled(true)
setTimeout(() => setPostDisabled(false), 3000)
2023-04-01 03:21:05 +00:00
getDupes({
variables: { url: e.target.value }
})
2023-04-01 03:27:49 +00:00
}
2021-08-22 15:25:17 +00:00
}}
2021-08-11 20:13:10 +00:00
/>
2022-08-18 18:15:24 +00:00
<AdvPostForm edit={!!item} />
2022-08-10 15:06:31 +00:00
<div className='mt-3'>
{item
2023-01-12 23:53:09 +00:00
? (
<div className='d-flex justify-content-between'>
<Delete itemId={item.id} onDelete={() => router.push(`/items/${item.id}`)}>
<Button variant='grey-medium'>delete</Button>
</Delete>
<div className='d-flex'>
2023-06-12 19:34:10 +00:00
<CancelButton />
<EditFeeButton
paidSats={item.meSats}
parentId={null} text='save' ChildButton={SubmitButton} variant='secondary'
/>
</div>
2023-01-12 23:53:09 +00:00
</div>)
: (
<div className='d-flex align-items-center'>
<FeeButton
baseFee={1} parentId={null} text='post' disabled={postDisabled}
ChildButton={SubmitButton} variant='secondary'
/>
{dupesLoading &&
2023-07-24 18:35:05 +00:00
<div className='d-flex ms-3 justify-content-center'>
<Moon className='spin fill-grey' />
2023-07-24 18:35:05 +00:00
<div className='ms-2 text-muted' style={{ fontWeight: '600' }}>searching for dupes</div>
</div>}
</div>
)}
2022-08-10 15:06:31 +00:00
</div>
2023-01-12 23:53:09 +00:00
{!item &&
<>
{dupesData?.dupes?.length > 0 &&
<div className='mt-3'>
<AccordianItem
show
headerColor='#c03221'
header={<div style={{ fontWeight: 'bold', fontSize: '92%' }}>dupes</div>}
body={
<div>
{dupesData.dupes.map((item, i) => (
<Item item={item} key={item.id} />
))}
</div>
2021-10-28 20:49:51 +00:00
}
2023-01-12 23:53:09 +00:00
/>
</div>}
<div className={`mt-3 ${related.length > 0 ? '' : 'invisible'}`}>
<AccordianItem
header={<div style={{ fontWeight: 'bold', fontSize: '92%' }}>similar</div>}
body={
<div>
{related.map((item, i) => (
<Item item={item} key={item.id} />
))}
</div>
2023-01-12 20:30:17 +00:00
}
2023-01-12 23:53:09 +00:00
/>
</div>
</>}
2021-08-11 20:13:10 +00:00
</Form>
)
}