Skip to content

Commit

Permalink
Temporary Sanity newsroom #2659 (#2661)
Browse files Browse the repository at this point in the history
* 🎨 sanity newsroom

* 🎨 fix direction

* 🎨 add norwegian route
  • Loading branch information
BorghildSelle authored Nov 7, 2024
1 parent 054b875 commit 2df4b0e
Show file tree
Hide file tree
Showing 11 changed files with 532 additions and 74 deletions.
4 changes: 2 additions & 2 deletions web/lib/queries/magazine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -95,11 +95,11 @@ export const allMagazineDocuments = /* groq */ `

//&& (${publishDateTimeQuery} < $lastPublishedAt || (${publishDateTimeQuery} == $lastPublishedAt && _id < $lastId))
const prevDirectionFilter = /* groq */ `
&& (${publishDateTimeQuery} < $lastPublishedAt || (${publishDateTimeQuery} == $lastPublishedAt && _id < $lastId))
&& (${publishDateTimeQuery} > $lastPublishedAt || (${publishDateTimeQuery} == $lastPublishedAt && _id > $lastId))
`
//&& (${publishDateTimeQuery} > $lastPublishedAt || (${publishDateTimeQuery} == $lastPublishedAt && _id > $lastId))
const nextDirectionFilter = /* groq */ `
&& (${publishDateTimeQuery} > $lastPublishedAt || (${publishDateTimeQuery} == $lastPublishedAt && _id > $lastId))
&& (${publishDateTimeQuery} < $lastPublishedAt || (${publishDateTimeQuery} == $lastPublishedAt && _id < $lastId))
`

export const getMagazineArticlesByTag = (hasFirstId = false, hasLastId = false) => /* groq */ `
Expand Down
57 changes: 56 additions & 1 deletion web/lib/queries/newsroom.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import linkSelectorFields, { linkReferenceFields } from './common/actions/linkSelectorFields'
import markDefs from './common/blockEditorMarks'
import { sameLang } from './common/langAndDrafts'
import { noDrafts, sameLang } from './common/langAndDrafts'
import { ingressForNewsQuery } from './common/newsSubqueries'
import { publishDateTimeQuery } from './common/publishDateTime'
import { seoAndSomeFields } from './common/seoAndSomeFields'
import slugsForNewsAndMagazine from './slugsForNewsAndMagazine'

export const newsroomQuery = /* groq */ `
*[_type == "newsroom" && ${sameLang}] {
Expand All @@ -22,3 +25,55 @@ export const newsroomQuery = /* groq */ `
backgroundImage,
"fallbackImages": imageThumbnailFallbacks[]{...}
}`

const prevDirectionFilter = /* groq */ `
&& (${publishDateTimeQuery} > $lastPublishedAt || (${publishDateTimeQuery} == $lastPublishedAt && _id > $lastId))
`

const nextDirectionFilter = /* groq */ `
&& (${publishDateTimeQuery} < $lastPublishedAt || (${publishDateTimeQuery} == $lastPublishedAt && _id < $lastId))
`

export const allNewsDocuments = /* groq */ `
*[_type == "news" && ${sameLang} && ${noDrafts} ] | order(${publishDateTimeQuery} desc)[0...30] {
"id": _id,
"updatedAt": _updatedAt,
title,
heroImage,
"slug": slug.current,
"tags":tags[]->{
"key": key.current,
"label":title[$lang],
},
"countryTags":countryTags[]->{
"key": key.current,
"label":title[$lang],
},
"publishDateTime": ${publishDateTimeQuery},
${slugsForNewsAndMagazine},
${ingressForNewsQuery},
}`

export const getNewsArticlesByPage = (hasFirstId = false, hasLastId = false) => /* groq */ `
*[_type == 'news' && ${sameLang} && ${noDrafts}
${hasLastId ? nextDirectionFilter : ''}
${hasFirstId ? prevDirectionFilter : ''}
] | order(${publishDateTimeQuery} desc)[0...30]{
"id": _id,
"updatedAt": _updatedAt,
"slug": slug.current,
title,
heroImage,
"tags":tags[]->{
"key": key.current,
"label":title[$lang],
},
"countryTags":countryTags[]->{
"key": key.current,
"label":title[$lang],
},
"publishDateTime": ${publishDateTimeQuery},
${slugsForNewsAndMagazine},
${ingressForNewsQuery},
}
`
21 changes: 21 additions & 0 deletions web/pages/api/news/next.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import { NextApiRequest, NextApiResponse } from 'next'
import { getNameFromLocale } from '../../../lib/localization'
import { sanityClient } from '../../../lib/sanity.server'
import { getNewsArticlesByPage } from '../../../lib/queries/newsroom'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const lang = req.query.lang === 'no' ? getNameFromLocale('no') : getNameFromLocale('en') // Defaults to 'en' if the lang parameter is not 'no'

console.log('get next from req.query.lastId', req.query.lastId)
console.log('get next from req.query.lastPublishedAt', req.query.lastPublishedAt)
try {
const news = await sanityClient.fetch(getNewsArticlesByPage(false, true), {
lang,
lastId: req.query.lastId,
lastPublishedAt: req.query.lastPublishedAt,
})
res.status(200).json({ news: news })
} catch (err) {
res.status(500).json({ error: 'Failed to fetch news' })
}
}
19 changes: 19 additions & 0 deletions web/pages/api/news/prev.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { NextApiRequest, NextApiResponse } from 'next'
import { getNameFromLocale } from '../../../lib/localization'
import { sanityClient } from '../../../lib/sanity.server'
import { getNewsArticlesByPage } from '../../../lib/queries/newsroom'

export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const lang = req.query.lang === 'no' ? getNameFromLocale('no') : getNameFromLocale('en') // Defaults to 'en' if the lang parameter is not 'no'

try {
const news = await sanityClient.fetch(getNewsArticlesByPage(true, false), {
lang,
lastId: req.query.lastId,
lastPublishedAt: req.query.lastPublishedAt,
})
res.status(200).json({ news: news })
} catch (err) {
res.status(500).json({ error: 'Failed to fetch news' })
}
}
54 changes: 19 additions & 35 deletions web/pages/news/index.global.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,29 @@
import { GetServerSideProps } from 'next'
import { InstantSearchSSRProvider, getServerState } from 'react-instantsearch'
import type { AppProps } from 'next/app'
import { IntlProvider } from 'react-intl'
import Footer from '../../pageComponents/shared/Footer'
import Header from '../../pageComponents/shared/Header'
import { newsroomQuery } from '../../lib/queries/newsroom'
import { allNewsDocuments, newsroomQuery } from '../../lib/queries/newsroom'
import getIntl from '../../common/helpers/getIntl'
import { getNameFromLocale, getIsoFromLocale } from '../../lib/localization'
import { defaultLanguage } from '../../languages'
import { AlgoliaIndexPageType, NewsRoomPageType } from '../../types'
import { getComponentsData } from '../../lib/fetchData'
import { renderToString } from 'react-dom/server'
import NewsRoomTemplate from '@templates/newsroom/Newsroom'
import { getComponentsData, getData } from '../../lib/fetchData'
import NewsRoomTemplateSanity from '@templates/newsroom/sanity/NewsroomSanity'

export default function NewsRoom({ isServerRendered = false, serverState, data, url }: AlgoliaIndexPageType) {
export default function NewsRoom({ data }: AlgoliaIndexPageType) {
const defaultLocale = defaultLanguage.locale
const { pageData, slug, intl } = data
const locale = data?.intl?.locale || defaultLocale

return (
<InstantSearchSSRProvider {...serverState}>
<IntlProvider
locale={getIsoFromLocale(locale)}
defaultLocale={getIsoFromLocale(defaultLocale)}
messages={intl?.messages}
>
<NewsRoomTemplate
isServerRendered={isServerRendered}
locale={locale}
pageData={pageData as NewsRoomPageType}
slug={slug}
url={url}
/>
</IntlProvider>
</InstantSearchSSRProvider>
<IntlProvider
locale={getIsoFromLocale(locale)}
defaultLocale={getIsoFromLocale(defaultLocale)}
messages={intl?.messages}
>
<NewsRoomTemplateSanity locale={locale} pageData={pageData as NewsRoomPageType} slug={slug} />
</IntlProvider>
)
}

Expand Down Expand Up @@ -97,28 +87,22 @@ export const getServerSideProps: GetServerSideProps = async ({ req, preview = fa

console.log(JSON.stringify(req.headers))
const url = new URL(req.headers.referer || `https://${req.headers.host}${req.url}`).toString()
const serverState = await getServerState(
<NewsRoom
isServerRendered
data={{
intl,
pageData,
slug,
}}
url={url}
/>,
{ renderToString },
)
const { data } = await getData({
query: allNewsDocuments,
queryParams,
})

return {
props: {
serverState,
url,
data: {
menuData,
footerData,
intl,
pageData,
pageData: {
...pageData,
newsArticles: data,
},
slug,
},
},
Expand Down
55 changes: 19 additions & 36 deletions web/pages/nyheter/index.global.tsx
Original file line number Diff line number Diff line change
@@ -1,39 +1,29 @@
import { GetServerSideProps } from 'next'
import { InstantSearchSSRProvider, getServerState } from 'react-instantsearch'
import type { AppProps } from 'next/app'
import { IntlProvider } from 'react-intl'
import Footer from '../../pageComponents/shared/Footer'
import Header from '../../pageComponents/shared/Header'
import { newsroomQuery } from '../../lib/queries/newsroom'
import { allNewsDocuments, newsroomQuery } from '../../lib/queries/newsroom'
import getIntl from '../../common/helpers/getIntl'
import { getNameFromLocale, getIsoFromLocale } from '../../lib/localization'
import { defaultLanguage } from '../../languages'
import { AlgoliaIndexPageType, NewsRoomPageType } from '../../types'
import { getComponentsData } from '../../lib/fetchData'
import { renderToString } from 'react-dom/server'
import NewsRoomTemplate from '@templates/newsroom/Newsroom'
import { getComponentsData, getData } from '../../lib/fetchData'
import NewsRoomTemplateSanity from '@templates/newsroom/sanity/NewsroomSanity'

export default function NorwegianNewsRoom({ isServerRendered = false, serverState, data, url }: AlgoliaIndexPageType) {
export default function NorwegianNewsRoom({ data, url }: AlgoliaIndexPageType) {
const defaultLocale = defaultLanguage.locale
const { pageData, slug, intl } = data
const locale = intl?.locale || defaultLocale

return (
<InstantSearchSSRProvider {...serverState}>
<IntlProvider
locale={getIsoFromLocale(locale)}
defaultLocale={getIsoFromLocale(defaultLocale)}
messages={intl?.messages}
>
<NewsRoomTemplate
isServerRendered={isServerRendered}
locale={locale}
pageData={pageData as NewsRoomPageType}
slug={slug}
url={url}
/>
</IntlProvider>
</InstantSearchSSRProvider>
<IntlProvider
locale={getIsoFromLocale(locale)}
defaultLocale={getIsoFromLocale(defaultLocale)}
messages={intl?.messages}
>
<NewsRoomTemplateSanity locale={locale} pageData={pageData as NewsRoomPageType} slug={slug} url={url} />
</IntlProvider>
)
}

Expand Down Expand Up @@ -93,30 +83,23 @@ export const getServerSideProps: GetServerSideProps = async ({ req, preview = fa
},
preview,
)

const serverState = await getServerState(
<NorwegianNewsRoom
isServerRendered
data={{
intl,
pageData,
slug,
}}
url={url}
/>,
{ renderToString },
)
const { data } = await getData({
query: allNewsDocuments,
queryParams,
})

return {
props: {
locale,
serverState,
url,
data: {
menuData,
footerData,
intl,
pageData,
pageData: {
...pageData,
newsArticles: data,
},
slug,
},
},
Expand Down
77 changes: 77 additions & 0 deletions web/templates/newsroom/sanity/NewsHeadlinerSanity.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import { FormattedDate } from '@components/FormattedDateTime'
import { forwardRef, HTMLAttributes } from 'react'
import { BaseLink } from '@core/Link'
import { Typography } from '@core/Typography'
import Image, { Ratios } from '../../../pageComponents/shared/SanityImage'
import envisTwMerge from '../../../twMerge'
import { NewsRoomNewsItem } from '../../../types/algoliaIndexPage'
import { SanityImageObject } from '@sanity/image-url/lib/types/types'
import Blocks from '../../../pageComponents/shared/portableText/Blocks'

export type NewsHeadlinerProps = {
data: NewsRoomNewsItem
fallbackImage?: SanityImageObject
} & HTMLAttributes<HTMLLIElement>

const NewsHeadlinerSanity = forwardRef<HTMLLIElement, NewsHeadlinerProps>(function NewsHeadlinerSanity(
{ data, fallbackImage, className = '', ...rest },
ref,
) {
const { slug, title, ingress, publishDateTime, heroImage, tags, countryTags } = data

return (
<section ref={ref} {...rest} className={envisTwMerge('', className)}>
<BaseLink href={slug} className="group flex flex-col gap-2 pb-6">
{(heroImage?.image?.asset || fallbackImage) && (
<div className="aspect-video relative max-h-[324px] mb-2">
<Image
//@ts-ignore: TODO Fix SanityImage to take SanityImageObject
image={heroImage?.image?.asset ? heroImage?.image : fallbackImage}
fill
priority
aspectRatio={Ratios.NINE_TO_SIXTEEN}
sizes="(max-width: 800px) 100vw, 1440px"
className="rounded-xs"
aria-hidden
/>
</div>
)}
{publishDateTime && (
<FormattedDate datetime={publishDateTime} uppercase className="pt-4 text-2xs font-normal leading-normal" />
)}
{title && (
<Typography as="h2" variant="lg" className="pb-6 group-hover:underline">
{title}
</Typography>
)}
<div className="pb-2 flex gap-3 text-xs divide-x-2 divide-energy-red-100">
{tags?.map((tag: any, i: number) => {
return (
<span key={tag.label} className=" text-xs inline-block text-grey-60 pl-3 pr-3 first:pl-0">
{tag.label}
{i < tags.length - 1 && <span className="sr-only">,</span>}
</span>
)
})}
{countryTags?.length > 0 && <span className="sr-only">,</span>}
{countryTags?.map((country: any, i: number) => {
return (
<span key={country.label} className=" inline-block text-grey-60 pl-3 pr-3 first:pl-0">
{country.label}
{i < countryTags.length - 1 && <span className="sr-only">,</span>}
</span>
)
})}
</div>
{Array.isArray(ingress) ? (
<Blocks value={ingress} className="text-sm max-w-prose" />
) : (
<Typography variant="body" className="text-sm max-w-prose`">
{ingress}
</Typography>
)}
</BaseLink>
</section>
)
})
export default NewsHeadlinerSanity
Loading

0 comments on commit 2df4b0e

Please sign in to comment.